<template>
  <basic-container>
    <avue-crud
      v-bind="bindVal"
      v-on="onEvent"
      v-model="form"
      :page.sync="page"
      :before-open="handleBeforeOpen"
      :permission="permissionList"
    >
      <template slot="menuLeft">
        <!-- <el-button
          v-if="!isSelAnnual"
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          @click="handleDelete"
        >
          删 除
        </el-button> -->
        <el-button
          v-if="!isSelAnnual"
          type="success"
          size="small"
          plain
          icon="el-icon-upload2"
          @click="handleImport"
        >
          导入
        </el-button>
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          @click="handleExport"
        >
          导出
        </el-button>
        <el-button
          v-if="!isSelAnnual"
          type="primary"
          size="small"
          plain
          @click="handleReadyLastMonData"
        >
          读取上个月人员名单
        </el-button>
        <print-table-btn @click="printTable" />

      </template>

      <template slot="departmentIdForm">
        <second-unit-cascader v-model="form.departmentId" :yearAndMonth="currYear" @change="handleSecondUnitChange" />
      </template>

      <template slot="hireDateSearch">
        <span>入职时间：</span>
        <el-date-picker
          v-model="extraParams.hireDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          style="width: 240px !important;"
        >
        </el-date-picker>
      </template>

      <template slot="body">
        <h3 class="page-title">{{ pageTitle }}</h3>
        <year-month-select v-model="params.yearAndMonth"></year-month-select>
      </template>
      
    </avue-crud>

    <upload-excel-dialog ref="uploadExcelDialog" templateKey="企业技术人员名单" :uploadAfter="uploadAfter"/>

    <WideTablePrinter
      ref="printWideTable"
      :columns="wideTableColumns"
      :data="wideTableData"
      :print-title="pageTitle"
      :rows-per-page="30"
      :default-landscape="true"
      :zoom="60"
    />
  </basic-container>
</template>

<script>
import { getLastMonthData } from "@/api/basicResource/technicianRoster";
import {exportBloByPost} from "@/api/common";
import YearMonthSelect from "@/components/year-month-select";
import UploadExcelDialog from "@/components/upload-excel-dialog";
import moment from "moment";
import {getToken} from "@/util/auth";
import {downloadXls} from "@/util/util";
import { isAlphanumericCombination } from "@/util/regex";
import secondUnitCascader from "@/components/second-unit-cascader";
import { mapGetters } from "vuex";


export default window.$crudCommon({
  components: {
    YearMonthSelect,
    UploadExcelDialog,
    secondUnitCascader
  },
  data() {
    return {
      params: {
        yearAndMonth: "",
      },
      isSelAnnual: false, // 是否选择全年

      wideTableColumns: [],
      wideTableData: [],
      printTitle: "",

      secondUnitNameArr: [],
    };
  },
  watch: {
    'params.yearAndMonth'(newVal) {
      if (newVal.length > 4) {
        // 是否勾选未全年
        this.isSelAnnual = false;
      } else {
        this.isSelAnnual = true;
      }
      this.page.currentPage = 1;
      this.getList(this.page);


      this.option.column.forEach(item => {
        if (item.prop == 'hireDate') {
          let lastMonthEndDate = moment(newVal).subtract(1, 'months').endOf('months').format('YYYY-MM-DD'); // 上个月最后一天
          let monthEndDate = moment(newVal).endOf('months').format('YYYY-MM-DD'); // 当前月最后一天
          item.defaultValue = monthEndDate;
          item.pickerOptions = {
            disabledDate(time) {
              

              // return time.getTime() < new Date(lastMonthEndDate).getTime() || time.getTime() > new Date(monthEndDate).getTime();
              return time.getTime() > new Date(monthEndDate).getTime();
            }
          };
        }
      });
    },
  },
  computed: {
    ...mapGetters(['tag']),
    currYear() {
      return moment(this.params.yearAndMonth).format('YYYY')
    },
    permissionList() {
      return {
        addBtn: !this.isSelAnnual,
        editBtn: !this.isSelAnnual,
        delBtn: !this.isSelAnnual,
      };
    },
    pageTitle() {
      let yearAndMonthCN = '';
      if (this.params.yearAndMonth) {
        let formatTemp = this.isSelAnnual ? "yyyy年" : "yyyy年MM月";
        yearAndMonthCN = moment(this.params.yearAndMonth).format(formatTemp);
      }

      return `${yearAndMonthCN}${this.tag.label}`;
    }
  },
  methods: {
    getSearchParams() {
      let searchParams = { ...this.params, ...this.extraParams };
      if (searchParams.hireDateRange) {
        searchParams.hireDateMin = searchParams.hireDateRange[0];
        searchParams.hireDateMax = searchParams.hireDateRange[1];
      }

      delete searchParams.hireDateRange;
      return searchParams;
    },
    handleSecondUnitChange(val, nameArr) {
      this.secondUnitNameArr = nameArr;
    },
    validCustom() {
      if (!this.form.number && !this.form.idCard) {
        this.$message.warning("工号和身份证号必须填写一项!");
        return false;
      }
      // else if (this.form.number && !isAlphanumericCombination(this.form.number)) {
      //   this.$message.warning("工号必须是英文字母加数字组合!");
      //   return false;
      // }
      return true;
    },
    getFormData() {
      let _deptId;
      if (this.form.departmentId && this.form.departmentId instanceof Array) {
        _deptId = this.form.departmentId[this.form.departmentId.length - 1];
      }

      return { ...this.form, departmentId: _deptId, department: this.secondUnitNameArr.join('/'), yearAndMonth: this.params.yearAndMonth };
    },
    addBefore(loading, callback) {
      if (!this.validCustom()) {
        loading();
        return;
      }
      callback && callback();
    },
    updateBefore(loading, callback) {
      if (!this.validCustom()) {
        loading();
        return false;
      }
      callback && callback();
    },
    getDelParams(row) {
      return [{ id: row.id, yearAndMonth: this.params.yearAndMonth }];
    },
    getBatchDelParams() {
      let delArr = [];
      this.data.forEach(item => {
        if (this.ids.indexOf(item.id) > -1) {
          delArr.push({ yearAndMonth: this.params.yearAndMonth, id: item.id });
        }
      });
      return delArr;
    },
    handleImport() {
      let excelParams = { yearAndMonth: this.params.yearAndMonth };
      this.$refs.uploadExcelDialog.open('/api/kd-scientific/technician/import', excelParams);
    },
    uploadAfter() {
      this.page.currentPage = 1;
      this.getList(this.page);
    },
    handleExport() {
      exportBloByPost(`/api/kd-scientific/technician/export?${this.website.tokenHeader}=${getToken()}`, this.params).then(res => {
        downloadXls(res.data, `${this.pageTitle}.xlsx`);
      });
    },
    handleReadyLastMonData() {
      this.$confirm("确认要读取上个月的数据吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const _pageLoading = this.getPageLoading('数据读取中，请耐心等待...');
        getLastMonthData({ yearAndMonth: this.params.yearAndMonth}).then(res => {
          _pageLoading.close();
          let data = res.data;
          if (data.success) {

            this.$message.success('读取成功!');
            this.page.currentPage = 1;
            this.getList(this.page);
          }
        }).catch(err => {
          _pageLoading.close();
        });
      });
    },
    /**
     * 打印表格
     * @param isLandscape 是否横向打印
     */
    printTable(isLandscape) {
      this.wideTableColumns = this.printOption.column;
      this.wideTableData = [...this.$refs.crud.list]
      
      this.$nextTick(() => {
        this.$refs.printWideTable.printTable(isLandscape);
      })
    },
  },
}, {
  // 模块路径
  name: 'basicResource/technicianRoster',
  res: ({ data }) => {
    data.records = data.records.map(item => {
      item.gender = item.gender ? String(item.gender) : '';
      item.birthday = item.birthday ? moment(item.birthday).format('yyyy-MM-DD') : '';
      item.hireDate = item.hireDate ? moment(item.hireDate).format('yyyy-MM-DD') : '';
      return item;
    });
    return data;
  },
});
</script>
