<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="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-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"
          v-hasPermi="['dept:org:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['dept:org:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-s-custom"
          size="mini"
          @click="allocation"
          v-hasPermi="['dept:org:all']"
        >权限分配
        </el-button>
      </el-col>
    </el-row>

    <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="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="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <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)"
            v-hasPermi="['dept:org:query']"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.reviewerStatus != 1 "
            v-hasPermi="['dept:org:query']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh-left"
            @click="handleWithdraw(scope.row)"
            v-if="scope.row.reviewerStatus == 0"
            v-hasPermi="['dept:org:edit']"
          >撤回
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="scope.row.reviewerStatus == 3 "
            v-hasPermi="['dept:org:remove']"
          >删除
          </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"
                          placeholder="选择上级部门" :searchable="true" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="部门名称" prop="orgName">
              <el-input v-model="form.orgName" placeholder="请输入部门名称" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门负责人" prop="orgHeadUserIdList">
              <el-select v-model="form.orgHeadUserIdList" filterable multiple placeholder="部门负责人" clearable style="width: 100%;">
                <el-option
                  v-for="item in personOptions"
                  :key="item.userIds"
                  :label="item.userName"
                  :value="item.userIds"
                />
              </el-select>
            </el-form-item>
          </el-col>


          <el-col :span="12">
            <el-form-item label="考勤员" prop="attendanceUserId">
              <el-select v-model="form.attendanceUserId" filterable placeholder="考勤员" clearable style="width: 100%;">
                <el-option
                  v-for="item in personOptions"
                  :key="item.userIds"
                  :label="item.userName"
                  :value="item.userIds"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="省份" prop="province">
              <el-select v-model="form.province" placeholder="省份" clearable style="width: 200px !important;">
                <el-option
                  v-for="item in provinceList"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="省内外" prop="isProvince">
              <el-radio-group v-model="form.isProvince">
                <el-radio
                  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"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="项目经理：" prop="managerId">
              <treeselect v-model="form.managerId" :multiple="false" :flat="true" :options="managerOptions"
                          :normalizer="normalizer2" placeholder="请选择项目经理" :searchable="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="安全员：" prop="safetyId">
              <treeselect v-model="form.safetyId" :multiple="false" :flat="true" :options="safetyOptions"
                          :normalizer="normalizer2" placeholder="请选择安全员" :searchable="true" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="质检员：" prop="qualityId">
              <treeselect v-model="form.qualityId" :multiple="false" :flat="true" :options="qualityOptions"
                          :normalizer="normalizer2" placeholder="请选择质检员" :searchable="true" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="项目总工：" prop="proId">
              <treeselect v-model="form.proId" :multiple="false" :flat="true" :options="proOptions"
                          :normalizer="normalizer2" placeholder="选择项目总工" :searchable="true" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="机械员：" prop="mechanicList">
              <treeselect v-model="form.mechanicList" :multiple="true" :flat="true" :options="mechanicOptions"
                          :normalizer="normalizer2" placeholder="请选择机械员" :searchable="true" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="资料员：" prop="documenterList">
              <treeselect v-model="form.documenterList" :multiple="true" :flat="true" :options="documenterOptions"
                          :normalizer="normalizer2" placeholder="请选择资料员" :searchable="true" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="施工员：" prop="constructionList">
              <treeselect v-model="form.constructionList" :multiple="true" :flat="true" :options="constructionOptions"
                          :normalizer="normalizer2" placeholder="请选择施工员" :searchable="true" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="材料员：" prop="materialmanList">
              <treeselect v-model="form.materialmanList" :multiple="true" :flat="true" :options="materialmanOptions"
                          :normalizer="normalizer2" placeholder="请选择材料员" :searchable="true" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="其他：" prop="otherList">
              <treeselect v-model="form.otherList" :multiple="true" :flat="true" :options="otherOptions"
                          :normalizer="normalizer2" placeholder="请选择其他" :searchable="true" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="details">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 单用户的表格 -->
    <el-dialog :title="title" :visible.sync="openUser" width="65%" append-to-body>
      <el-form :model="queryParamsUser" ref="queryFormUser" size="small" :inline="true" v-show="showSearchUser" label-width="68px">
        <el-form-item label="姓名" prop="userName">
          <el-input
            v-model="queryParamsUser.userName"
            placeholder="请输入姓名"
            clearable
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="orgId">
          <treeselect v-model="queryParamsUser.orgId" :options="deptOptionsUser" :normalizer="normalizerUser" placeholder="选择部门" style="width: 240px"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryUser">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQueryUser">重置</el-button>
        </el-form-item>
      </el-form>


      <el-table v-loading="loading" :data="userList" >
        <el-table-column label="序号" align="center" width="80" type="index">
          <template slot-scope="scope">
            <span>{{ (queryParamsUser.pageNum - 1) * queryParamsUser.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" align="center" prop="userName" />
        <el-table-column label="所属部门" align="center" prop="orgName" :show-overflow-tooltip="true" />
        <el-table-column label="岗位" align="center" prop="postName" :show-overflow-tooltip="true"/>
        <el-table-column label="人员角色" align="center" prop="roleName" :show-overflow-tooltip="true" />
        <el-table-column label="身份证号" align="center" prop="idNumber" :show-overflow-tooltip="true" />
        <el-table-column label="手机号(登录名称)" align="center" prop="phone" :show-overflow-tooltip="true" />
        <el-table-column label="操作" align="center" width="230">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handlePermission(scope.row)"
              ref="editButton"
            >分配项目部管理权限</el-button>
          </template>
        </el-table-column>
      </el-table>

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

    </el-dialog>

  </div>
</template>

<script>
import {listType, getType, delSubOrg, addType, updateType, changeStatus,listUser,updatePermission} from "@/api/process/branchPro";
import {listDept, orgPersonSelect,listDeptUser} 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";
import {exportSubOrg} from "@/api/process/branchProExamine";
import {downloadFile} from "@/utils/download";
import {getPersonSelect} from "@/api/system/userInfo";

export default {
  name: "branchPro",
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      typeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      details: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orgName: undefined,
        orgHeadUserName: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          {required: true, message: "上级部门不能为空", trigger: "blur"}
        ],
        orgName: [
          {required: true, message: "部门名称不能为空", trigger: "blur"}
        ],
        orgHeadUserIdList: [
          {required: true, message: "部门负责人不能为空", trigger: "blur"}
        ],
        attendanceUserId: [
          {required: true, message: "考勤员不能为空", trigger: "blur"}
        ],
        province: [
          {required: true, message: "省份不能为空", trigger: "blur"}
        ],
        isProvince: [
          {required: true, message: "省内外不能为空", trigger: "blur"}
        ],
        address: [
          {required: true, message: "位置不能为空", trigger: "blur"}
        ],
        managerId: [
          {required: true, message: "项目经理不能为空", trigger: "blur"}
        ],
        safetyId: [
          {required: true, message: "安全员不能为空", trigger: "blur"}
        ],
        qualityId: [
          {required: true, message: "质检员不能为空", trigger: "blur"}
        ],
        proId: [
          {required: true, message: "项目总工不能为空", trigger: "blur"}
        ],
        mechanicList: [
          {required: true, message: "机械员不能为空", trigger: "change"},
        ],
        documenterList: [
          {required: true, message: "资料员不能为空", trigger: "change"},
        ],
        constructionList: [
          {required: true, message: "施工员不能为空", trigger: "change"},
        ],
        materialmanList: [
          {required: true, message: "材料员不能为空", trigger: "change"},
        ],

      },

      // 部门树选项
      deptOptions: [],
      personOptions: [],
      isProvinceList: [{id: '1', name: '省内'}, {id: '2', name: '省外'}],
      provinceList: ["北京", "上海", "天津",
        "重庆",
        "河北",
        "山西",
        "内蒙古",
        "辽宁",
        "吉林",
        "黑龙江",
        "江苏",
        "浙江",
        "安徽",
        "福建",
        "江西",
        "山东",
        "河南",
        "湖北",
        "湖南",
        "广东",
        "广西",
        "海南",
        "四川",
        "贵州",
        "云南",
        "西藏",
        "陕西",
        "甘肃",
        "宁夏",
        "青海",
        "新疆",
        "香港",
        "澳门",
        "台湾"],
      // 人员列表
      managerOptions: [],
      safetyOptions: [],
      qualityOptions: [],
      proOptions: [],
      mechanicOptions: [],
      documenterOptions: [],
      constructionOptions: [],
      materialmanOptions: [],
      otherOptions: [],


      oldOrgName: [],

      //用户管理
      openUser:false,
      queryParamsUser: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        orgId: undefined,
      },
      showSearchUser: true,
      deptOptionsUser:[],
      userList: [],
    };
  },
  mounted() {
    this.getList();
    this.getPersonSelect();
    this.getDeptListUser()
  },
  methods: {
    /** 人员选择下拉 */
    getPersonSelect() {
      getPersonSelect().then(response => {
        this.personOptions=response.data
      });
    },
    /** 查询列表 */
    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,
        orgHeadUserIdList: [],
        orgHeadUserName: undefined,
        province: undefined,
        isProvince: "1",
        isDepartment: "0",
        //选中的人员列表
        managerId: undefined,
        safetyId: undefined,
        qualityId: undefined,
        proId: undefined,
        mechanicList: [],
        documenterList: [],
        constructionList: [],
        materialmanList: [],
        otherList: [],
        oldOrgName: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    async handleAdd() {
      this.reset();
      /**
       * 上级部门下拉选
       */
      await listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, "id");
      });


      /** 人员 */
      this.getStaffTreeselect("-1", "1", "", "manager");
      this.getStaffTreeselect("-1", "2", "", "safety");
      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");

      this.open = true;
      this.details = true;
      this.title = "分公司项目部新增";


    },

    //数据操作
    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;
    },

    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      const ids = row.id;
      await getType(ids).then(response => {
        this.form = response.data;
        this.oldOrgName = row.orgName

        if(!this.form.parentId){
          this.form.parentId=0
        }
        if(this.form.orgHeadUserId!=null){
          let arr = this.form.orgHeadUserId.split(',')
          this.$set(this.form,"orgHeadUserIdList",arr)
        }

        listDept().then(response => {
          this.deptOptions = this.handleTree(response.data, "id");
        });

        /** 人员 */
        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");

        this.form.managerId=this.form.roleList[0].userId;
        this.form.safetyId=this.form.roleList[1].userId;
        this.form.qualityId=this.form.roleList[2].userId;
        this.form.proId=this.form.roleList[3].userId;

        if(this.form.roleList[4].userId){
          this.form.mechanicList=this.form.roleList[4].userId.split(",").map(id => id.trim());
        }else{
          this.form.mechanicList=this.form.roleList[4];
        }
        if(this.form.roleList[5].userId){
          this.form.documenterList=this.form.roleList[5].userId.split(",").map(id => id.trim());
        }else{
          this.form.documenterList=this.form.roleList[5].userId;
        }

        if(this.form.roleList[6].userId){
          this.form.constructionList=this.form.roleList[6].userId.split(",").map(id => id.trim());
        }else{
          this.form.constructionList=this.form.roleList[6].userId;
        }

        if(this.form.roleList[7].userId){
          this.form.materialmanList=this.form.roleList[7].userId.split(",").map(id => id.trim());
        }else {
          this.form.materialmanList=this.form.roleList[7].userId;
        }
        if(this.form.roleList[8].userId){
          this.form.otherList=this.form.roleList[8].userId.split(",").map(id => id.trim());
        }else{
          this.form.otherList=this.form.roleList[8].userId;
        }
      });
      console.log("this.form=",this.form)

      this.open = true;
      this.details = true;
      this.title = "分公司项目部修改";
    },


    /** 详情按钮操作 */
    detailsUpdate(row) {
      this.reset();
      const ids = row.id
      getType(ids).then(response => {
        this.form = response.data;
        if(!this.form.parentId){
          this.form.parentId=0
        }
        if(this.form.orgHeadUserId!=null){
          let arr = this.form.orgHeadUserId.split(',')
          this.$set(this.form,"orgHeadUserIdList",arr)
        }
        listDept().then(response => {
          this.deptOptions = this.handleTree(response.data, "id");
        });

        /** 人员 */
        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");

        this.form.managerId=this.form.roleList[0].userId;
        this.form.safetyId=this.form.roleList[1].userId;
        this.form.qualityId=this.form.roleList[2].userId;
        this.form.proId=this.form.roleList[3].userId;

        if(this.form.roleList[4].userId){
          this.form.mechanicList=this.form.roleList[4].userId.split(",").map(id => id.trim());
        }else{
          this.form.mechanicList=this.form.roleList[4];
        }
        if(this.form.roleList[5].userId){
          this.form.documenterList=this.form.roleList[5].userId.split(",").map(id => id.trim());
        }else{
          this.form.documenterList=this.form.roleList[5].userId;
        }

        if(this.form.roleList[6].userId){
          this.form.constructionList=this.form.roleList[6].userId.split(",").map(id => id.trim());
        }else{
          this.form.constructionList=this.form.roleList[6].userId;
        }

        if(this.form.roleList[7].userId){
          this.form.materialmanList=this.form.roleList[7].userId.split(",").map(id => id.trim());
        }else {
          this.form.materialmanList=this.form.roleList[7].userId;
        }
        if(this.form.roleList[8].userId){
          this.form.otherList=this.form.roleList[8].userId.split(",").map(id => id.trim());
        }else{
          this.form.otherList=this.form.roleList[8].userId;
        }
      });
      this.open = true;
      this.details = false;
      this.title = "分公司项目部详情";
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        console.log(this.form);
        if (valid) {
          this.form.orgHeadUserId=this.form.orgHeadUserIdList.join(',');

          let managerIds = this.form.managerId;
          let safetyIds = this.form.safetyId;
          let qualityIds = this.form.qualityId;
          let proIds = this.form.proId;
          if(managerIds == safetyIds || managerIds ==qualityIds || managerIds ==proIds || safetyIds==qualityIds || qualityIds == proIds   ){
            this.$modal.msgError("项目经理、 安全员、质检员、项目总工不能为同一人");
            return
          }


          if (this.form.id != undefined) {
            updateType(this.form, this.oldOrgName).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addType(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      this.$modal.confirm('是否确认删除此数据项？').then(function () {
        return delSubOrg(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    /** 撤回按钮操作 */
    handleWithdraw(row) {
      const ids = row.id;
      this.$modal.confirm('是否确认撤回此数据项？').then(function () {
        return changeStatus(ids, "3");
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("撤回成功");
      }).catch(() => {
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      exportSubOrg(this.queryParams).then(res =>{
        downloadFile({ fileName: `分公司项目_${new Date().getTime()}.xlsx`, fileData: res, fileType: 'application/vnd.ms-excel;charset=utf-8' })
      })
    },

    /** 权限分配-跳转到人员信息页面*/
    allocation(){
      this.reset();
      this.resetForm("queryFormUser");
      this.getListUser();
      this.openUser=true
      this.title="权限分配"

      // this.$router.push({ path : '/system/userInfo' }); // 使用路由名称进行跳转
    },

    /** 刷新缓存按钮操作 */
    handleRefreshCache() {
      refreshCache().then(() => {
        this.$modal.msgSuccess("刷新成功");
        this.$store.dispatch('dict/cleanDict');
      });
    },


    /** 转换部门数据结构 */
    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;
    },
    handleSelect2(value, instanceId) {
      // 在这里处理选择事件
      this.form.attendanceUserName = value.name;
    },

    /** 查询员工树结构 */
    async getStaffTreeselect(orgId, deptRoleId, departmentId, types) {
      let data = {
        orgId: orgId,
        deptRoleId: deptRoleId,
        departmentId: departmentId,
      }
      await staffTreeselect(data).then(response => {
        // 动态设置每个类型的选项
        this[`${types}Options`] = this.changeDataStaff(response.data);
      });
    },

    changeDataStaff(data) {
      if (!Array.isArray(data)) {
        console.error('Expected an array, but received:', data);
        return [];
      }
      data.map(item => {
        if (item.disabled) {
          if (item.isCheck == 0) {
            item.isChecked = false
            item.isDisabled = true
          } else {
            item.isChecked = true
            item.isDisabled = false
          }
        } else if (!item.disabled) {
          item.isChecked = false
          item.isDisabled = false
        }
        item.children && item.children.length > 0 && this.changeDataStaff(item.children);
      })
      return data;
    },


    /** 转换部门数据结构 */
    normalizerUser(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.orgName,
        children: node.children
      };
    },


    /** 搜索按钮操作 */
    handleQueryUser() {
      this.queryParamsUser.pageNum = 1;
      this.getListUser();
    },
    /** 重置按钮操作 */
    resetQueryUser() {
      this.resetForm("queryFormUser");
      this.handleQueryUser();
    },

    /** 查询列表 */
    getListUser() {
      this.loading = true;
      listUser(this.queryParamsUser).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },

    getDeptListUser() {
      listDeptUser().then(response => {
        this.deptOptionsUser = this.handleTree(response.data, "id");
      });
    },

    handlePermission(row){
      var roleIds = row.roleIds;
      if (!roleIds.some(id => id === 10)) {
        roleIds.push(10);
      }
      var userId = row.userId;
      var data = {
        roleIds:roleIds,
        userId:userId
      }

      updatePermission(data).then(response => {
        this.$modal.msgSuccess("更新成功");
        this.openUser = false;
        this.getList();
      });

    }

  }
};
</script>
