<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="部门名称" prop="orgName">
        <el-input
          v-model="queryParams.orgName"
          maxlength="28"
          placeholder="请输入部门名称"
          clearable
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="角色名称" prop="deptRoleName">
        <el-input
          v-model="queryParams.deptRoleName"
          maxlength="28"
          placeholder="请输入角色名称"
          clearable
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="人员名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          maxlength="28"
          placeholder="请输入人员名称"
          clearable
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </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-table v-loading="loading" :data="typeList" :span-method="objectSpanMethod">
      <el-table-column label="序号" align="center" width="80" type="index">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="部门名称" align="center" prop="orgName" :show-overflow-tooltip="true"/>
      <el-table-column label="角色名称" align="center" prop="deptRoleName" :show-overflow-tooltip="true"/>
      <el-table-column label="人员名称" align="center" prop="userName" :show-overflow-tooltip="true"/>
      <el-table-column label="审批状态" align="center" prop="reviewerStatus" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="scope.row.reviewerStatus == 0">待审核</span>
          <span v-else-if="scope.row.reviewerStatus == 1">已审核</span>
          <span v-else-if="scope.row.reviewerStatus == 2">未通过</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.reviewerStatus == null"
            @click="handleAllocation(scope.row)"
          >分配人员
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.reviewerStatus == 1 || scope.row.reviewerStatus == 2"
            @click="handleChange(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="500px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="部门名称" prop="orgName">
          <el-input v-model="form.orgName" :disabled="true"/>
        </el-form-item>
        <el-form-item label="角色名称" prop="deptRoleName">
          <el-input v-model="form.deptRoleName" :disabled="true"/>
        </el-form-item>

        <el-form-item label="人员" required>
          <el-tree
            class="tree-border"
            :data="staffOptions"
            show-checkbox
            ref="staff"
            node-key="uniqueId"
            empty-text="加载中，请稍候"
            :props="defaultProps"
            default-expand-all
            :default-checked-keys="defaultCheckedKeys"
            @check-change="handleCheckChange"
          ></el-tree>
        </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>
  </div>
</template>

<script>
import {getRoleUserList, proDeptRole} from "@/api/process/roles";
import {treeselect as staffTreeselect, roleStaffTreeselect} from "@/api/process/tree";


export default {
  name: "Roles",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      typeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptRoleName: undefined,
        orgName: undefined,
        userName: undefined
      },
      // 人员列表
      staffOptions: [],
      // 默认选中的节点 id 数组
      defaultCheckedKeys: [],
      // 用于存储 uniqueId 到 id 的映射
      uniqueIdToIdMap: {},
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "name",
        disabled: "disabled" // 添加 disabled 属性
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      getRoleUserList(this.queryParams).then(response => {
          this.typeList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },

    objectSpanMethod({row, column, rowIndex, columnIndex}) {
      this.getSpanArray(this.typeList);
      if (columnIndex === 1) {
        const _row = this.spanArray[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
    },
    getSpanArray(data) {
      this.spanArray = [];
      let count = 1;
      for (let i = 0; i < data.length; i++) {
        if (i < data.length - 1 && data[i].orgId === data[i + 1].orgId) {
          count++;
        } else {
          for (let j = 0; j < count; j++) {
            this.spanArray.push(j === 0 ? count : 0);
          }
          count = 1;
        }
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orgId: undefined,
        orgName: undefined,
        departmentId: undefined,
        deptRoleId: undefined,
        deptRoleName: undefined,
        userId: undefined,
        userName: undefined,
        reviewerStatus: undefined,
        reviewerTime: undefined,
        reviewerUserId: undefined,
        roleType: undefined,
        staffOptions: []
      };
      this.defaultCheckedKeys = [];  // 重置默认选中的节点
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 分配人员按钮操作 */
    handleAllocation(row) {
      this.reset();
      this.getStaffTreeselect(row);
      this.form = row;
      this.open = true;
      this.title = "分配人员";
    },

    /** 人员变更按钮操作 */
    handleChange(row) {
      this.reset();
      this.getStaffTreeselect(row);
      this.form = row;
      this.open = true;
      this.title = "分配人员";
    },

    /** 查询员工树结构 */
    getStaffTreeselect(data) {
      staffTreeselect(data).then(response => {
        this.staffOptions = response.data;
        this.processData(this.staffOptions);
        this.setDefaultCheckedKeys();
      });
    },

    /** 处理数据，为每个节点生成唯一标识符并建立映射 */
    processData(nodes, parentId = '') {
      nodes.forEach(node => {
        node.uniqueId = `${parentId ? parentId + '-' : ''}${node.id}`; // 生成唯一标识符
        this.uniqueIdToIdMap[node.uniqueId] = node.id; // 建立 uniqueId 到 id 的映射
        if (node.children && node.children.length > 0) {
          this.processData(node.children, node.uniqueId); // 递归处理子节点
        }
      });
      console.log("this.uniqueIdToIdMap",this.uniqueIdToIdMap)
    },

    /** 设置默认选中的节点 */
    setDefaultCheckedKeys() {
      this.defaultCheckedKeys = this.getCheckedKeys(this.staffOptions);
    },

    /** 递归获取默认选中的节点 id */
    getCheckedKeys(nodes) {
      const keys = new Set();
      const recursiveCheck = (nodes) => {
        nodes.forEach(node => {
          if (node.isCheck === 1) {
            keys.add(node.uniqueId);
          }
          if (node.children && node.children.length > 0) {
            recursiveCheck(node.children);
          }
        });
      };
      recursiveCheck(nodes);
      return Array.from(keys);
    },

    // 如果节点被取消选中
    handleCheckChange(data, checked, indeterminate) {
      if (!checked) { // 如果节点被取消选中
        const idToUncheck = data.id;
        this.$nextTick(() => {
          this.uncheckAllWithSameId(idToUncheck);
        });
      }
    },
    // 第三个参数防止递归影响父节点和子节点的状态
    uncheckAllWithSameId(id) {
      const tree = this.$refs.staff;
      if (tree && tree.store) {
        const allNodes = tree.store._getAllNodes();
        allNodes.forEach(node => {
          if (this.uniqueIdToIdMap[node.key] === id) {
            tree.setChecked(node, false, false);
          }
        });
      } else {
        console.error('Tree or store is not initialized yet.');
      }
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const checkedKeys = this.getStaffAllCheckedKeys();
          if (checkedKeys.length === 0) {
            this.$message.error("请至少选择一个人员");
            return;
          }
          this.form.userId = checkedKeys.join(",");
          proDeptRole(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },

    // 所有菜单节点数据
    getStaffAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.staff.getCheckedKeys();
      console.log("checkedKeys,",checkedKeys)
      const checkedIds = checkedKeys.map(uniqueId => this.uniqueIdToIdMap[uniqueId]);
      // 半选中的菜单节点
      // let halfCheckedKeys = this.$refs.staff.getHalfCheckedKeys();
      // checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      // checkedKeys.unshift.apply(checkedKeys);
      return checkedIds;
    },
  },
};
</script>
