<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="规则名称" prop="ruleName">
        <el-input
          v-model="queryParams.ruleName"
          placeholder="请输入规则名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="启用" :value="1" />
          <el-option label="停用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="assignRuleList" border>
      <el-table-column label="规则名称" align="center" prop="ruleName" />
      <el-table-column label="分配类型" align="center" prop="assignType">
        <template slot-scope="scope">
          <span v-if="scope.row.assignType === 1">轮询</span>
          <span v-else-if="scope.row.assignType === 2">依次</span>
          <span v-else-if="scope.row.assignType === 3">按权重</span>
        </template>
      </el-table-column>
      <el-table-column label="员工数" align="center" prop="qwAssignRuleUsers">
        <template slot-scope="scope">
          {{ scope.row.qwAssignRuleUsers && Array.isArray(scope.row.qwAssignRuleUsers) ? scope.row.qwAssignRuleUsers.length : 0 }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="280px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleStatusChange(scope.row)"
          >{{ scope.row.status === 1 ? '停用' : '启用' }}</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDetails(scope.row)"
          >分配详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改分配规则对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="form.ruleName" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="分配类型" prop="assignType">
          <el-radio-group v-model="form.assignType">
            <el-radio :label="3">按权重</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择员工" prop="qwAssignRuleUsers" style="margin-top: 2%">
          <div>
            <el-button
              size="medium"
              icon="el-icon-circle-plus-outline"
              plain
              @click="handleSelectUser">请选择使用员工</el-button>
          </div>
          <div style="margin-top: 10px;">
            <el-table :data="personnelList" border size="small" style="margin-top: 10px;">
              <el-table-column label="企微号" align="center" prop="qwUserId" width="120px" />
              <el-table-column label="企微姓名" align="center" prop="qwUserName" width="120px" />
              <el-table-column label="权重数" align="center" width="100px">
                <template slot-scope="scope">
                  <el-input v-model.number="scope.row.weight" type="number" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="80px">
                <template slot-scope="scope">
                  <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleRemovePersonnel(scope.row)"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配详情对话框 -->
    <el-dialog title="分配详情" :visible.sync="detailsOpen" width="900px" append-to-body>
      <el-table :data="detailsPersonnelList" border style="margin-bottom: 20px;">
        <el-table-column label="企微号" align="center" prop="qwUserId" />
        <el-table-column label="企微姓名" align="center" prop="qwUserName" />
        <el-table-column label="权重数" align="center" prop="weight" />
        <el-table-column label="今日分配数" align="center" prop="assignNumToDay" />
        <el-table-column label="累积分配数" align="center" prop="assignNumCount" />
        <el-table-column label="今日添加数" align="center" prop="addNumToDay" />
        <el-table-column label="累积添加数" align="center" prop="addNumCount" />
      </el-table>
    </el-dialog>

    <!-- 选择员工对话框 -->
    <el-dialog :title="selectUserDialog.title" :visible.sync="selectUserDialog.open" width="1300px" append-to-body>
      <qwUserList ref="QwUserList" @selectUserList="selectUserList"></qwUserList>
    </el-dialog>
  </div>
</template>

<script>
import { listAssignRule, getAssignRule, addOrUpdateAssignRule, enableAssignRule } from "@/api/qw/assignRule";
import qwUserList from '@/views/qw/user/qwUserList.vue'

export default {
  name: "AssignRule",
  components: { qwUserList },
  data() {
    return {
      loading: true,
      showSearch: true,
      total: 0,
      assignRuleList: [],
      title: "",
      open: false,
      detailsOpen: false,
      detailsPersonnelList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ruleName: null,
        status: null,
      },
      form: {
        assignType: 3,
        qwAssignRuleUsers: null
      },
      personnelList: [],
      selectUserDialog: {
        title: "选择员工",
        open: false
      },
      rules: {
        ruleName: [
          { required: true, message: "规则名称不能为空", trigger: "blur" }
        ]
      },

    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询分配规则列表 */
    getList() {
      this.loading = true;
      listAssignRule(this.queryParams).then(response => {
        this.assignRuleList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    // ... existing code ...

    /** 新增按钮 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增分配规则";
    },

    /** 修改按钮 */
    handleUpdate(row) {
      this.reset();
      this.open = true;
      this.title = "修改分配规则";
      getAssignRule(row.id).then(response => {
        this.form = response.data;
        if (this.form.qwAssignRuleUsers && Array.isArray(this.form.qwAssignRuleUsers)) {
          this.personnelList = this.form.qwAssignRuleUsers;
        }
      });
    },

    /** 启用/停用 */
    handleStatusChange(row) {
      const status = row.status === 1 ? 0 : 1;
      const statusText = status === 1 ? "启用" : "停用";
      this.$confirm(`确认要${statusText}该分配规则吗？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        enableAssignRule(row.id, status).then(response => {
          this.msgSuccess(`${statusText}成功`);
          this.getList();
        });
      }).catch(() => {});
    },

    /** 分配详情 */
    handleDetails(row) {
      if (row.qwAssignRuleUsers && Array.isArray(row.qwAssignRuleUsers)) {
        this.detailsPersonnelList = row.qwAssignRuleUsers;
      } else {
        this.detailsPersonnelList = [];
      }
      this.detailsOpen = true;
    },

    /** 选择员工 */
    handleSelectUser() {
      this.selectUserDialog.open = true;
      this.$nextTick(() => {
        this.$refs.QwUserList.getDetails(null, null, null, null);
      });
    },

    /** 接收选中的员工 */
    selectUserList(selectUsers) {
      this.selectUserDialog.open = false;
      if (selectUsers && selectUsers.length > 0) {
        selectUsers.forEach(user => {
          const exists = this.personnelList.find(p => p.sysQwUserId === user.id);
          if (!exists) {
            this.personnelList.push({
              assignId: this.form.id || null,
              sysQwUserId: user.id,
              qwUserName: user.qwUserName,
              qwUserId: user.qwUserId,
              weight: 1,
              assignNumToDay: 0,
              assignNumCount: 0,
              addNumToDay: 0,
              addNumCount: 0
            });
          }
        });
      }
    },

    /** 移除员工 */
    handleRemovePersonnel(item) {
      const index = this.personnelList.findIndex(p => p.qwUserId === item.qwUserId);
      if (index > -1) {
        this.personnelList.splice(index, 1);
      }
    },

    /** 表单提交 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.personnelList.length === 0) {
            this.$message.error("请选择至少一个员工");
            return;
          }
          // 准备发送的数据，包含 weight
          const submitPersonnelList = this.personnelList.map(p => ({
            assignId: this.form.id || null,
            sysQwUserId: p.sysQwUserId,
            qwUserName: p.qwUserName,
            qwUserId: p.qwUserId,
            weight: p.weight
          }));
          const data = {
            ...this.form,
            qwAssignRuleUsers: submitPersonnelList
          };
          addOrUpdateAssignRule(data).then(response => {
            this.msgSuccess(this.form.id ? "修改成功" : "新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },

    /** 取消 */
    cancel() {
      this.open = false;
      this.reset();
    },

    /** 表单重置 */
    reset() {
      this.form = {
        id: null,
        ruleName: null,
        assignType: 3,
        qwAssignRuleUsers: null,
        status: 1
      };
      this.personnelList = [];
      this.resetForm("form");
    },

    /** 搜索 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    }
  }
};
</script>
