<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="handleExport"
          v-hasPermi="['dept:org:export']"
        >导出
        </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)"
            v-hasPermi="['dept:org:query']"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['dept:org:edit']"
          >审核
          </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="orgHeadUserIdList">
              <el-select v-model="form.orgHeadUserIdList" 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" 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"
                  :disabled="true"
                />
              </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"
                  :disabled="true"
                >{{ 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="项目经理：" prop="managerId">
              <treeselect v-model="form.managerId" :multiple="false" :flat="true" :options="managerOptions"
                          :normalizer="normalizer2" placeholder="请选择项目经理" :disabled="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="请选择安全员" :disabled="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="请选择质检员" :disabled="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="选择项目总工" :disabled="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="请选择机械员" :disabled="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="请选择资料员" :disabled="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="请选择施工员" :disabled="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="请选择材料员" :disabled="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="请选择其他" :disabled="true" />
            </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,exportSubOrg} 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";
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,
        applyName: undefined,
        reviewerStatus: 0,
      },
      // 表单参数
      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: [],
    };
  },
  created() {
    if(this.$route.query.param){
      console.log(this.$route.query.param)
      this.queryParams.applyName=this.$route.query.param
    }
    this.getList();
    this.getPersonSelect();
  },


  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,
        applyName: 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();
    },

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

        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 = 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 = "分公司项目部详情";
    },

    /**
     * 审核同意
     */
    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() {
      exportSubOrg(this.queryParams).then(res =>{
        downloadFile({ fileName: `分公司项目_${new Date().getTime()}.xlsx`, fileData: res, fileType: 'application/vnd.ms-excel;charset=utf-8' })
      })
    },

    /** 转换部门数据结构 */
    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;
    },

    /** 查询员工树结构 */
    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;
    },
  }
};
</script>
