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

      <el-form-item label="项目部名称" prop="orgName">
        <el-input
          v-model="queryParams.orgName"
          placeholder="请输入项目部名称"
          clearable
          style="width: 200px"
          maxlength="28"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="orgHeadUserName">
        <el-input
          v-model="queryParams.orgHeadUserName"
          placeholder="请输入部门负责人"
          clearable
          style="width: 200px"
          maxlength="28"
          @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-button
          type="success"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleUpdate"
        >导出
        </el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="typeList">
      <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="applyName" :show-overflow-tooltip="true"/>
      <el-table-column label="申请时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上级部门" align="center" prop="parentOrgName" :show-overflow-tooltip="true"/>
      <el-table-column label="项目部名称" align="center" prop="orgName" :show-overflow-tooltip="true"/>
      <el-table-column label="项目部负责人" align="center" prop="orgHeadUserName" :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>
          <span v-else-if="scope.row.reviewerStatus == 3">撤回</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-search"
            @click="detailsUpdate(scope.row)"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(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="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12" v-if="form.parentId !== 0">
            <el-form-item label="上级部门" prop="parentId">
              <treeselect v-model="form.parentId" :options="deptOptions" :normalizer="normalizer" :disabled="true"
                          placeholder="选择上级部门"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="部门名称" prop="orgName">
              <el-input v-model="form.orgName" placeholder="请输入部门名称" maxlength="30" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门负责人" prop="orgHeadUserId">
              <treeselect v-model="form.orgHeadUserId" :flat="true" :options="personOptions" :normalizer="normalizer2"
                          placeholder="选择部门负责人" @select="handleSelect1" :disabled="true" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="省内外" prop="isProvince">
              <el-radio-group v-model="form.isProvince">
                <el-radio
                  :disabled="true"
                  v-for="item in isProvinceList"
                  :key="item.id"
                  :label="item.id"
                >{{ item.name }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>

          <el-col :span="12">
            <el-form-item label="位置" prop="address">
              <el-input v-model="form.address" placeholder="请输入位置" maxlength="50" :disabled="true" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="项目经理" required>
              <el-tree
                class="tree-border"
                :data="managerOptions"
                show-checkbox
                ref="manager"
                node-key="managerId"
                empty-text="加载中，请稍候"
                :props="defaultProps"
                :default-checked-keys="managerDefaultCheckedKeys"
                @check-change="managerHandleCheckChange"
                :disabled="true"
              ></el-tree>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="安全员" required>
              <el-tree
                class="tree-border"
                :data="safetyOptions"
                show-checkbox
                ref="safety"
                node-key="safetyId"
                empty-text="加载中，请稍候"
                :props="defaultProps"
                :default-checked-keys="safetyDefaultCheckedKeys"
                @check-change="safetyHandleCheckChange"
                :disabled="true"
              ></el-tree>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="质检员" required>
              <el-tree
                class="tree-border"
                :data="qualityOptions"
                show-checkbox
                ref="quality"
                node-key="qualityId"
                empty-text="加载中，请稍候"
                :props="defaultProps"
                :default-checked-keys="qualityDefaultCheckedKeys"
                @check-change="qualityHandleCheckChange"
                :disabled="true"
              ></el-tree>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目总工" required>
              <el-tree
                class="tree-border"
                :data="proOptions"
                show-checkbox
                ref="pro"
                node-key="proId"
                empty-text="加载中，请稍候"
                :props="defaultProps"
                :default-checked-keys="proDefaultCheckedKeys"
                @check-change="proHandleCheckChange"
                :disabled="true"
              ></el-tree>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="机械员" required>
              <el-tree
                class="tree-border"
                :data="mechanicOptions"
                show-checkbox
                ref="mechanic"
                node-key="mechanicId"
                empty-text="加载中，请稍候"
                :props="defaultProps"
                :default-checked-keys="mechanicDefaultCheckedKeys"
                @check-change="mechanicHandleCheckChange"
                :disabled="true"
              ></el-tree>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="资料员" required>
              <el-tree
                class="tree-border"
                :data="documenterOptions"
                show-checkbox
                ref="documenter"
                node-key="documenterId"
                empty-text="加载中，请稍候"
                :props="defaultProps"
                :default-checked-keys="documenterDefaultCheckedKeys"
                @check-change="documenterHandleCheckChange"
                :disabled="true"
              ></el-tree>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="施工员" required>
              <el-tree
                class="tree-border"
                :data="constructionOptions"
                show-checkbox
                ref="construction"
                node-key="constructionId"
                empty-text="加载中，请稍候"
                :props="defaultProps"
                :default-checked-keys="constructionDefaultCheckedKeys"
                @check-change="constructionHandleCheckChange"
                :disabled="true"
              ></el-tree>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="材料员" required>
              <el-tree
                class="tree-border"
                :data="materialmanOptions"
                show-checkbox
                ref="materialman"
                node-key="materialmanId"
                empty-text="加载中，请稍候"
                :props="defaultProps"
                :default-checked-keys="materialmanDefaultCheckedKeys"
                @check-change="materialmanHandleCheckChange"
                :disabled="true"
              ></el-tree>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="其他">
              <el-tree
                class="tree-border"
                :data="otherOptions"
                show-checkbox
                ref="other"
                node-key="otherId"
                empty-text="加载中，请稍候"
                :props="defaultProps"
                :default-checked-keys="otherDefaultCheckedKeys"
                @check-change="otherHandleCheckChange"
                :disabled="true"
              ></el-tree>
            </el-form-item>
          </el-col>


        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleAgree" v-if="details">同 意</el-button>
        <el-button type="danger" @click="handleReject" v-if="details">驳 回</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listType, getType, changeStatus} from "@/api/process/branchProExamine";
import {listDept, orgPersonSelect} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {treeselect as staffTreeselect} from "@/api/process/tree";

export default {
  name: "BranchPro",
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      typeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      details: true,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orgName: undefined,
        orgHeadUserName: undefined,
        applyName: undefined,
        reviewerStatus:0,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        menuName: [
          {required: true, message: "菜单名称不能为空", trigger: "blur"}
        ],
        orderNum: [
          {required: true, message: "菜单顺序不能为空", trigger: "blur"}
        ],
        path: [
          {required: true, message: "路由地址不能为空", trigger: "blur"}
        ],
        systemType: [
          {required: true, message: "请选择系统类型", trigger: "change"}
        ],
      },

      // 部门树选项
      deptOptions: [],
      personOptions: [],
      isProvinceList: [{id: '1', name: '省内'}, {id: '2', name: '省外'}],

      // 人员列表
      managerOptions: [],
      safetyOptions: [],
      qualityOptions: [],
      proOptions: [],
      mechanicOptions: [],
      documenterOptions: [],
      constructionOptions: [],
      materialmanOptions: [],
      otherOptions: [],

      // 默认选中的节点 id 数组
      managerDefaultCheckedKeys: [],
      safetyDefaultCheckedKeys: [],
      qualityDefaultCheckedKeys: [],
      proDefaultCheckedKeys: [],
      mechanicDefaultCheckedKeys: [],
      documenterDefaultCheckedKeys: [],
      constructionDefaultCheckedKeys: [],
      materialmanDefaultCheckedKeys: [],
      otherDefaultCheckedKeys: [],
      // 用于存储 uniqueId 到 id 的映射
      managerIdToIdMap: {},
      safetyIdToIdMap: {},
      qualityIdToIdMap: {},
      proIdToIdMap: {},
      mechanicIdToIdMap: {},
      documenterIdToIdMap: {},
      constructionIdToIdMap: {},
      materialmanIdToIdMap: {},
      otherIdToIdMap: {},
      //保存返回的值
      defaultProps: {
        children: "children",
        label: "name",
        disabled: "disabled" // 添加 disabled 属性
      },
      // 用于存储当前选中的节点
      managerCurrentCheckedNode: [],
      safetyCurrentCheckedNode: [],
      qualityCurrentCheckedNode: [],
      proCurrentCheckedNode: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      listType(this.queryParams).then(response => {
          this.typeList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        parentId: undefined,
        orgName: undefined,
        address: undefined,
        attendanceUserId: undefined,
        attendanceUserName: undefined,
        orgHeadUserId: undefined,
        orgHeadUserName: undefined,
        province: undefined,
        applyName: undefined,
        isProvince: "1",
        isDepartment: "0",

        // 部门树选项
        deptOptions: [],
        personOptions: [],
        isProvinceList: [{id: '1', name: '省内'}, {id: '2', name: '省外'}],

        // 人员列表
        managerOptions: [],
        safetyOptions: [],
        qualityOptions: [],
        proOptions: [],
        mechanicOptions: [],
        documenterOptions: [],
        constructionOptions: [],
        materialmanOptions: [],
        otherOptions: [],

        // 默认选中的节点 id 数组
        managerDefaultCheckedKeys: [],
        safetyDefaultCheckedKeys: [],
        qualityDefaultCheckedKeys: [],
        proDefaultCheckedKeys: [],
        mechanicDefaultCheckedKeys: [],
        documenterDefaultCheckedKeys: [],
        constructionDefaultCheckedKeys: [],
        materialmanDefaultCheckedKeys: [],
        otherDefaultCheckedKeys: [],
        // 用于存储 uniqueId 到 id 的映射
        managerIdToIdMap: {},
        safetyIdToIdMap: {},
        qualityIdToIdMap: {},
        proIdToIdMap: {},
        mechanicIdToIdMap: {},
        documenterIdToIdMap: {},
        constructionIdToIdMap: {},
        materialmanIdToIdMap: {},
        otherIdToIdMap: {},
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.details = true;
      this.title = "分公司项目部新增";
      /**
       * 上级部门下拉选
       */
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, "id");
      });
      /**
       * 项目部负责人
       */
      orgPersonSelect().then(response => {
        this.personOptions = this.changeData(response.data);
      });

      /** 人员 */
      this.getStaffTreeselect("-1", "1", "", "manager");
      this.getStaffTreeselect("-1", "2", "", "safety");
      this.getStaffTreeselect("-1", "3", "", "quality");
      this.getStaffTreeselect("-1", "4", "", "pro");
      this.getStaffTreeselect("-1", "5", "", "mechanic");
      this.getStaffTreeselect("-1", "6", "", "documenter");
      this.getStaffTreeselect("-1", "7", "", "construction");
      this.getStaffTreeselect("-1", "8", "", "materialman");
      this.getStaffTreeselect("-1", "9", "", "other");
    },

    //数据操作
    changeData(data) { // 存在子集就不让禁止，父级让禁止
      data.map(item => {
        if (!item.disabled) {
          item.isDisabled = false
        } else if (item.disabled) {
          item.isDisabled = true
        }
        item.children && item.children.length > 0 && this.changeData(item.children);
      })
      return data;
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ids = row.id
      getType(ids).then(response => {
        this.form = response.data;
        this.open = true;
        this.details = true;
        this.title = "分公司项目部修改";
        listDept().then(response => {
          this.deptOptions = this.handleTree(response.data, "id");
        });

        /**
         * 项目部负责人
         */
        orgPersonSelect().then(response => {
          this.personOptions = this.changeData(response.data);
        });

        /** 人员 */
        this.getStaffTreeselect(ids, "1", "", "manager");
        this.getStaffTreeselect(ids, "2", "", "safety");
        this.getStaffTreeselect(ids, "3", "", "quality");
        this.getStaffTreeselect(ids, "4", "", "pro");
        this.getStaffTreeselect(ids, "5", "", "mechanic");
        this.getStaffTreeselect(ids, "6", "", "documenter");
        this.getStaffTreeselect(ids, "7", "", "construction");
        this.getStaffTreeselect(ids, "8", "", "materialman");
        this.getStaffTreeselect(ids, "9", "", "other");

      });
    },


    /** 详情按钮操作 */
    detailsUpdate(row) {
      this.reset();
      const ids = row.id
      getType(ids).then(response => {
        this.form = response.data;
        this.open = true;
        this.details = false;
        this.title = "分公司项目部详情";
        listDept().then(response => {
          this.deptOptions = this.handleTree(response.data, "id");
        });

        /**
         * 项目部负责人
         */
        orgPersonSelect().then(response => {
          this.personOptions = this.changeData(response.data);
        });

        /** 人员 */
        this.getStaffTreeselect(ids, "1", "", "manager");
        this.getStaffTreeselect(ids, "2", "", "safety");
        this.getStaffTreeselect(ids, "3", "", "quality");
        this.getStaffTreeselect(ids, "4", "", "pro");
        this.getStaffTreeselect(ids, "5", "", "mechanic");
        this.getStaffTreeselect(ids, "6", "", "documenter");
        this.getStaffTreeselect(ids, "7", "", "construction");
        this.getStaffTreeselect(ids, "8", "", "materialman");
        this.getStaffTreeselect(ids, "9", "", "other");

      });
    },

    /**
     * 审核同意
     */
    handleAgree(){
      this.handleExamine("1");
    },

    /**
     * 审核驳回
     */
    handleReject(){
      this.handleExamine("2");
    },

    /** 审核按钮操作 */
    handleExamine(reviewerStatus) {
      const ids = this.form.id;
      this.$modal.confirm('是否确认审核此数据项？').then(function () {
        return changeStatus(ids, reviewerStatus);
      }).then(() => {
        this.$modal.msgSuccess("审核成功");
        this.open = false;
        this.getList();
      }).catch(() => {
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('system/dict/type/export', {
        ...this.queryParams
      }, `type_${new Date().getTime()}.xlsx`)
    },

    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.orgName,
        children: node.children
      };
    },
    /** 项目部负责人 */
    normalizer2(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    handleSelect1(value, instanceId) {
      // 在这里处理选择事件
      this.form.orgHeadUserName = value.name;
    },

    /** 查询员工树结构 */
    getStaffTreeselect(orgId, deptRoleId, departmentId, types) {
      let data = {
        orgId: orgId,
        deptRoleId: deptRoleId,
        departmentId: departmentId,
      }
      staffTreeselect(data).then(response => {
        // 动态设置每个类型的选项
        this[`${types}Options`] = response.data;
        // 处理数据
        this.processData(types, this[`${types}Options`]);
        // 设置默认选中的节点
        this[`${types}DefaultCheckedKeys`] = this.getCheckedKeys(types, this[`${types}Options`]);
      });
    },

    /** 处理数据，为每个节点生成唯一标识符并建立映射 */
    processData(types, nodes, parentId = '') {
      const idKey = `${types}Id`;
      const idMapKey = `${types}IdToIdMap`;

      nodes.forEach(node => {
        // 生成唯一标识符
        node[idKey] = `${parentId ? parentId + '-' : ''}${node.id}`;
        // 建立 uniqueId 到 id 的映射
        if (!this[idMapKey]) {
          this[idMapKey] = {};
        }
        this[idMapKey][node[idKey]] = node.id;

        // 递归处理子节点
        if (node.children && node.children.length > 0) {
          this.processData(types, node.children, node[idKey]);
        }
      });
    },

    /** 递归获取默认选中的节点 id */
    getCheckedKeys(types, nodes) {
      const keys = new Set();
      const recursiveCheck = (nodes, keyField) => {
        nodes.forEach(node => {
          if (node.isCheck === 1) {
            keys.add(node[keyField]);
          }
          if (node.children && node.children.length > 0) {
            recursiveCheck(node.children, keyField);
          }
        });
      };
      switch (types) {
        case 'manager':
          recursiveCheck(nodes, 'managerId');
          break;
        case 'safety':
          recursiveCheck(nodes, 'safetyId');
          break;
        case 'quality':
          recursiveCheck(nodes, 'qualityId');
          break;
        case 'pro':
          recursiveCheck(nodes, 'proId');
          break;
        case 'mechanic':
          recursiveCheck(nodes, 'mechanicId');
          break;
        case 'documenter':
          recursiveCheck(nodes, 'documenterId');
          break;
        case 'construction':
          recursiveCheck(nodes, 'constructionId');
          break;
        case 'materialman':
          recursiveCheck(nodes, 'materialmanId');
          break;
        case 'other':
          recursiveCheck(nodes, 'otherId');
          break;
        default:
          console.error(`Unknown type: ${types}`);
          break;
      }
      return Array.from(keys);
    },

    // 如果节点被取消选中
    managerHandleCheckChange(data, checked, indeterminate) {
      if (!checked) { // 如果节点被取消选中
        const idToUncheck = data.id;
        this.$nextTick(() => {
          this.uncheckAllWithSameId(idToUncheck, "manager");
        });
      }
    },

    safetyHandleCheckChange(data, checked, indeterminate) {
      if (!checked) { // 如果节点被取消选中
        const idToUncheck = data.id;
        this.$nextTick(() => {
          this.uncheckAllWithSameId(idToUncheck, "safety");
        });
      }
    },
    qualityHandleCheckChange(data, checked, indeterminate) {
      if (!checked) { // 如果节点被取消选中
        const idToUncheck = data.id;
        this.$nextTick(() => {
          this.uncheckAllWithSameId(idToUncheck, "quality");
        });
      }
    },
    proHandleCheckChange(data, checked, indeterminate) {
      if (!checked) { // 如果节点被取消选中
        const idToUncheck = data.id;
        this.$nextTick(() => {
          this.uncheckAllWithSameId(idToUncheck, "pro");
        });
      }
    },
    mechanicHandleCheckChange(data, checked, indeterminate) {
      if (!checked) { // 如果节点被取消选中
        const idToUncheck = data.id;
        this.$nextTick(() => {
          this.uncheckAllWithSameId(idToUncheck, "mechanic");
        });
      }
    },
    documenterHandleCheckChange(data, checked, indeterminate) {
      if (!checked) { // 如果节点被取消选中
        const idToUncheck = data.id;
        this.$nextTick(() => {
          this.uncheckAllWithSameId(idToUncheck, "documenter");
        });
      }
    },
    constructionHandleCheckChange(data, checked, indeterminate) {
      if (!checked) { // 如果节点被取消选中
        const idToUncheck = data.id;
        this.$nextTick(() => {
          this.uncheckAllWithSameId(idToUncheck, "construction");
        });
      }
    },
    materialmanHandleCheckChange(data, checked, indeterminate) {
      if (!checked) { // 如果节点被取消选中
        const idToUncheck = data.id;
        this.$nextTick(() => {
          this.uncheckAllWithSameId(idToUncheck, "materialman");
        });
      }
    },
    otherHandleCheckChange(data, checked, indeterminate) {
      if (!checked) { // 如果节点被取消选中
        const idToUncheck = data.id;
        this.$nextTick(() => {
          this.uncheckAllWithSameId(idToUncheck, "other");
        });
      }
    },
    // 第三个参数防止递归影响父节点和子节点的状态
    uncheckAllWithSameId(id, type) {
      let tree = "";
      switch (type) {
        case "manager":
          tree = this.$refs.manager;
          if (tree && tree.store) {
            const allNodes = tree.store._getAllNodes();
            allNodes.forEach(node => {
              if (this.managerIdToIdMap[node.key] === id) {
                tree.setChecked(node, false, false);
              }
            });
          } else {
            console.error('Tree or store is not initialized yet.');
          }
          break;
        case "safety":
          tree = this.$refs.safety;
          if (tree && tree.store) {
            const allNodes = tree.store._getAllNodes();
            allNodes.forEach(node => {
              if (this.safetyIdToIdMap[node.key] === id) {
                tree.setChecked(node, false, false);
              }
            });
          } else {
            console.error('Tree or store is not initialized yet.');
          }

          break;
        case "quality":
          tree = this.$refs.quality;
          if (tree && tree.store) {
            const allNodes = tree.store._getAllNodes();
            allNodes.forEach(node => {
              if (this.qualityIdToIdMap[node.key] === id) {
                tree.setChecked(node, false, false);
              }
            });
          } else {
            console.error('Tree or store is not initialized yet.');
          }
          break;
        case "pro":
          tree = this.$refs.pro;
          if (tree && tree.store) {
            const allNodes = tree.store._getAllNodes();
            allNodes.forEach(node => {
              if (this.proIdToIdMap[node.key] === id) {
                tree.setChecked(node, false, false);
              }
            });
          } else {
            console.error('Tree or store is not initialized yet.');
          }
          break;
        case "mechanic":
          tree = this.$refs.mechanic;
          if (tree && tree.store) {
            const allNodes = tree.store._getAllNodes();
            allNodes.forEach(node => {
              if (this.mechanicIdToIdMap[node.key] === id) {
                tree.setChecked(node, false, false);
              }
            });
          } else {
            console.error('Tree or store is not initialized yet.');
          }
          break;
        case "documenter":
          tree = this.$refs.documenter;
          if (tree && tree.store) {
            const allNodes = tree.store._getAllNodes();
            allNodes.forEach(node => {
              if (this.documenterIdToIdMap[node.key] === id) {
                tree.setChecked(node, false, false);
              }
            });
          } else {
            console.error('Tree or store is not initialized yet.');
          }
          break;
        case "construction":
          tree = this.$refs.construction;
          if (tree && tree.store) {
            const allNodes = tree.store._getAllNodes();
            allNodes.forEach(node => {
              if (this.constructionIdToIdMap[node.key] === id) {
                tree.setChecked(node, false, false);
              }
            });
          } else {
            console.error('Tree or store is not initialized yet.');
          }
          break;
        case "materialman":
          tree = this.$refs.materialman;
          if (tree && tree.store) {
            const allNodes = tree.store._getAllNodes();
            allNodes.forEach(node => {
              if (this.materialmanIdToIdMap[node.key] === id) {
                tree.setChecked(node, false, false);
              }
            });
          } else {
            console.error('Tree or store is not initialized yet.');
          }
          break;
        case "other":
          tree = this.$refs.other;
          if (tree && tree.store) {
            const allNodes = tree.store._getAllNodes();
            allNodes.forEach(node => {
              if (this.otherIdToIdMap[node.key] === id) {
                tree.setChecked(node, false, false);
              }
            });
          } else {
            console.error('Tree or store is not initialized yet.');
          }
          break;
      }
    },

    // 所有菜单节点数据
    getAllCheckedKeys(type) {
      // 获取当前被选中的菜单节点
      const idMapKey = `${type}IdToIdMap`;
      const ref = this.$refs[type];
      const idMap = this[idMapKey];
      if (!ref || !idMap) {
        console.error(`Reference or ID map for type "${type}" not found.`);
        return [];
      }
      const checkedKeys = ref.getCheckedKeys();
      const checkedIds = checkedKeys.map(key => idMap[key]);
      return checkedIds;
    },
  }
};
</script>
