<template>
  <el-row>
    <el-col :span="5">
      <basic-container>
        <!-- <el-collapse v-model="activeNames">
          <el-collapse-item name="1" disabled="true">
        <template slot="title">-->
        <!-- <p>全部（{{ personTotal }}人）</p> -->
        <p>人群分组管理</p>
        <!-- </template> -->
        <div class="box" :style="{ height: leftHeight }">
          <el-scrollbar style="height: 100%">
            <el-tree ref="tree" node-key="id" highlight-current :expand-on-click-node="false" @node-click="nodeClick"
                     :data="treeData" :props="props">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <!-- <el-tooltip class="item" effect="dark" :content="node.label" placement="top"> -->
                <TextTooltip :content="`${node.label}(${data.sumNum}人)`" length="16" tip-width="16"></TextTooltip>
                <!-- </el-tooltip> -->
                <!--                <span v-show="data.id && data.id !== '0'" style="flex-basis: 20%">-->
                <!--                  <el-button type="text" icon="el-icon-edit" size="mini"-->
                <!--                             v-if="vaildData(permission.tenant_main_talents_latent_index_groupedit, false)"-->
                <!--                             @click="() => updateGroups('edit', data)">-->
                <!--                  </el-button>-->
                <!--                  <el-button icon="el-icon-delete" type="text" size="mini"-->
                <!--                             v-if="vaildData(permission.tenant_main_talents_latent_index_groupdelete, false)"-->
                <!--                             @click="() => removeGroups(data)">-->
                <!--                  </el-button>-->
                <!--                </span>-->
              </span>
            </el-tree>
            <!-- v-show="vaildData(permission.tenant_wage_payroll_view, false)" -->
            <div class="footer" style="padding-left: 6px">
              <el-button type="text" icon="el-icon-plus"
                         v-if="vaildData(permission.tenant_main_talents_latent_index_groupadd, false)"
                         @click="updateGroups('add')">新建分组
              </el-button>
            </div>
          </el-scrollbar>
        </div>
        <!-- </el-collapse-item>
        </el-collapse>-->
      </basic-container>
      <!-- <div>
            <el-button type="text" icon="el-icon-setting" @click="drawer = true">分组管理</el-button>
      </div>-->
    </el-col>
    <el-col :span="19">
      <basic-container>
        <!--/搜索栏-->
        <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" ref="crud" v-model="obj"
                   :permission="permissionList" :before-open="beforeOpen" @row-del="rowDel" @row-update="rowUpdate"
                   @row-save="rowSave" @search-change="searchChange" @search-reset="searchReset"
                   @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
                   @refresh-change="refreshChange" class="customPage" :row-style="rowStyle">
          <!--自定义列-->
          <template slot="labelsBase" slot-scope="{ row }">
            <el-tooltip effect="dark" placement="top">
              <div slot="content" v-for="(item,index) in row.labelsBaseArr" :key="index">{{ item }}<br/></div>
              <div>{{ row.labelsBase | ellipsis }}</div>
            </el-tooltip>
          </template>
          <template slot="resume" slot-scope="{ row }">
            <div>
              <el-button type="text" size="mini" @click="$refs.resume.openDialog(row)"
                         v-if="row.userId && row.userId !== '0'">查看简历
              </el-button>
              <div v-else>暂无简历</div>
            </div>
          </template>
          <!--/自定义列-->
          <template slot="labelsBaseForm">
            <tag-select v-model="selectedWorkTypes" :prop="{ label: 'name', value: 'name' }" :data="arr">
            </tag-select>
          </template>

          <template slot-scope="{row}" slot="employInfoListForm">
            <div>
              <el-radio-group v-model="employInfoType" @input="employInfoInput">
                <el-radio-button :label="1">失业就业信息</el-radio-button>
                <el-radio-button :label="2">养老待遇信息</el-radio-button>
                <el-radio-button :label="3">人员死亡信息</el-radio-button>
              </el-radio-group>
              <el-table
                v-if="employInfoType === 1"
                :data="row.employInfoList"
                style="width: 100%">
                <el-table-column
                  prop="workCompany"
                  label="工作单位">
                </el-table-column>
                <el-table-column
                  prop="date"
                  label="日期"
                  width="180">
                </el-table-column>
                <el-table-column
                  prop="title"
                  label="内容"
                  width="180">
                </el-table-column>
                <el-table-column
                  prop="remarks"
                  label="备注">
                </el-table-column>
              </el-table>
              <div v-else-if="employInfoType === 2">
                <el-row style="margin-top: 10px">
                  <el-col :span="8">养老保险: {{
                      row.isPension ? '已领取' : ' 未领取'
                    }}
                  </el-col>
                  <el-col :span="8">最大做账期: {{ splitDate(row.biggestDate) || '无' }}</el-col>
                  <el-col :span="8">经办时间: {{
                      row.operateDate && dateFormat(new Date(Number(row.operateDate))) || '无'
                    }}
                  </el-col>
                  <el-col :span="8">开始年月: {{ splitDate(row.startDate) || '无' }}</el-col>
                  <el-col :span="8">终止年月: {{ splitDate(row.endDate) || '无' }}</el-col>
                </el-row>
              </div>
              <div v-else-if="employInfoType === 3">
                <el-row style="margin-top: 10px">
                  <el-col :span="8">是否死亡: {{ row.isDead ? '已死亡' : ' 未死亡' }}</el-col>
                  <el-col :span="8">火化地址: {{ row.funeralAddress || '无' }}</el-col>
                  <el-col :span="8">火化时间: {{ row.funeralDate || '无' }}</el-col>
                </el-row>
              </div>
            </div>
          </template>
          <!--自定义按钮-->
          <template slot="menuLeft">
            <!--            <el-button type="success" size="small" plain icon="el-icon-plus" @click="handleImport"-->
            <!--                       v-show="vaildData(permission.tenant_main_talents_latent_index_add, false)">批量导入-->
            <!--            </el-button>-->
            <el-button type="warning" size="small" plain :disabled="!selectionList.length" icon="el-icon-sort"
                       @click="handleTransfer"
                       v-show="vaildData(permission.tenant_main_talents_latent_index_tansfergroup, false)">转移推送
            </el-button>
            <!--            <el-button type="danger" size="small" icon="el-icon-delete" @click="handleDelete"-->
            <!--                       :disabled="!selectionList.length" plain-->
            <!--                       v-show="vaildData(permission.tenant_main_talents_latent_index_tansfergroup, false)">-->
            <!--              删除-->
            <!--            </el-button>-->
          </template>
          <template slot="name" slot-scope="{row}">
            <span>{{ row.name }}</span>
            <!-- <span v-if="row.status == 1">{{ row.name }}</span>
            <span v-else>{{ row.name }}（<span style="color: red;">未实名</span>）</span> -->

          </template>
          <!--/自定义按钮-->
          <template slot="menuRight">
            <el-button
              type="primary"
              size="small"
              :disabled="downloadButton"
              @click="handleExport"
            >导出
            </el-button>
          </template>
          <template slot-scope="{row}" slot="menu">
            <!--            <el-button type="text"-->
            <!--                       icon="el-icon-document"-->
            <!--                       size="small"-->
            <!--                       @click="serveLog(row)"-->
            <!--            >查看日志-->
            <!--            </el-button>-->
            <el-button type="text"
                       icon="el-icon-circle-check"
                       size="small"
                       @click="checkUserInfo(row)"
            >核实
            </el-button>
          </template>

        </avue-crud>

        <!--批量导入-->
        <el-dialog title="导入" append-to-body :visible.sync="excelBox" :close-on-click-modal="false" width="555px">
          <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter"
                     :upload-before="beforeAvatarUpload" :upload-error="uploadError">
            <template slot="excelTemplate">
              <el-button type="primary" @click="handleTemplate()" :loading="templateLoading">
                点击下载
                <i class="el-icon-download el-icon--right"></i>
              </el-button>
            </template>
          </avue-form>
        </el-dialog>
        <!--         log-->
        <el-drawer
          title="服务日志"
          size="80%"
          :append-to-body="true"
          :before-close="handleCloseLog"
          :visible.sync="innerDrawerLog">
          <!-- <div>
            <span>姓名：</span>
            <span>身份证号：</span>
          </div> -->
          <avue-crud
            :data="logDataSource"
            :option="logOption"
            :page.sync="logPage"
            :table-loading="loadingLog"
            @row-save="saveLog"
            @row-update="saveUpdateLog"
            @row-del="removeLog"
            @size-change="logSizeChange"
            @current-change="logCurrentChange"
          >
            <!-- <template slot="menuLeft">
              <el-button @click="addNewLog" icon="el-icon-plus" type="primary" size="mini">添加</el-button>
            </template>
            <template slot="menu" slot-scope="{row}">
              <el-button type="text" @click="editLogInfo(row.id)" icon="el-icon-edit" size="mini">修改</el-button>
              <el-button type="text" @click="editLogInfo(row.id)" icon="el-icon-edit" size="mini">查看附件</el-button>
            </template> -->
          </avue-crud>
        </el-drawer>
        <!--/批量导入-->
        <!--新建 编辑分组dialog-->
        <add-groups ref="addGroups" @refresh="refresh" :treeData="treeData"></add-groups>
        <!--转移分组dialog-->
        <transfer-groups ref="transferGroups" @refresh="refresh" :ids="ids"></transfer-groups>
        <!--/转移分组dialog-->
        <resume ref="resume" v-show="false"></resume>

        <PromptDialog
          :visible="dialogFlag"
          title="核实"
          :back-btn-status="1"
          submit-text="符 合"
          :submit-vail="false"
          back-text="不符合"
          dialogWidth="60%"
          :isInputInfo="false"
          :placeholder="`请输入不符合 ${selectGroupName} 的具体原因`"
          :sub-title="[
            `请核实人员相关信息，进行以下操作：`,
            `符合：表示为已初步判定该人员符合 ${selectGroupName} 相关条件，但仍需与该人员主动联系并进一步核实，最终以省就业3.0实际政策经办情况为准。`,
            `不符合：表示经核查后该人员不符合 ${selectGroupName} 相关条件，并将该人员从 ${selectGroupName} 列表中剔除。`,
            '核实完成后会产生服务日志记录。'
          ]"
          :tips="dialogTips"
          :pattern="{
            reg: /[\u4e00-\u9fff]{6,}/g,
            check: function checkChineseString(val) {
                const pattern = /[\u4e00-\u9fff]/g;
                const chineseChars = val.match(pattern);
                return chineseChars && chineseChars.length >= 6;
            },
            message: '请填写具体原因，且字数长度不得小于6个汉字'
          }"
          @onClose="dialogFlag = false; GroupValue = ''"
          @onCancel="diaLogCancel"
          @onConfirm="diaLogConfirm"
        >
          <!--          <template v-slot:header>-->
          <!--            <div class="input_box" style="margin-top: 20px">-->
          <!--              <el-select style="width: 100%" clearable v-model="GroupValue" placeholder="请选择分组 (驳回不用选择此项)">-->
          <!--                <el-option-->
          <!--                  v-for="item in selecTreeData"-->
          <!--                  :key="item.id"-->
          <!--                  :label="item.groupName"-->
          <!--                  :value="item.id">-->
          <!--                </el-option>-->
          <!--              </el-select>-->
          <!--            </div>-->
          <!--          </template>-->
        </PromptDialog>

      </basic-container>
      <ied ref="ied"></ied>
    </el-col>
  </el-row>
</template>

<script>
import {
  getList,
  remove,
  update,
  add,
  detail,
  getDept,
  removeDept,
  upload,
  getDeptMyTree,
  talentsApproval, talentsEliminate
} from "@/api/tenant/talents";
import {getWorkTypes, getLabelList} from "@/api/tenant/common";
import {mapGetters} from "vuex";
import addGroups from "./Dialog/addGroups";
import transferGroups from "./Dialog/transferGroups";
import Resume from "@/components/resume/index";
import {check18IdCardNo, isvalidatemobile, isExcel} from "@/util/validate";
import {getTemplate, getTemplateRecommendExportList} from "@/api/resource/template";
import ied from "@/views/util/import-error-dialog";
import {excelAccept} from "@/common/accept";
import TextTooltip from '@/components/text-tooltip'
import {exportList} from "@/api/workstation/post";
import {addServeLog, getMainServeUserLog, removeServeLog, updateServeLog} from "@/api/tenant/serve";
import PromptDialog from "@/components/promptDialog/index.vue";
import {setWith} from "lodash";
import {dateFormat} from '@/util/date'

let page = {
  pageSize: 10,
  currentPage: 1,
  total: 0,
}
export default {
  filters: {
    ellipsis(value) {
      if (!value) return "";
      if (value.length > 15) {
        return value.slice(0, 14) + "...";
      }
      return value;
    },
  },
  name: "tenant_talents",
  data() {
    return {
      employInfoType: 1,
      dialogFlag: false,
      dialogInfo: null,
      downloadButton: false,
      activeNames: "1",
      isIndeterminate: false,
      checkAll: false,
      checked: false,
      selectionList: [],
      loading: true,
      templateLoading: false,
      query: {},
      props: {
        label: "groupName",
        id: "id",
      },
      personTotal: 0,
      treeData: [],
      tenantId: "",
      page: Object.assign({}, page),
      logPage: Object.assign({}, page),
      logDataSource: [],
      loadingLog: false,
      innerDrawerLog: false,
      selectUserServeLog: null,
      tempWorkType: [],
      worktypeDic: {},
      arr: [],//////
      depTree: [],
      deptId: '',
      excelBox: false,
      data: [],
      obj: {},
      excelForm: {isCovered: 1},
      selecTreeData: [],
      GroupValue: '',
      selectInfo: {},
      selectGroupName: '',
      dialogTips: []
    };
  },
  components: {addGroups, transferGroups, Resume, ied, TextTooltip, PromptDialog},
  watch: {},
  computed: {
    ...mapGetters(["permission", "userInfo"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.tenant_main_talents_latent_index_add, false),
        viewBtn: true,
        delBtn: this.vaildData(this.permission.tenant_main_talents_latent_index_del, false),
        editBtn: this.vaildData(this.permission.tenant_main_talents_latent_index_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    leftHeight: function () {
      //获取高度值
      if (document.getElementsByClassName("avue-crud__pagination")[0]) {
        let pageHeight = document.getElementsByClassName(
          "avue-crud__pagination"
        )[0].offsetTop;
        return pageHeight - 105 + "px";
      } else {
        return 725 + "px";
      }
    },
    option() {
      const self = this;
      const IdCardNo = (rule, value, callback) => {
        // if (check18IdCardNo(value)) {
        callback();
        // } else {
        //   callback(new Error("身份证格式不正确"));
        // }
      };
      const validateTel = (rule, value, callback) => {
        if (isvalidatemobile(value)[0]) {
          callback(new Error(isvalidatemobile(value)[1]));
        } else {
          callback();
        }
      };
      // 潜在就业困难人员
      // const unemployedCollegeStudents = this.selectInfo && this.selectInfo.groupName === '潜在就业困难人员'
      return {
        height: "auto",
        dialogWidth: "60%",
        calcHeight: 180,
        align: "center",
        menuAlign: "center",
        tip: false,
        columnBtn: false,
        searchBtn: true,
        delBtn: false,
        searchShow: true,
        editBtnText: '移 交',
        editTitle: '移 交',
        viewBtn: true,
        menuWidth: 170,
        searchMenuSpan: 6,
        border: true,
        index: false,
        indexLabel: "序号",
        selection: true,
        dialogType: "drawer",
        dialogClickModal: false,
        formLabelWidth: '220px',
        column: [
          {
            label: "所属机构",
            prop: "createDept",
            type: "tree",
            multiple: false,
            dicData: this.depTree,
            props: {
              label: "title",
              value: 'value'
            },
            checkStrictly: true,
            span: 24,
            search: true,
            change: this.deptChange
          },
          {
            label: "姓名",
            prop: "name",
            // search: true,
            span: 24,
            viewDisplay: false,
            rules: [
              {
                required: true,
                whitespace: true,
                message: "请输入姓名",
                trigger: "blur",
              },
            ],
            slot: true,
            search: true,
            editDisabled: true,
            editDisplay: false
          },
          {
            label: "姓别",
            prop: "aac004",
            type: 'select',
            viewDisplay: false,
            dicUrl: "/api/jobslink-api/system/dict-biz/tadict?code=AAC004",
            editDisplay: false,
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            editDisabled: true,
            rules: [
              {
                required: true,
                message: "请输入性别",
                trigger: "blur",
              },
            ],
            span: 24,

          },
          {
            label: "身份证",
            prop: "idNumber",
            editDisplay: false,
            viewDisplay: false,
            // hide: true,
            span: 24,
            rules: [
              {required: true, message: "请输入身份证号", trigger: "blur"},
              {trigger: "blur", validator: IdCardNo},
            ],
            search: true,
            editDisabled: true,
          },
          {
            label: "手机号",
            prop: "telphone",
            editDisplay: false,
            viewDisplay: false,
            span: 24,
            hide: false,
            editDisabled: true,
            rules: [
              {
                required: true,
                validator: validateTel,
                trigger: "blur",
              },
            ],
          },
          {
            label: "民族",
            prop: "aac005",
            type: 'select',
            editDisabled: true,
            editDisplay: false,
            viewDisplay: false,
            dicUrl: "/api/jobslink-api/system/dict-biz/tadict?code=AAC005",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            rules: [
              {
                required: true,
                message: "请输入民族",
                trigger: "blur",
              },
            ],
            span: 24,
          },
          {
            label: "户口性质",
            prop: "aac009",
            type: 'select',
            editDisabled: true,
            editDisplay: false,
            viewDisplay: false,
            dicUrl: "/api/jobslink-api/system/dict-biz/tadict?code=AAC009",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            rules: [
              {
                required: true,
                message: "请输入户口性质",
                trigger: "blur",
              },
            ],
            span: 24,
          },
          {
            label: "户口所在地",
            prop: "aac010",
            // hide: true,
            span: 24,
            editDisabled: true,
            editDisplay: false,
            viewDisplay: false,
            rules: [
              {required: true, message: "请输入口所在地", trigger: "blur"},
            ],
          },
          {
            label: "文化程度",
            prop: "aac011",
            editDisabled: true,
            editDisplay: false,
            viewDisplay: false,
            type: 'select',
            dicUrl: "/api/jobslink-api/system/dict-biz/tadict?code=AAC011",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            rules: [
              {
                required: true,
                message: "请输入文化程度",
                trigger: "blur",
              },
            ],
            span: 24,
          },
          {
            label: "是否已核实",
            prop: "isConfirm",
            type: 'select',
            display: false,
            viewDisplay: false,
            dicData: [
              {
                value: -1,
                label: "",
              },
              {
                value: 0,
                label: "否",
              },
              {
                value: 1,
                label: "是",
              },
            ],
          },
          {
            label: "经办时间",
            prop: "aae036",
            display: false,
            viewDisplay: false,
            span: 24,
            editDisabled: true,
            editDisplay: false,
            rules: [
              {required: true, message: "请输入经办时间", trigger: "blur"},
            ],
          },
          {
            label: "用户类型",
            prop: "userId",
            type: "select",
            editDisabled: true,
            editDisplay: false,
            viewDisplay: false,
            dicData: [
              {
                value: "0",
                label: "未注册用户",
              },
              {
                value: "1",
                label: "已注册用户",
              },
            ],
            display: false,
            hide: true,
            // search: true
          },
          {
            label: "分组",
            prop: "groupId",
            type: "tree",
            span: 24,
            viewDisplay: false,
            editDisabled: true,
            editDisplay: false,
            dicData: self.treeData,
            props: {
              label: "groupName",
              value: "id",
            },
            rules: [
              {
                required: true,
                message: "请选择分组",
                trigger: "change",
              },
            ],
            placeholder: "请选择 分组",
          },
          {
            label: "标签名称",
            prop: "labelsBase",
            editDisplay: false,
            editDisabled: true,
            viewDisplay: false,
            rules: [
              {
                required: false,
                message: "请选择标签名称",
                trigger: ["blur"],
              },
            ],
            slot: true,
            formslot: true,
            span: 24,
          },
          {
            label: "备注",
            prop: "remarks",
            type: "textarea",
            editDisplay: false,
            viewDisplay: false,
            slot: true,
            hide: true,
            span: 24,
            maxlength: 100,
            showWordLimit: true,
          },
          {
            label: '',
            prop: 'employInfoList',
            formslot: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            span: 24,
            labelPosition: 'top', //标签位置
          }
        ],
      };
    },
    excelOption() {
      const baseUrl = upload() + `&deptId=${this.deptId}`
      const url = this.tenantId ? `${baseUrl}&id=${this.tenantId}` : baseUrl

      return {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "所属机构",
            prop: "deptId",
            type: "tree",
            multiple: false,
            dicData: this.depTree,
            props: {
              label: "title",
              value: 'value'
            },
            checkStrictly: true,
            slot: true,
            span: 20,
            change: this.deptChange
          },
          {
            label: "文件上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "文件上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            accept: excelAccept,
            showFileList: false,
            action: url,
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      }
    },
    selectedWorkTypes: {
      get() {
        if (!this.obj.labelsBase) {
          return [];
        }
        const result = [];
        const wt = this.obj.labelsBase.split(",");
        wt.forEach((item) => {
          result.push({name: item});
        });
        return result;
      },
      set(val) {
        const arr = [];
        val.forEach((item) => {
          arr.push(item.name);
        });
        this.obj.labelsBase = arr.join(",");
      },
    },
    worktypeData() {
      let rel = [];
      for (let j = 0; j < this.arr.length; j++) {
        const key = this.arr[j];
        if (this.worktypeDic.hasOwnProperty(key)) {
          rel.push({name: key})
        }
      }
      /* for (const key in this.worktypeDic) {
         if (this.worktypeDic.hasOwnProperty(key)) {
           rel.push({ name: key });
         }
       }*/
      for (let i = 0; i < this.tempWorkType.length; i++) {
        const key = this.tempWorkType[i];
        if (key && !this.worktypeDic.hasOwnProperty(key)) {
          rel.push({name: key});
        }
      }
      return rel;
    },
    logOption() {
      return {
        editBtn: true,
        delBtn: true,
        addBtn: true,
        viewBtn: true,
        border: true,
        index: true,
        indexLabel: "序号",
        refreshBtn: false,
        dialogType: "drawer",
        addBtnText: "新增日志",
        height: '100',
        column: [{
          label: '服务时间',
          prop: 'createTime',
          type: 'date',
          format: "yyyy-MM-dd",
          valueFormat: "yyyy-MM-dd HH:mm:ss",
          rules: [
            {
              required: true,
              message: "请选择服务时间",
              trigger: "blur",
            },
          ],
        }, {
          label: '服务发起人',
          prop: 'fromName',
          display: false,
        }, {
          label: '服务对象',
          prop: 'toName',
          display: false,
        }, {
          label: '服务主题',
          prop: 'serveTheme',
          rules: [
            {
              required: true,
              message: "请输入服务主题",
              trigger: "blur",
            },
          ],
        }, {
          label: '服务内容',
          type: 'textarea',
          prop: 'serveContent',
          span: 24,
          rules: [
            {
              required: true,
              message: "请输入服务内容",
              trigger: "blur",
            },
          ],
        }, {
          label: '备注说明',
          type: 'textarea',
          prop: 'bak1',
          span: 24,
        }]
      }
    }
  },
  created() {
    this.initDept();
    // this.getWorkTypes();
    this.getLabelList();
    this.getDept()
  },
  methods: {
    splitDate(time) {
      if (!time) return
      return `${time.slice(0, 4)}年${time.slice(4, 6)}日`
    },
    dateFormat: dateFormat,
    rowStyle(column) {
      // const groupId = column.row.groupId
      // const groupInfo = this.treeData.find((item) => item.id === groupId)
      // if (groupInfo.groupName === '潜在就业困难人员' || groupInfo.groupName === '潜在就业见习申请人员') {
      //   console.log(this.option.column[15])
      //   // this.option.column[15].viewDisplay = true
      // } else {
      //   console.log(this.option.column[15])
      //   // this.option.column[15].viewDisplay = false
      // }
    },
    checkUserInfo(row) {
      this.dialogInfo = row
      const groupInfo = this.treeData.find((item) => item.id === row.groupId)
      this.selectGroupName = groupInfo.groupName
      switch (groupInfo.groupName) {
        case '潜在就业困难人员':
          this.dialogTips = ['人员已经死亡', '已经进行就业登记', '享受养老保险待遇', '不满足男性大于等于50岁女性大于等于40岁', '不满足失业登记一年以上', '存在工商信息']
          break
        case '潜在登记失业人员':
          this.dialogTips = ['不满足断保3个月', '存在工商信息']
          break
        case '潜在失业保险金申领人员':
          this.dialogTips = ['已经进行就业登记', '享受养老保险待遇', '存在工商信息', '连续参保不满一年']
          break
        case '潜在就业困难人员中以个人身份参保人员':
          this.dialogTips = ['已经进行就业登记', '存在工商信息', '不是以个人身份参保']
          break
        case '潜在公益性岗位申请人员':
          this.dialogTips = ['人员已经死亡', '已经进行就业登记', '享受养老保险待遇', '不满足男性大于等于50岁女性大于等于40岁', '不满足失业登记一年以上', '存在工商信息']
          break
        case '潜在就业见习申请人员':
          this.dialogTips = ['已经进行就业登记', '不满足16-24岁']
          break
        default :
          this.dialogTips = []
      }
      this.dialogFlag = true
    },
    diaLogCancel(value) {
      if (value) {
        let params = {
          idNumber: this.dialogInfo.idNumber,
          id: this.dialogInfo.id,
          name: this.dialogInfo.name,
          approvalStatus: 1,
          content: value,
        }
        this.$confirm("确定数据不符合?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return talentsApproval(params);
          })
          .then(() => {
            // this.initDept();
            this.onLoad(this.page, this.query);
            this.dialogFlag = false
            this.$message.success('操作成功');
          });
      } else {
        this.$message.error("请填写驳回原因");
      }
    },
    diaLogConfirm(value) {
      // if (this.GroupValue) {
      let params = {
        idNumber: this.dialogInfo.idNumber,
        id: this.dialogInfo.id,
        name: this.dialogInfo.name,
        approvalStatus: 0,
        content: value,
        // groupId: this.GroupValue
      }
      this.$confirm("确定通过?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return talentsApproval(params);
        })
        .then(() => {
          // this.initDept();
          // this.onLoad(this.page, this.query);
          this.dialogFlag = false
          this.$message.success('操作成功');
        });
      // } else {
      //   this.$message.error("请选择分组");
      // }
    },
    handleExport() {
      this.downloadButton = true
      // 0 潜在 1 已认定
      getTemplateRecommendExportList({
        groupType: 0,
        ...this.query
      }).then((response) => {
        const blob = window.URL.createObjectURL(new Blob([response.data], {type: response.headers['content-type']}));
        let fileName = decodeURI(response.headers['content-disposition'].split(';')[1].split('filename=')[1])
        let a = document.createElement('a')
        let event = new MouseEvent('click')
        a.download = fileName || Date.now() + '.xlsx'
        a.href = blob
        a.dispatchEvent(event)
        this.downloadButton = false
      })

    },
    deptChange({value, column}) {
      this.deptId = value
      console.log(value)
    },
    async getDept() {
      let params = {
        tenantId: '000000'
      }
      let resData = await getDeptMyTree(params)
      if (resData.data.code === 200) {
        this.depTree = resData.data.data
        console.log(this.depTree)

      }
    },
    getWorkTypes() {

      getWorkTypes().then((res) => {

        for (let i = 0; i < res.data.data.length; i++) {
          const element = res.data.data[i];
          this.worktypeDic[element.name] = 1;
          this.arr.push(element.name)

        }
      });
    },
    getLabelList() {
      getLabelList().then(async (res) => {
        const arr = res.data.data.flatMap(obj => obj.child.map(item => item.concatName));
        this.arr = arr.map(concatName => {
          return {name: concatName};
        });
      });
    },
    /*加载分组*/
    initDept(groupId) {
      getDept({groupType: 0}).then((res) => {
        const data = res.data.data.list;
        this.selecTreeData = data;
        this.treeData = data;
        let treeDataOne = {
          companyId: "",
          createTime: "",
          groupName: "全部",
          id: "",
          remarks: "",
          sort: '',
          sumNum: res.data.data.sum,
          type: '',
        };
        this.treeData.unshift(treeDataOne);
        const column = this.findObject(this.option.column, "groupId");
        column.dicData = this.treeData;
        if (groupId) {
          this.$nextTick(function () {
            this.$refs.tree.setCurrentKey(groupId);
          }); //默认高亮
          this.nodeClick({id: groupId});
        } else {
          if (this.treeData.length) {
            this.$nextTick(function () {
              this.$refs.tree.setCurrentKey(this.treeData[0].id);
            }); //默认高亮第一个
            this.nodeClick({id: this.treeData[0].id});
          }
        }
        this.personTotal = res.data.data.sum;
        // this.onLoad();
        //this.treeData.push(treeDataOne);
        this.loading = false;
      });
    },
    /*新建 编辑分组*/
    updateGroups(type, data) {
      this.$refs.addGroups.openDialog(type, data);
    },
    /*删除分组*/
    removeGroups(data) {
      //检验该分组是否存在人员,存在提示无法删除，不存在泽提示确定要删除此分组吗
      const h = this.$createElement;
      this.$confirm(
        h("div", null, [
          h("p", {style: "font-size: 16px"}, "您确定要删除此分组吗? "),
          h("p", {style: "color: red"}, "一旦删除则无法找回"),
        ]),
        {
          type: "warning",
          showClose: false,
          showCancelButton: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          beforeClose: (action, instance, done) => {
            if (action === "confirm") {
              instance.confirmButtonLoading = true;
              instance.cancelButtonLoading = true;
              instance.closeOnPressEscape = false;
              instance.closeOnClickModal = false;
              setTimeout(() => {
                done();
                setTimeout(() => {
                  instance.confirmButtonLoading = false;
                  instance.cancelButtonLoading = false;
                }, 300);
              }, 1000);
            } else {
              done();
            }
          },
        }
      )
        .then(() => {
          removeDept(data.id).then(
            () => {
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.refresh("del");
            },
            (error) => {
              window.console.log(error);
            }
          );
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消'
          // });
        });
    },
    /*批量转移分组 */
    handleTransfer() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$refs.transferGroups.openDialog();
    },
    /*点击分组加载相应人才列表*/
    nodeClick(data) {
      this.tenantId = data.id ? data.id : "";
      this.selectInfo = data
      this.page.currentPage = 1;
      this.onLoad(this.page, this.query);
      // if (this.tenantId !== data.id) {

      // } else {
      //   return;
      // }
    },
    /*新增 编辑 转移  删除分组 更新人才后*/
    refresh(type) {
      this.page.currentPage = 1;
      this.query = {};
      if (type === "del") {
        //删除分组后重新选中分组为未分组
        this.initDept();
        this.onLoad(this.page, this.query);
      } else {
        this.initDept(this.tenantId);
        this.onLoad(this.page, this.query);
      }
    },
    /*获取人才详情 */
    beforeOpen(done, type) {
      if (["edit", "view", "add"].includes(type)) {
        if (type === "edit" || type === "view") {
          setTimeout(() => {
            detail(this.obj.id).then(
              (res) => {
                console.log(res)
                this.obj = res.data.data;
                this.tempWorkType = this.obj.labelsBase.split(",");
                done();
              },
              (error) => {
                window.console.log(error);
              }
            );
          }, 0);
        } else {
          this.tempWorkType = [];
          done();
        }
      }
    },
    /*新增人才*/
    rowSave(row, done) {
      let obj = {}
      for (const rowKey in row) {
        if (row[rowKey]) {
          obj[rowKey] = row[rowKey]
        }
      }
      add({
        ...obj,
        groupId: row.groupId,
        name: row.name,
        idNumber: row.idNumber,
        telphone: row.telphone,
        labelsBase: row.labelsBase,
        remarks: row.remarks,
        groupType: 0,
      }).then(
        () => {
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
          this.refresh();
        },
        (error) => {
          window.console.log(error);
          done();
        }
      );
    },
    /*编辑人才*/
    rowUpdate(row, index, done) {
      update({
        ...row,
        id: row.id,
        groupId: row.groupId,
        name: row.name,
        idNumber: row.idNumber,
        telphone: row.telphone,
        labelsBase: row.labelsBase,
        remarks: row.remarks,
      }).then(
        () => {
          done();
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.refresh();
        },
        (error) => {
          window.console.log(error);
          done();
        }
      );
    },
    /*删除人才 */
    rowDel(row) {
      const h = this.$createElement;
      this.$confirm(
        h("div", null, [
          h("p", {style: "font-size: 16px"}, "您确定要删除此人才吗? "),
          h("p", {style: "color: red"}, "一旦删除则无法找回"),
        ]),
        {
          type: "warning",
          showClose: false,
          showCancelButton: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          beforeClose: (action, instance, done) => {
            if (action === "confirm") {
              instance.confirmButtonLoading = true;
              instance.cancelButtonLoading = true;
              instance.closeOnPressEscape = false;
              instance.closeOnClickModal = false;
              setTimeout(() => {
                done();
                setTimeout(() => {
                  instance.confirmButtonLoading = false;
                  instance.cancelButtonLoading = false;
                }, 300);
              }, 1000);
            } else {
              done();
            }
          },
        }
      )
        .then(() => {
          remove(row.id).then(
            () => {
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.refresh();
            },
            (error) => {
              window.console.log(error);
            }
          );
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消'
          // });
        });
    },
    /*批量删除人才*/
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      const h = this.$createElement;
      this.$confirm(
        h("div", null, [
          h("p", {style: "font-size: 16px"}, "您确定要批量删除选中人才吗? "),
        ]),
        {
          type: "warning",
          showClose: false,
          showCancelButton: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          beforeClose: (action, instance, done) => {
            if (action === "confirm") {
              instance.confirmButtonLoading = true;
              instance.cancelButtonLoading = true;
              instance.closeOnPressEscape = false;
              instance.closeOnClickModal = false;
              setTimeout(() => {
                done();
                setTimeout(() => {
                  instance.confirmButtonLoading = false;
                  instance.cancelButtonLoading = false;
                }, 300);
              }, 1000);
            } else {
              done();
            }
          },
        }
      )
        .then(() => {
          remove(this.ids).then(
            () => {
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.onLoad(this.page);
              this.$refs.crud.toggleSelection();
            },
            (error) => {
              window.console.log(error);
            }
          );
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消'
          // });
        });
    },
    /*导入人才库*/
    beforeAvatarUpload(file, done, loading) {
      console.log(file)
      if (!isExcel(file)) {
        loading();
        this.$message.error("上传人才库信息只能是 .xls,.xlsx 标准格式文件!");
      } else {
        done();
      }
    },
    uploadAfter(res, done) {
      if (!(res instanceof Error) && !res.data) {
        this.excelBox = false;
      } else if (res.data && res.data.code === 900) {
        const arr = [];
        const data = res.data.data;
        data.error &&
        data.error.errorList.forEach((item) => {
          arr.push(`${item.name} ${item.remarks}`);
        });
        data.auth &&
        data.auth.authList.forEach((item) => {
          arr.push(`${item.name} ${item.remarks}`);
        });
        this.$refs.ied.show(arr);
      }
      this.refreshChange();
      this.initDept(this.tenantId);
      done();
    },
    uploadError(error) {
      if (error) {
        this.$message.error(error);
      }
    },
    handleImport() {
      this.excelBox = true;
    },
    /*下载人才库模板 */
    handleTemplate() {
      this.templateLoading = true;
      getTemplate("rqkdr")
        .then((rep) => {
          this.templateLoading = false;
          window.open(rep.data.data);
        })
        .catch(() => {
          this.templateLoading = false;
        });
    },
    /*人才列表切换页码 */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.refreshChange();
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.refreshChange();
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    /*搜索 */
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    /*人才列表多选 */
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    async saveLog(row, index, done, loading) {
      let params = {
        ...row,
        serveId: this.selectUserServeLog.serveId,
        serveUserId: this.selectUserServeLog.serveUserId,
        talentsId: this.selectUserServeLog.id,
        idNumber: this.selectUserServeLog.idNumber,
        toName: this.selectUserServeLog.name,
        fromName: this.userInfo.real_name
      }
      console.log(params)
      let resData = await addServeLog(params)
      done()
      if (resData.data.code === 200) {
        this.$message({
          type: "success",
          message: "添加成功!",
        });
        this.serveLog(this.selectUserServeLog)
      }
    },
    async saveUpdateLog(row, index, done, loading) {
      let params = {
        id: row.id,
        createTime: row.createTime,
        fromName: row.fromName,
        toName: row.toName,
        serveTheme: row.serveTheme,
        serveContent: row.serveContent,
        bak1: row.bak1,
      }
      let resData = await updateServeLog(params)
      done()
      if (resData.data.code === 200) {
        this.$message({
          type: "success",
          message: "修改成功!",
        });
        this.serveLog(this.selectUserServeLog)
      }
    },
    removeLog(row, index, done, loading) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return removeServeLog({ids: row.id});
        })
        .then(() => {
          this.serveLog(this.selectUserServeLog)
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    handleCloseLog() {
      this.innerDrawerLog = false
    },
    logSizeChange(pageSize) {
      this.logPage.pageSize = pageSize;
      this.serveLog(this.selectUserServeLog)
    },
    logCurrentChange(currentPage) {
      this.logPage.currentPage = currentPage;
      this.serveLog(this.selectUserServeLog)
    },
    serveLog(row) {
      console.log('服务日志', row)
      this.selectUserServeLog = row
      this.loadingLog = true
      getMainServeUserLog({
        idNumber: row.idNumber,
        current: this.logPage.currentPage,
        size: this.logPage.pageSize
      }).then(res => {
        this.loadingLog = false
        const {records, current, size, total} = res.data.data
        this.logDataSource = records
        this.innerDrawerLog = true
        this.logPage = {
          pageSize: size,
          currentPage: current,
          total: total,
        }
      })
    },
    /*加载人才列表 */
    onLoad(page, params = {}) {
      const paramsd = {
        ...params,
        ...this.query,
        groupType: 0
      }
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        paramsd,
        this.tenantId
      ).then((res) => {
        res.data.data.records.forEach(item => {
          item.labelsBaseArr = item.labelsBase.split(',');
        })
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
  },
};
</script>

<style scoped>
.el-tree {
  font-size: 14px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.el-form-item {
  margin-bottom: 18px;
  padding: 0 10px;
}

.searchBtn {
  display: inline-block;
  margin-bottom: 18px;
}
</style>
