<template>
  <div>
    <el-row>
      <el-col :span="6">
        <basic-container>
          <div style="display: flex; justify-content: space-between; align-items: center">
            <div>服务分组管理</div>
            <div>
              <el-button type="text" icon="el-icon-plus"
                v-if="vaildData(permission.tenant_main_serve_index_groupadd, false)" @click="updateGroups('add')">新建分组
              </el-button>
            </div>
          </div>
          <div class="box" :style="{ height: leftHeight }">
            <el-scrollbar style="height: 100%">
              <el-tree ref="tree" node-key="id" highlight-current @node-click="nodeClick" :default-expand-all="true"
                :data="treeData" :props="{ label: 'groupName', id: 'id' }">
                <span class="custom-tree-node" slot-scope="{ node, data }" style="width: 80%">
                  <span style="
                    flex-basis: 80%;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                    flex-shrink: 1;
                  ">
                    {{ data.groupName || data.name }}
                  </span>
                  <span v-show="data.children && 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_serve_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_serve_index_groupdel, false)"
                      @click="() => removeGroups(data)">
                    </el-button>
                  </span>
                </span>
              </el-tree>
            </el-scrollbar>
          </div>
        </basic-container>
      </el-col>
      <el-col :span="18">
        <basic-container>
          <avue-crud v-model="obj" ref="crud" :data="dataSource" :option="option" :search.sync="query" :page.sync="page"
            :table-loading="loading" @search-change="serveSearchChange" @search-reset="serveResetChange"
            @size-change="infoSizeChange" @current-change="infoCurrentChange">
            <!--            <template slot="menuLeft">-->
            <!--              <el-button type="primary" size="small" @click="selectPushService">推送服务</el-button>-->
            <!--            </template>-->
            <template slot-scope="{row,index}" slot="menu">
              <!--              <el-button type="text"-->
              <!--                         icon="el-icon-document"-->
              <!--                         size="small"-->
              <!--                         @click="matchWorkStation(row)"-->
              <!--              >查看匹配岗位-->
              <!--              </el-button>-->
              <!--              <el-button type="text"-->
              <!--                         icon="el-icon-document"-->
              <!--                         size="small"-->
              <!--                         @click="matchPolicy(row)"-->
              <!--              >查看匹配政策-->
              <!--              </el-button>-->
              <el-button type="text" icon="el-icon-document" size="small" @click="phoneDataList(row)">回访
              </el-button>
              <el-button type="text" icon="el-icon-document" size="small" @click="selectPushUserService(row)">推送服务
              </el-button>
              <el-button type="text" icon="el-icon-document" size="small" @click="serveLog(row)">管理服务日志
              </el-button>
            </template>
          </avue-crud>
        </basic-container>
      </el-col>
    </el-row>
    <!--  匹配任务/岗位  -->
    <el-drawer title="匹配任务/岗位" size="80%" :append-to-body="true" :before-close="() => innerDrawer1 = false"
      :visible.sync="innerDrawer1">
      <avue-crud :data="workData" :option="workOption" :page.sync="workPage" @size-change="workSizeChange"
        @current-change="workCurrentChange">
        <template slot="missionDesc" slot-scope="{ row }">
          <TextTooltip :content="row.missionDesc"></TextTooltip>
        </template>
        <template slot-scope="{row,index}" slot="menu">
          <el-button type="text" icon="el-icon-document" size="small" @click="toWorkMissionDetail(row)">查看详情
          </el-button>
        </template>
      </avue-crud>
    </el-drawer>
    <!--    匹配政策-->
    <el-drawer title="匹配政策" size="80%" :append-to-body="true" :before-close="() => innerDrawer2 = false"
      :visible.sync="innerDrawer2">
      <avue-crud :data="policyData" :option="policyOption" :page.sync="policyPage" @size-change="policySizeChange"
        @current-change="policyCurrentChange">
        <template slot="policyContent" slot-scope="{ row }">
          <el-tooltip class="item" effect="dark" placement="top-start">
            <div slot="content">
              <div v-for="(item, index) in clipStr(row.policyContent)" :key="index2">
                <div>{{ item }}</div>
              </div>
            </div>
            <span>{{ row.policyContent.length > 50 ? row.policyContent.substring(0, 50) : row.policyContent }}</span>
          </el-tooltip>
        </template>
        <template slot="labelName" slot-scope="{ row }">
          <el-tooltip class="item" effect="dark" placement="top-start">
            <div slot="content">
              <div v-for="(item, index) in clipStr(row.labelName)" :key="index2">
                <div>{{ item }}</div>
              </div>
            </div>
            <span>{{ row.labelName.length > 50 ? row.labelName.substring(0, 50) : row.labelName }}</span>
          </el-tooltip>
        </template>
        <template slot="labelNameForm" slot-scope="{row}">
          <div>
            <el-tag style="margin: 4px 10px" v-for="(item, index) in row.labelName.split(',')" :key="index2">{{
              item
            }}
            </el-tag>
          </div>
        </template>

        <template slot="guidelineContentForm" slot-scope="{row}">
          <div>
            <Tinymce v-model="row.guidelineContent" :visibleToolbar="false" :visibleMenubar="false"></Tinymce>
          </div>
        </template>
        <template slot="policyContentForm" slot-scope="{row}">
          <div>
            <Tinymce v-model="row.policyContent" :visibleToolbar="false" :visibleMenubar="false"></Tinymce>
          </div>
        </template>

      </avue-crud>
    </el-drawer>
    <!--    服务日志-->
    <el-drawer title="服务日志" size="80%" :append-to-body="true" :before-close="() => innerDrawer3 = false"
      :visible.sync="innerDrawer3">
      <!-- <div>
        <span>姓名：</span>
        <span>身份证号：</span>
      </div> -->
      <avue-crud :data="logData" :option="logOption" @row-save="saveLog" @row-update="saveUpdateLog"
        @row-del="removeLog" :page.sync="logPage" @size-change="logSizeChange" @current-change="logCurrentChange"
        ref="logCrud">
        <!-- <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> -->
        <template slot-scope="{row,index}" slot="menu">
          <el-button type="text" icon="el-icon-edit" size="small"
            v-if="row.serveTheme !== '人工推送岗位' && row.serveTheme !== '人工推送政策'" v-show="row.serveName === '手工录入服务日志'"
            @click="$refs.logCrud.rowEdit(row, index2)">编辑
          </el-button>
          <el-button type="text" icon="el-icon-edit" size="small" v-show="row.serveName === '手工录入服务日志'"
            @click="$refs.logCrud.rowDel(row, index2)">删除
          </el-button>
        </template>
      </avue-crud>
    </el-drawer>
    <!--新建 编辑分组dialog-->
    <add-groups ref="addGroups" @refresh="refresh" :listAllPolicyTree="listAllPolicyTree" :treeData="treeData"
      :data="worktypeData" :worktypeDic="worktypeDic" :talentsList="talentsList"></add-groups>
    <PushService :visible.sync="PushServiceVisible" :rowData="selectPushServiceData" :phoneItem="phoneItem"
      :selectInfo="selectInfo" ref="pushRef"></PushService>

    <mission-view :visible.sync="viewDrawer" :model="view"></mission-view>

    <work-view :visible.sync="workViewDrawer" :model="workViewModel"></work-view>

    <FollowUpDialog :visible.sync="phoneDialogVisible" :item="phoneItem" :serveId="selectInfo ? selectInfo.id : null"
      :phoneList="phoneList" :workSkillsOptions="workSkillsOptions" :areaOptions="areaOptions" :selectInfo="selectInfo"
      :exitReasonOptions="exitReasonOptions" @curdUpdate="callbackPopup" />
  </div>
</template>

<script>
import {
  addServeLog, detail,
  getDepTree,
  getList,
  getListAllPolicy,
  getListAllTalents, getMatchPolicy, getMatchServeList, getMatchWorkStation,
  getServeListTalents,
  removeDept, removeServeLog, updateServeLog, getPhoneList, serveRegion, serveExitReason
} from "@/api/tenant/serve";
import { mapGetters } from "vuex";
import addGroups from "./Dialog/addGroup";
import { getLabelList, getWorkTypes } from "@/api/tenant/common";
import missionView from "../../mission/Table/missionView.vue";
import workView from "../../works/Table/missionView.vue"
import TextTooltip from "@/components/text-tooltip/index.vue";
import { serveTypeOptions, serviceType } from "@/common/dic";
import PushService from './Dialog/pushService2.vue'
import { getDeptMyTree } from "@/api/tenant/talents";
import FollowUpDialog from "@/views/tenant/main/serve/followUpVisit/qzjyknry.vue";

const page = {
  size: 10,
  currentPage: 1,
  total: 0,
}
export default {
  components: { FollowUpDialog, addGroups, missionView, workView, TextTooltip, PushService },
  data() {
    return {
      exitReasonOptions: [],
      arr: [],
      worktypeDic: {},
      arr_2: [],
      worktypeDic_2: {},
      workSkillsOptions: [],
      areaOptions: [],
      treeData: [],
      loading: false,
      tenantId: null,
      page: Object.assign({}, page),
      workPage: Object.assign({}, page),
      dataSource: [],
      tempWorkType: [],
      talentsList: [],
      query: {},
      obj: {},
      selectInfo: null,
      innerDrawer1: false,
      viewDrawer: false,
      workViewDrawer: false,
      workViewModel: {},
      view: {},
      workData: [],
      policyData: [],
      innerDrawer2: false,
      policyPage: Object.assign({}, page),
      innerDrawer3: false,
      logData: [],
      logPage: Object.assign({}, page),
      selectUserServeLog: null,
      selectPushServiceData: null,
      PushServiceVisible: false,
      phoneDialogVisible: false,
      phoneList: [],
      phoneForm: {
        phone: '',
        list: [],
        isServe: 0,
        isTrain: 0,
        isWork: 1,
        salary: 4000,
        workSkillOne: '',
        workSkillTwo: '',
      },
      phoneItem: null,
      depTree: [],
      rules: {
        isServe: [
          { required: true, message: '请选择是否服务', trigger: 'change' }
        ],
        isTrain: [
          { required: true, message: '请选择是否培训', trigger: 'change' }
        ],
        isWork: [
          { required: true, message: '请选择是否有就业意愿', trigger: 'change' }
        ],
        salary: [
          { required: true, message: '请选择期望薪资', trigger: 'change' }
        ],
      },
      logOption: {
        editBtn: false,
        delBtn: false,
        addBtn: true,
        viewBtn: true,
        border: true,
        index: true,
        indexLabel: "序号",
        refreshBtn: false,
        dialogType: "drawer",
        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: 'serveName',
          display: false,
        }, {
          label: '服务发起人',
          prop: 'fromName',
          display: false,
        }, {
          label: '服务对象',
          prop: 'toName',
          display: false,
        }, {
          label: '服务类型',
          prop: 'serveType',
          type: 'select',
          dicData: serveTypeOptions,
          display: false,
        }, {
          label: '服务主题',
          prop: 'serveTheme',
          rules: [
            {
              required: true,
              message: "请输入服务主题",
              trigger: "blur",
            },
          ],
        }, {
          label: '服务内容',
          span: 24,
          prop: 'serveContent',
          type: 'textarea',
          rules: [
            {
              required: true,
              message: "请输入服务内容",
              trigger: "blur",
            },
          ],
        }, {
          label: '备注说明',
          span: 24,
          type: 'textarea',
          prop: 'bak1'
        }]
      }
    }
  },
  computed: {
    ...mapGetters(["permission", "userInfo"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.tenant_main_serve_index_add, false),
        viewBtn: true,
        delBtn: this.vaildData(this.permission.tenant_main_serve_index_del, false),
        editBtn: this.vaildData(this.permission.tenant_main_serve_index_edit, false),
      };
    },
    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";
      }
    },
    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 (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;
    },
    option() {
      const unemployedCollegeStudents = this.selectInfo && this.selectInfo.name === '离校未就业大学生'
      return {
        dialogWidth: "50%",
        dialogType: "drawer",
        dialogClickModal: false,
        editBtn: false,
        delBtn: false,
        addBtn: false,
        viewBtn: false,
        border: true,
        refreshBtn: false,
        searchBtn: true,
        searchShow: true,
        searchMenuSpan: 6,
        height: '100',
        column: [
          {
            label: "服务机构",
            prop: "companyName",
            type: "tree",
            multiple: false,
            dicData: this.depTree,
            props: {
              label: "title",
              value: 'value'
            },
            checkStrictly: true,
            search: true,
            span: 20,
            // hide: true,
            searchLabelWidth: 80,
            searchSpan: 8,
          },
          {
            label: "姓名",
            prop: "name",
            search: false,
          },
          {
            label: "身份证",
            prop: "idNumber",
            search: true,
            searchLabelWidth: 100,
            searchSpan: 8,
          },
          // {
          //   label: '专业',
          //   prop: 'aac183Major'
          // },
          {
            label: '性别',
            prop: 'aac004',
            type: 'select',
            dicUrl: "/api/jobslink-api/system/dict-biz/tadict?code=AAC004",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            rules: [
              {
                required: true,
                message: "请输入性别",
                trigger: "blur",
              },
            ],
          },
          {
            label: '常驻地址',
            prop: 'residentAddress',
          },
          {
            label: "是否本级",
            prop: "isCurrentLevel",
            dicData: [
              { value: 0, label: "是" },
              { value: 1, label: "否" },
            ],
            type: 'select',
            search: true,
            hide: true,
            searchLabelWidth: 100,
            searchSpan: 8,
          },
          {
            label: "是否回访",
            prop: "isBack",
            dicData: [
              { value: 1, label: "是" },
              { value: 0, label: "否" },
            ],
            type: 'select',
            search: true,
            hide: true,
            searchLabelWidth: 100,
            searchSpan: 8,
          },
          {
            label: "毕业年份",
            width: 100,
            prop: "year",
            sortable: true,
            overHidden: true,
            align: "center",
            type: "year",
            format: "yyyy",
            valueFormat: "yyyy",
            op: "ge,le",
            searchType: "year",
            hide: true,
            searchLabelWidth: 80,
            searchSpan: 8,
            search: unemployedCollegeStudents,
          },
          {
            label: '文化程度',
            prop: 'aac011',
            type: 'select',
            dicUrl: "/api/jobslink-api/system/dict-biz/tadict?code=AAC011",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
          },
          {
            label: '户口所在地',
            prop: 'aac010'
          },
          {
            label: "最小服务次数",
            prop: "serveCountDown", // 后端对应的【最小】次数查询字段
            type: "number",
            search: true,
            hide: true,           // 不在列表中展示
            display: false,       // 不在表单中展示
            searchSpan: 8,        // 栅格占 4 (两个加起来是 8)
            searchLabelWidth: 80,
          },
          {
            label: "最大服务次数",
            prop: "serveCountUp", // 后端对应的【最大】次数查询字段
            type: "number",
            search: true,
            hide: true,
            display: false,
            searchSpan: 8,        // 栅格占 4
            searchLabelWidth: 80,
          },
          // {
          //   label: "政策推送次数",
          //   prop: "servePolicyCount",
          //   searchType: 'number',
          //   search: unemployedCollegeStudents,
          //   searchLabelWidth: 100,
          //   searchSpan: 8,
          // },
          // {
          //   label: "岗位服务次数",
          //   prop: "serveCount",
          //   searchType: 'number',
          //   search: unemployedCollegeStudents,
          //   searchLabelWidth: 100,
          //   searchSpan: 8,
          // },
          {
            label: "服务次数",
            prop: "serveTotalCount",
          },
          {
            label: "识别原因",
            prop: "labelsBase",
          }
        ]
      }
    },
    workOption() {
      return {
        editBtn: false,
        delBtn: false,
        addBtn: false,
        border: true,
        index: true,
        indexLabel: "序号",
        refreshBtn: false,
        height: '100',
        column: [{
          label: "名称",
          prop: "missionTitle",
        }, {
          label: "描述",
          prop: "missionDesc",
          slot: true
        }]
      }
    },
    policyOption() {
      return {
        editBtn: false,
        delBtn: false,
        addBtn: false,
        border: true,
        index: true,
        indexLabel: "序号",
        refreshBtn: false,
        height: '100',
        viewBtn: true,
        dialogType: "drawer",
        column: [{
          label: '政策名称',
          prop: 'name'
        },
        {
          label: "政策级别",
          prop: "level",
          span: 12,
          hide: true,
        },
        {
          label: "政策文号",
          prop: "number",
          span: 12,
          hide: true,
        },
        {
          label: "发文机构",
          prop: "issuingAuthority",
          span: 12,
          hide: true,
        },
        {
          label: "分组",
          prop: "groupId",
          type: "tree",
          hide: true,
          span: 12,
          display: true,
          placeholder: "请选择 分组",
        },
        {
          label: "有效性",
          prop: "status",
          type: "tree",
          span: 12,
          hide: true,
          display: true,
          dicData: [{ name: "有效", value: 1 }, { name: "无效", value: 0 }],
          props: {
            label: "name",
            value: "value",
          },
        },
        {
          label: "服务类型",
          prop: "stype",
          type: "tree",
          span: 12,
          display: true,
          hide: true,
          dicData: serviceType,
          props: {
            label: "label",
            value: "value",
          },
          rules: [
            {
              required: true,
              message: "请选择服务类型",
              trigger: "change",
            },
          ],
          placeholder: "请选择 服务类型",
        },
        {
          label: "发文字号",
          prop: "issuingNumber",
          hide: true,
          span: 12,
          // row: true,
          maxlength: 50,
          showWordLimit: true,
        },
        {
          label: "类别",
          prop: "category",
          span: 12,
          hide: true,
          maxlength: 50,
          showWordLimit: true,
        },
        {
          label: "标签",
          prop: "labelName",
          hide: false,
          formslot: true,
          span: 24,
        },
        {
          label: "政策文件名",
          prop: "policyFileName",
          hide: true,
          span: 24,
        },
        {
          label: '政策内容',
          prop: 'policyContent',
          slot: true,
          hide: true,
          formslot: true,
          span: 24,
        },
        {
          label: "指南文件名",
          prop: "guidelineFileName",
          hide: true,
          span: 24,
          maxlength: 50,
          showWordLimit: true,
        },
        {
          label: "指南内容",
          prop: "guidelineContent",
          hide: true,
          formslot: true,
          span: 24,
        },
        {
          label: "备注",
          prop: "remarks",
          type: "textarea",
          hide: true,
          span: 24,
          maxlength: 100,
          showWordLimit: true,
        },
        ]
      }
    },
  },
  created() {
    this.initDept();
    this.getListAllPolicyTree()
    this.getLabelList()
    this.ListAllTalents()
    this.getDept()
  },
  methods: {
    async getDept() {
      let params = {
        tenantId: '000000'
      }
      let resData = await getDeptMyTree(params)
      if (resData.data.code === 200) {
        this.depTree = resData.data.data

      }
    },
    selectPushUserService(row) {
      this.selectPushService().then(() => {
        this.$nextTick(() => {
          this.phoneItem = row
          this.$refs.pushRef.upDateUser(row)
          this.$refs.pushRef.refLeftSearch(row.name)
        })
      })
    },
    // 5. 重写 phoneDataList 方法
    async phoneDataList(item) {
      // 开启 Loading
      const loadingInstance = this.$loading({
        lock: true,
        text: '正在加载数据...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      try {
        // 1. 获取电话列表
        let params = { idNumber: item.idNumber };
        let resData = await getPhoneList(params);

        // 2. (如果需要) 获取技能列表
        if (this.workSkillsOptions.length === 0) {
          let skillsRes = await getWorkTypes(1);
          if (skillsRes.data.code === 200) {
            this.workSkillsOptions = skillsRes.data.data;
          }
        }

        if (this.areaOptions.length === 0) {
          let regsRes = await serveRegion();
          if (regsRes.data.code === 200) {
            this.areaOptions = regsRes.data.data;
          }
        }

        if (this.exitReasonOptions.length === 0) {
          let Reason = await serveExitReason();
          if (Reason.data.code === 200) {
            this.exitReasonOptions = Reason.data.data;
          }
        }


        // 检查电话列表API结果
        if (resData.data.code === 200) {
          // 成功: 关闭 loading, 传递数据, 打开弹窗
          loadingInstance.close();
          this.phoneList = resData.data.data;
          this.phoneItem = item;
          this.phoneDialogVisible = true;
        } else {
          // 失败: 关闭 loading, 显示错误
          loadingInstance.close();
          this.$message.error("用户数据异常!");
        }

      } catch (error) {
        // 异常: 关闭 loading, 显示错误
        console.error("Error loading follow-up data:", error);
        loadingInstance.close();
        this.$message.error("获取用户数据失败!");
      }
    },
    /*点击分组加载相应人才列表*/
    nodeClick(data) {
      if (data.children) return;
      this.selectInfo = data
      this.tenantId = data.id ? data.id : "";
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    /*加载分组*/
    getLabelList() {
      getLabelList().then((res) => {
        const arr = res.data.data.flatMap(obj => obj.child.map(item => item.concatName));
        this.arr = arr.map(concatName => {
          this.worktypeDic[concatName] = 1;
          return concatName;
        });
      });
    },
    async ListAllTalents() {
      let resData = await getListAllTalents()
      if (resData.data.code === 200) {
        this.talentsList = resData.data.data
      }
    },
    initDept(groupId) {
      getDepTree().then((res) => {
        const data = res.data.data.list.map((item) => ({
          ...item,
          disabled: true
        }));
        this.treeData = data;
        // 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) {
            const serveId2 = this.treeData[0].id
            const serveId = this.treeData[0].children[0].id
            this.$nextTick(function () {
              this.$refs.tree.setCurrentKey(serveId);
            }); //默认高亮第一个
            this.nodeClick({ id: serveId });
          }
        }
        this.selectInfo = data[0].children[0]
        this.loading = false;
      });
    },
    async getListAllPolicyTree() {
      let resData = await getListAllPolicy({})
      if (resData.data.code === 200) {
        this.listAllPolicyTree = resData.data.data
      }
    },
    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(() => {
        });
    },
    callbackPopup() {
      this.onLoad(this.page, this.query);
    },
    /*加载人才列表 */
    onLoad(page, params = {}) {
      this.loading = true;
      let paramsed = {
        current: page.currentPage,
        size: page.size,
        id: this.tenantId,
      }
      for (const paramsKey in params) {
        params[paramsKey] !== '' ? paramsed[paramsKey] = params[paramsKey] : null
      }
      getServeListTalents(paramsed).then((res) => {
        const { records, current, size, total } = res.data.data
        this.dataSource = records
        this.loading = false;
        this.page.size = size
        this.page.currentPage = current
        this.page.total = total
        // this.selectionClear();
      });
    },
    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);
      }
    },
    serveSearchChange(params, done) {
      this.page.currentPage = 1;
      let newObj = Object.assign({}, params);
      if (params.companyName) {
        newObj.deptId = params.companyName
        delete newObj.companyName;
      }
      this.query = newObj
      this.onLoad(this.page, this.query);
      done();
    },
    serveResetChange() {
      this.page.currentPage = 1;
      this.query = {}
      this.onLoad(this.page, this.query);
    },
    infoSizeChange(size) {
      this.page.size = size;
      this.onLoad(this.page, this.query);
    },
    infoCurrentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page, this.query);
    },
    // 匹配任务和岗位
    matchWorkStation(row) {
      getMatchWorkStation({
        serveUserId: row.serveUserId,
        serveId: this.selectInfo.id,
        companyId: this.selectInfo.companyId
      }).then(res => {
        const { records, current, size, total } = res.data.data
        this.innerDrawer1 = true
        this.workData = records
        this.workPage.size = size
        this.workPage.currentPage = current
        this.workPage.total = total
      })
    },
    // 匹配政策
    matchPolicy(row) {
      getMatchPolicy({ id: row.id, serveId: this.selectInfo.id, serveUserId: row.serveUserId }).then(res => {
        let _this = this;
        const { records, current, size, total } = res.data.data
        _this.policyData = records
        _this.innerDrawer2 = true
        _this.policyPage.size = size
        _this.policyPage.currentPage = current
        _this.policyPage.total = total
      })
    },
    // 服务日志
    serveLog(row) {
      this.selectUserServeLog = row
      getMatchServeList({
        id: row.id,
        serveId: this.selectInfo.id,
        companyId: this.selectInfo.companyId,
        current: this.logPage.currentPage,
        size: this.logPage.size
      }).then(res => {
        let _this = this;
        const { records, current, size, total } = res.data.data
        _this.logData = records
        _this.innerDrawer3 = true
        _this.logPage.size = size
        _this.logPage.currentPage = current
        _this.logPage.total = total
      })
    },
    async saveLog(row, index, done, loading) {
      let params = {
        ...row,
        serveId: this.selectInfo.id,
        serveUserId: this.selectUserServeLog.serveUserId,
        talentsId: this.selectUserServeLog.id,
        idNumber: this.selectUserServeLog.idNumber,
        toName: this.selectUserServeLog.name,
        fromName: this.userInfo.real_name
      }
      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: "操作成功!",
          });
        });
    },
    logSizeChange(size) {
      this.logPage.size = size;
      this.serveLog(this.selectUserServeLog)
    },
    logCurrentChange(currentPage) {
      this.logPage.currentPage = currentPage;
      this.serveLog(this.selectUserServeLog)
    },
    workSizeChange() {
    },
    workCurrentChange() {
    },
    policySizeChange() {
    },
    policyCurrentChange() {
    },
    selectPushService() {
      return new Promise((resolve, reject) => {
        detail(this.selectInfo.id).then((res) => {
          if (res.data.code === 200) {
            this.selectPushServiceData = res.data.data
            this.PushServiceVisible = true
            resolve()
          }
        })
      })
      // this.selectPushServiceData = deepClone(this.selectInfo)
      // this.PushServiceVisible = true
    },
    /*查看*/
    toWorkMissionDetail(row) {
      if (row.type == 0) {
        missionDetail(row.missionNo).then((res) => {
          this.viewDrawer = true;
          this.view = res;
        });
      } else if (row.type == 1) {
        workDetail(row.id).then(res => {
          this.workViewDrawer = true;
          this.workViewModel = res;
        })
      }

    },
    clipStr(str) {
      const clip = []
      if (str && str.length > 50) {
        for (let i = 0; i < Math.ceil(str.length / 50); i++) {
          clip.push(str.slice(i * 50, i * 50 + 50))
        }
        return clip
      }
      return [str]
    },
  }
}
</script>

<style lang="scss" scoped></style>
