<template>
  <basic-container>
    <!--搜索栏-->
    <el-form
      size="small"
      label-position="right"
      style="padding-left: 10px; padding-right: 10px"
      :inline="true"
    >
      <el-row :span="24">
        <el-form-item label="机构名称:">
          <el-input
            v-model="query.companyName"
            placeholder="机构名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="岗位编码:">
          <el-input
            v-model="query.missionNo"
            placeholder="岗位编码"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="岗位名称:">
          <el-input
            v-model="query.jobName"
            placeholder="岗位名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="地址:">
          <el-input
            v-model="query.address"
            placeholder="地址"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="零工岗位工种:">
          <el-input
            v-model="query.worktypeNames"
            placeholder="零工岗位工种"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="学历：">
          <el-select v-model="query.education">
            <el-option
              v-for="(item, index) in educationState"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态：">
          <el-select v-model="query.reviewState">
            <el-option
              v-for="(item, index) in recruitStatus"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <div class="searchBtn">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-search"
            @click="searchChange1"
            >搜 索</el-button
          >
          <el-button size="small" icon="el-icon-delete" @click="searchReset1"
            >清 空</el-button
          >
        </div>
      </el-row>
    </el-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.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}}{{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"></post-view>
    </el-drawer>
    <zp-view ref="zpView"></zp-view>
    <wage-view ref="wageView"></wage-view>
  </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";
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},
  name: "manage_mission",
  data() {
    return {
      recruitStatus,
      dataSourcesEnum,
      educationState,
      downloadButton: false,
      wageUnitCategoryStateEnum,
      view: {},
      form: {},
      selectionList: [],
      query: { type: '' },
      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: [],
    };
  },
  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;
    },
  },
  methods: {
    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() {
      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);
    },
    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);
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(this.query, 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 {
        let h = this.$createElement;
        this.$prompt(
          h("p", { style: "color: #F56C6C" }, "一旦驳回无法进行后续操作"),
          "请核对招聘信息后再进行审核通过",
          {
            distinguishCancelAndClose: true,
            confirmButtonText: "通 过",
            cancelButtonText: "驳 回",
            type: "warning",
            center: true,
            inputType: "textarea",
            inputPlaceholder: "备注驳回原因",
            beforeClose: function(action, instance, done) {
              if(action === 'cancel') {
                if (!instance.inputValue) {
                  return this.$message({
                    type: "info",
                    message: "请输入驳回原因!",
                  });
                }
                self.handelFetchAuditing(idList, 9, instance.inputValue, "成功驳回, 操作成功!").then(() => done())
              } else if(action === 'confirm') {
                self.handelFetchAuditing(idList, 1, instance.inputValue).then(() => done())
              } else {
                done()
              }
            }
          }
        )
      }
    },
    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
      })

    },

  },
};
</script>

<style>
  .el-form-item {
    margin-right: 18px !important;
  }
.searchBtn{
  display: inline-block;
}
</style>
