<template>
  <basic-container>
    <el-drawer
      title="已录用"
      append-to-body
      :visible.sync="drawer"
      size="80%"
      class="drawer"
      :before-close="drawerClose"
    >
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        ref="crud"
        v-model="obj"
        :permission="permissionList"
        @search-change="searchChange"
        @search-reset="searchReset"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        class="customPage"
        @on-load="onLoad"
      >
        <!--自定义列-->
        <template slot="period" slot-scope="{row}">
        <span v-if="row.startTime && row.endTime">
            <el-tag type="warning"
                    v-if="row.serviceStatus==0">{{ dateFormat(row.startTime) }}-{{ dateFormat(row.endTime) }}</el-tag>
            <el-tag type="success"
                    v-if="row.serviceStatus==1">{{ dateFormat(row.startTime) }}-{{ dateFormat(row.endTime) }}</el-tag>
            <el-tag type="danger"
                    v-if="row.serviceStatus==2">{{ dateFormat(row.startTime) }}-{{ dateFormat(row.endTime) }}</el-tag>
            <el-tag type="info"
                    v-if="row.serviceStatus==3">{{ dateFormat(row.startTime) }}-{{ dateFormat(row.endTime) }}</el-tag>
        </span>
        </template>
        <template slot="serviceStatus" slot-scope="{row}">
      <span>
          <el-tag type="warning" v-if="row.serviceStatus==0">未生效</el-tag>
          <el-tag type="success" v-if="row.serviceStatus==1">生效中</el-tag>
          <el-tag type="danger" v-if="row.serviceStatus==2">即将失效</el-tag>
          <el-tag type="info" v-if="row.serviceStatus==3">已失效</el-tag>
      </span>

        </template>
        <template slot="missionDate" slot-scope="{ row }">
          <div>{{ row.startDate }}至{{ row.endDate }}</div>
        </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="canBao" slot-scope="{ row }">
          <div>
            <el-button type="text" size="mini">{{ row.canBao }}</el-button>
          </div>
        </template>
        <!--/自定义列-->
        <template v-slot:cardNumber="{row}">
          <span>{{ idNumberDDesensitization(row.cardNumber) }}</span>
        </template>

      </avue-crud>
    </el-drawer>
  </basic-container>
</template>

<script>
import {employList, cancelEmploy,} from "@/api/tenant/mission";
import {getCode, resetPwd} from "@/api/manage/econtract.js";//api
import Resume from "@/components/resume/index";
import {idNumberDDesensitization} from "@/util/util";
import {mapGetters} from 'vuex'
import {dateFormat} from "@/util/date";
import {getConfig} from '@/api/tenant/config'
import EmployInformation from "./EmployInformation";

export default {
  comments: {},
  components: {
    Resume,
    EmployInformation
  },
  props: {
    status: Number,
  },

  data() {
    const validatePwdLength = (rule, value, callback) => {
      if (value.length != 6 || isNaN(Number(value))) {
        callback(new Error('请输入6位数的数字密码'));
      } else {
        callback();
      }
    }

    const validatePwd = (rule, value, callback) => {
      if (value != this.resetPwdForm.pwd) {
        callback(new Error('两次输入密码不一致'));
      } else {
        callback();
      }
    };
    const validPwdNums = (rule, value, callback) => {
      if (value.length != 6 || isNaN(Number(value))) {
        callback(new Error('请输入6位数的数字密码'));
      } else {
        callback();
      }
    }

    return {
      selectTaskInfo: {},
      getUserConfig: {},
      checkDisplayVisible: false,
      fpTitleId: '',
      fpData: {},
      pwdFormRules: {
        pwd: [
          {
            required: true, message: '请输入密码', trigger: 'blur'
          },
          {
            validator: validatePwdLength, trigger: 'blur'
          },

        ]
      },
      selectionFlag: true,
      /*忘记密码*/
      resetPwdDialogVisible: false,
      resetPwdForm: {},
      formLabelWidth: '150px',
      msgText: '获取验证码',
      msgTime: 120,
      //重置密码校验
      resetPwdRules: {
        code: [
          {
            required: true, message: '请输入验证码', trigger: 'blur'
          }
        ],
        pwd: [
          {
            required: true, message: '请输入密码', trigger: 'blur'
          },
          {
            validator: validPwdNums, trigger: 'blur'
          }
        ],
        pwd2: [
          {
            required: true, message: '请输入确认密码', trigger: 'blur'
          },
          {
            validator: validatePwd, trigger: 'blur'
          }
        ]

      },

      loadingbut: false,
      loadingbuttext: '确定',
      downLoadRow: {},
      dataCurClick: {},
      employDataIds: 1,
      employNum: 1,
      imgStr: '',
      isIndeterminate: false,
      checkAll: false,
      checked: false,
      missionId: "",
      loading: false,
      selectionList: [],
      dialogVisible: false,
      dialogVisible1: false,
      contractId: '',
      labelPosition: 'right',
      pwdForm: {
        pwd: ''
      },
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0,
      },
      query: {
        status: 1,
      },
      drawer: false,
      data: [],
      obj: {},

    };
  },
  computed: {
    ...mapGetters(['userInfo']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    employState() {
      return this.query.status;
    },
    option() {
      //const self = this;
      return {
        height: "auto",
        align: "center",
        // menuAlign: "center",
        tip: false,
        addBtn: false,
        viewBtn: false,
        delBtn: false,
        editBtn: false,
        excelBtn: false,
        columnBtn: false,
        searchBtn: false,
        searchShow: false,
        searchMenuSpan: 6,
        searchLabelWidth: 60,
        menu: false,
        // menuPosition: "center",
        labelPosition: "right",
        border: true,
        index: false,
        // index: true,
        // indexLabel: "序号",
        // selection: this.selectionFlag,
        // selectable: function (row) {
        //   return !row.noSelection;
        // },
        dialogType: "drawer",
        dialogWidth: "60%",
        dialogClickModal: false,
        column: [
          {
            label: "",
            prop: "status",
            search: true,
            searchSpan: 5,
            searchLabelWidth: 1,
            hide: true,
            searchslot: true,
          },
          {
            label: "姓名",
            prop: "realName",
            searchSpan: 4,
          },
          {
            label: "性别",
            prop: "sex",
            search: false,
            dicData: [
              {
                label: "男",
                value: 1,
              },
              {
                label: "女",
                value: 2,
              },
            ],
          },
          {
            label: "年龄",
            prop: "age",
            search: false,
          },
          {
            label: "手机号",
            prop: "telphone",
            search: false,
          },
          {
            label: "身份证",
            prop: "cardNumber",
            search: false,
            slot: true,
          },
        ],
      };
    },
  },
  watch: {
    "query.status": function (val, oldVal) {
      this.query.realName = '';
      this.query.groupId = '';
      if (val !== oldVal) {
        this.query.status = val;
        this.page.currentPage = 1;
        this.onLoad(this.page, this.query);
      }
    },
  },
  methods: {
    checkDisplayVisibleClose() {
      this.checkDisplayVisible = false;
    },
    rowEmployDisabled() {
    },
    dateFormat(date) {
      return dateFormat(new Date(date), 'yyyy/MM/dd')
    },
    idNumberDDesensitization,
    drawerClose() {
      this.$emit('refresh');
      this.drawer = false;
    },
    radioButtonChange() {
      this.query.realName = '';
      this.query.groupId = '';
      if (this.query.status == 2) {
        this.selectionFlag = false;
      } else {
        this.selectionFlag = true;
      }
    },
    /*打开drawer*/
    openDialog(row, status) {
      this.selectTaskInfo = row;
      this.missionId = row.missionNo;
      this.query = {
        status: status,
      };
      if (this.$refs.crud) {
        this.$refs.crud.searchReset();
      } else {
        this.onLoad(this.page, this.query);
      }
      this.drawer = true;
    },
    /*单行取消*/
    rowDel(row) {
      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(() => {
          cancelEmploy(this.missionId, row.id).then(
            () => {
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.onLoad(this.page);
              this.$emit("refresh");
            },
            (error) => {
              window.console.log(error);
            }
          );
        })
        .catch(() => {
        });
    },
    searchReset() {
      this.query = {
        status: this.query.status,
      };
      this.onLoad(this.page, this.query);
    },
    searchChange(params, done) {
      this.page.currentPage = 1;
      this.query = {
        realName: params.realName,
        groupId: params.groupId,
        status: this.query.status,
        worktypes: params.worktypes,
      };
      this.onLoad(this.page, this.query);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    /*刷新本页 带搜索参数*/
    refreshChange() {
      this.onLoad(this.page);
    },
    /*加载数据*/
    onLoad(page, params) {
      getConfig().then((res) => {
        this.getUserConfig = res.data.data;
      });
      this.loading = true;
      let paramscur = params ? Object.assign(params, this.query) : this.query;
      employList(
        page.currentPage,
        page.pageSize,
        paramscur,
        this.missionId
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        // if(this.getUserConfig.insuranceOn == 1){
        //     this.data.forEach((ele)=>{
        //       if(!ele.effect){
        //         ele.noSelection = 1;
        //       }
        //     })
        // }

        this.loading = false;
        /*let datas = data.records;
        datas.forEach((ele,index)=>{
          isGenerateContract(ele.userId,ele.missionNo).then((res) => {
            datas[index].successFlag = res.data.data;
          })
        })
        setTimeout(()=>{
          this.data = datas;
          this.loading = false;
        },1000)
        */
        //this.selectionClear();
      });

    },
    /*返回首页*/
    backIndex() {
      this.$emit("refresh");
    },
    forgetPwd() {
      this.phone = this.userInfo.account;
      var pat = /(\d{3})\d*(\d{4})/;
      this.phone = this.phone.replace(pat, '$1****$2');
      this.resetPwdDialogVisible = true;
      this.resetPwdForm = {};
    },
    /*获取验证码*/
    getCode() {
      this.msgKey = true;
      this.msgText = "发送中...";
      getCode(this.userInfo.account)
        .then(() => {
          this.msgText = "剩余" + 120 + "s";
          this.msgKey = true;
          const time = setInterval(() => {
            this.msgTime--;
            this.msgText = "剩余" + this.msgTime + "s";
            if (this.msgTime <= 0) {
              this.msgTime = 120;
              this.msgText = "重新获取";
              this.msgKey = false;
              clearInterval(time);
            }
          }, 1000);
        })
        .catch(() => {
          this.msgText = "重新获取";
          this.msgKey = false;
        });

    },
    /*重置密码*/
    submitResetPwd() {
      this.$refs.resetPwdForm.validate(valid => {
        if (valid) {
          resetPwd(this.userInfo.account, this.resetPwdForm.pwd, this.resetPwdForm.code).then(() => {
            this.$message.success('密码重置成功');
            this.resetPwdDialogVisible = false;
          })
            .catch((err) => {
              this.$message.error(err);
            })
        }
      })
    },
  },
};
</script>

<style>
.selectBtn {
  color: #787879 !important;
}

.selectBtn:hover {
  color: #787879 !important;
}

.tipsWrap {
  font-size: 14px;
  color: #ff0000;
  position: absolute;
  top: 26px;
  left: 120px;
}

.employ-employNum-count {
  color: #2098ee;
}

.employ-forgetPwd {
  float: right;
  margin-top: -33px;
}
</style>
