<template>
  <basic-container>
    <!--搜索栏-->
    <avue-form :option="searchOption" v-model="query" @submit="searchChange1" @reset-change="searchReset1"></avue-form>
    <!--搜索-->
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      ref="crud"
      v-model="form"
      :permission="permissionList"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      :page.sync="page"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <!-- <template slot="menuLeft">
        <el-button
          v-if="vaildData(permission.manage_mission_check, false)"
          size="small"
          @click.stop="handleCheck"
          type="primary"
        >审核
        </el-button
        >
      </template> -->
      <!-- <template slot="menuRight">
        <el-button size="small" @click.stop="downRecords" type="primary"
          >导出</el-button
        >
      </template> -->
      <template slot-scope="{ row }" slot="menu">
        <el-button
          type="text"
          size="small"
          @click.stop="rowView(row)"
          v-if="vaildData(permission.manage_mission_view, false)"
        >详情
        </el-button>
        <el-button
        type="text"
        size="small"
        @click="employ(row, 1)"
        v-if="row.reviewState === 1"
      >申请录用
      </el-button>
        <!-- <el-button
          type="text"
          size="small"
          @click.stop="rowZPView(row)"
          v-if="vaildData(permission.manage_mission_zpview, false)"
          >报名详情</el-button> -->
      </template>
      <template slot="menuRight">
        <el-button size="small" :disabled="downloadButton" @click.stop="downRecords" type="primary"
        >导出
        </el-button
        >
      </template>
      <template slot="wage" slot-scope="{ row }">
        <div>{{ row.wage }}~{{row.wageUpper}}{{ wageUnitCategoryStateEnum[row.wageUnitCategory] }}</div>
      </template>
    </avue-crud>
    <delay-dialog
      ref="delay"
      :ids="ids"
      @success="onLoad(page, query)"
    ></delay-dialog>
    <el-drawer title="详情" :visible.sync="viewDrawer" size="60%">
      <post-view :model="view" :wage="true"></post-view>
    </el-drawer>
    <zp-view ref="zpView"></zp-view>
    <wage-view ref="wageView"></wage-view>
    <PromptDialog
      :visible="dialogFlag"
      title="审核"
      sub-title="请核对招聘信息后再进行审核通过， 一旦驳回无法进行后续操作"
      :tips="[
        '招聘职位描述不清晰或过于简单；',
        '招聘职位与公司业务不相关；',
        '招聘职位存在违法违规行为；',
        '招聘职位的薪资、福利等待遇不符合市场标准；',
        '用工单位资质不符；',
      ]"
      @onClose="dialogFlag = false"
      @onCancel="diaLogCancel"
      @onConfirm="diaLogConfirm"
    ></PromptDialog>

    <Employ ref="employ" @refresh="refreshChange" :status="status"></Employ>
  </basic-container>
</template>

<script>
import {
  getList,
  review,
  getDetail,
  download,
  exportList
} from "@/api/workstation/post";
import {mapGetters} from "vuex";
import postView from "@/views/util/post-view";
import zpView from "./zpView";
import {
  companyPostState,
  dataSourcesEnum,
  educationState,
  missionState,
  recruitStatus,
  wageUnitCategoryState
} from "@/common/dic";
import {calcDate} from "@/util/date";
import {Message} from "element-ui";
import lodash from "lodash";
import {Auditing} from "@/api/manage/mission";
import PromptDialog from "@/components/promptDialog/index.vue";
import Employ from "./Employ.vue";
import {getDeptMyTree} from "@/api/tenant/talents";

const wageUnitCategoryStateEnum = {}
wageUnitCategoryState.map((item) => {
  wageUnitCategoryStateEnum[item.value] = item.label
})
const message = lodash.throttle(
  function (options) {
    Message(options);
  },
  3000,
  {trailing: false}
);

export default {
  components: {postView, zpView, PromptDialog, Employ},
  name: "manage_mission",
  data() {
    return {
      dialogFlag: false,
      selectIdList: [],
      recruitStatus,
      dataSourcesEnum,
      educationState,
      downloadButton: false,
      wageUnitCategoryStateEnum,
      view: {},
      form: {},
      selectionList: [],
      query: {type: '', reviewState: 0},
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      checkDialog: false,
      finishDialog: false,
      viewDrawer: false,
      mStatusList: [
        {value: 1, label: "招聘中"},
        {value: 2, label: "任务中"},
        {value: 3, label: "已完成"},
        {value: 4, label: "已失效"},
        {
          label: "审核未通过",
          value: 9,
        },
      ],
      option: {
        height: "auto",
        tip: false,
        columnBtn: false,
        searchShow: true,
        searchMenuSpan: 5,
        menuWidth: 110,
        border: true,
        selection: true,
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        dialogClickModal: false,
        dialogType: "drawer",
        dialogFullscreen: true,
        mStatusList: companyPostState,
        column: [
          {
            label: "用工单位",
            prop: "jobCompanyName",
            display: false,
            fixed: true,
            width: 120,
          },
          {
            label: "岗位名称",
            prop: "jobName",
            display: false,
            fixed: true,
            width: 120,
          },
          {
            label: "招聘人数",
            prop: "peopleNum",
            search: false,
            searchSpan: 1,
            display: false,
          },
          {
            label: "参考工资",
            prop: "wage",
            search: false,
            searchSpan: 5,
            display: false,
            slot: true,
            width: 140,
          },
          {
            label: "岗位工种",
            prop: "worktypeNames",
            search: false,
            display: false,
          }, {
            label: "年龄要求",
            prop: "ageDesc",
            search: false,
            display: false,
          }, {
            label: "学历要求",
            prop: "education",
            type: "select",
            dicData: educationState,
            search: false,
            display: false,
          }, {
            label: "经验要求",
            prop: "experienceDesc",
            search: false,
            display: false,
          },
          {
            label: "岗位状态",
            prop: "status",
            type: "select",
            dicData: missionState,
            display: false,
            hide: true,
            span: 24,
            width: 80,
          },
          {
            label: "岗位编码",
            prop: "missionNo",
            hide: true,
            display: false,
          },
          {
            label: "任务时长",
            prop: "missionDuration",
            search: false,
            searchSpan: 5,
            display: false,
            hide: true,
            minWidth: 70,
          },
          {
            label: "详细地址",
            prop: "address",
            display: false,
            span: 6,
            width: 200,
          },
          {
            label: "开始日期",
            prop: "stime",
            type: "date",
            display: false,
            minWidth: 100,
            format: "yyyy-MM-dd",
          },
          {
            label: "结束日期",
            prop: "etime",
            type: "date",
            display: false,
            minWidth: 100,
            format: "yyyy-MM-dd",
          },
          {
            label: "录入人员",
            prop: "createUserName",
            display: false,
            span: 6,
            width: 80,
          },
          {
            label: "审核状态",
            prop: "reviewState",
            dicData: recruitStatus,
            display: false,
            span: 6,
            width: 100,
          },
          {
            label: "审核时间",
            prop: "reviewTime",
            display: false,
            span: 6,
            width: 100,
          },
          {
            label: "审核人员",
            prop: "reviewUserName",
            display: false,
            span: 6,
            width: 100,
          },
          {
            label: "数据来源",
            prop: "dataSources",
            dicData: dataSourcesEnum,
            display: false,
            span: 24,
            width: 100,
          },
          {
            label: "机构名称",
            prop: "companyName",
            display: false,
            width: 200,
          },
        ],
      },
      data: [],
      depTree: [],
      status: 1,
    };
  },
  computed: {
    ...mapGetters(["userInfo", "permission"]),
    permissionList() {
      return {
        viewBtn: this.vaildData(
          this.permission.manage_station_mainList_view,
          false
        ),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    },
    searchOption() {
      return {
        menuSpan: 6,
        column: [
          {
            label: "所属机构",
            prop: "deptId",
            type: "tree",
            multiple: false,
            dicData: this.depTree,
            props: {
              label: "title",
              value: 'value'
            },
            span: 6,
          },
          {
            label: '岗位名称',
            prop: 'jobName',
            span: 6,
          },
          {
            label: '地址',
            prop: 'address',
            placeholder: "请输入地址",
            span: 6,
          },
          {
            label: '岗位工种',
            prop: 'worktypeNames',
            span: 6,
          },
          {
            label: '审核状态',
            prop: 'reviewState',
            type: 'select',
            dicData: recruitStatus,
            span: 6,
          }, {
            label: '学历',
            prop: 'education',
            type: 'select',
            dicData: educationState,
            span: 6,
          },
        ]
      }
    }
  },
  created() {
    this.getDept()
  },
  methods: {
    async getDept() {
      let params = {
        tenantId: '000000'
      }
      let resData = await getDeptMyTree(params)
      if (resData.data.code === 200) {
        this.depTree = resData.data.data
      }
    },
    initData() {
      this.onLoad(this.page, this.query);
    },
    rowView(row) {
      getDetail(row.missionNo).then((resp) => {
        this.viewDrawer = true;
        this.view = resp.data.data;
      });
    },
    rowZPView(row) {
      this.$refs.zpView.open(row.missionNo);
    },
    handleWageView(row) {
      this.$refs.wageView.open(row.missionNo);
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.time) {
        params.stime = params.time[0];
        params.etime = params.time[1];
        delete params.time;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    searchChange1(from, done) {
      if (this.query.time) {
        this.query.stime = this.query.time[0];
        this.query.etime = this.query.time[1];
        // delete this.query.time;
      }
      this.page.currentPage = 1;
      this.onLoad(this.page, this.query);
      done && done()
    },
    searchReset1() {
      this.query = {};
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    beforeOpen(done, type) {
      if (["add", "edit"].includes(type)) {
        this.initData();
        done();
      }
      if (["edit", "view"].includes(type)) {
        this.loading = true;
      }
    },
    beforeClose(done) {
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      params = Object.assign(this.query, params);
      params = this.$api.filterObject(params)
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        params
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.data.map((val) => {
          val.missionDuration =
            calcDate(
              new Date(val.stime).getTime(),
              new Date(val.etime).getTime()
            ).days + "天";
          val.payStatus =
            (val.payPersonTotal && val.payPersonTotal) > 0
              ? "已支付"
              : "未支付";
        });
      });
    },
    handleDelay(row) {
      this.$refs.delay.open(row.missionNo);
    },
    handleCheck() {
      let self = this
      if (this.ids.length < 1) {
        message({
          type: "warning",
          message: "请至少选择一条数据",
        });
        return;
      }
      let idList = [];
      for (let i = 0; i < this.ids.length; i++) {
        this.data.forEach((ele) => {
          if (ele.id == this.ids[i]) {
            idList.push(ele.id);
          }
        });
      }

      if (idList.length == 0) {
        this.$message.error("只能驳回【招聘中】的任务");
      } else {
        this.dialogFlag = true
        this.selectIdList = idList
      }
    },
    diaLogCancel(value) {
      if (!value) {
        return this.$message({
          type: "info",
          message: "请输入驳回原因!",
        });
      }
      this.handelFetchAuditing(this.selectIdList, 9, value, "成功驳回, 操作成功!").then(() => {
        this.dialogFlag = false
      })
    },
    diaLogConfirm(value) {
      this.handelFetchAuditing(this.selectIdList, 1, value).then(() => {
        this.dialogFlag = false
      })
    },
    handelFetchAuditing(idList, reviewState, msg, message) {
      return new Promise((resolve, reject) => {
        let arr = idList.map((item) => ({
          id: item,
          reviewState: reviewState,
          reviewMsg: msg || '',
          jobType: 1,
        }))
        this.loading = true;
        Auditing(arr).then(() => {
          this.loading = false;
          this.onLoad(this.page, this.params);
          this.$message({
            type: message ? "info" : "success",
            message: message || "审核通过，操作成功!",
          });
          resolve()
        }).catch(() => {
          this.loading = false;
          reject()
        });
      })
    },
    downRecords() {
      this.downloadButton = true
      exportList(
        this.page.currentPage,
        this.page.pageSize,
        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
      })

    },

     /*打开录用人员*/
     employ(row, status) {
console.log(row, status, '========', this.$refs.employ)
      this.$refs.employ.openDialog(row, status);
    },

  },
};
</script>

<style>
.el-form-item {
  margin-right: 18px !important;
}

.searchBtn {
  display: inline-block;
}
</style>
