<template>
  <basic-container>
    <avue-crud
      v-if="!headerLoading"
      v-bind="bindVal"
      v-on="onEvent"
      v-model="form"
      :page.sync="page"
      :before-open="handleBeforeOpen"
      :permission="permissionList"
      :header-cell-style="headerCellStyle" 
    >
      <template slot="menuLeft">
        <el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          @click="handleDelete"
        >
          清除工时数据
        </el-button>
        <el-button
          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>
        <!-- <print-table-btn @click="printTable" /> -->
        
      </template>

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


      <!-- <template slot="monthlyHoursSearch">
        <div style="display: flex; align-items: center;">
          <span>使用工时/小时：</span>
          <avue-input-number v-model="params.monthlyHoursStart" :min="0" style="width: 100px !important;"></avue-input-number>
          <span style="width: 20px; text-align: center;">至</span>
          <avue-input-number v-model="params.monthlyHoursEnd" :min="0" style="width: 100px !important;"></avue-input-number>
        </div>
      </template> -->
      
    </avue-crud>

    <upload-excel-dialog ref="uploadExcelDialog" :showTempBtn="false" :uploadAfter="uploadAfter"/>

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

<script>
import YearMonthSelect from "@/components/year-month-select";
import UploadExcelDialog from "@/components/upload-excel-dialog";
import {exportBloByPost} from "@/api/common";
import {getToken} from "@/util/auth";
import {downloadXls} from "@/util/util";
import { deepClone, getMonthDatesWithMarkers } from "@/util/util";
import moment from "moment";
import ChineseHoliday from "@chnlib/chinese-holiday";
import { mapGetters } from "vuex";


export default window.$crudCommon({
  components: {
    YearMonthSelect,
    UploadExcelDialog,
  },
  data() {
    return {
      params: {
        yearAndMonth: "",
      },
      defaultColumns: [
        {
          label: '研发项目编号',
          prop: 'xmbh',
          span: 24,
          width: 100,
          align: 'center',
          type: 'input',
          showOverflowTooltip: true,
          disabled: true,
        },
        {
          label: '研发项目名称',
          prop: 'xmmc',
          type: 'input',
          span: 24,
          width: 110,
          align: 'center',
          search: true,
          showOverflowTooltip: true,
          disabled: true,
        },
        {
          label: '姓名',
          prop: 'name',
          span: 24,
          search: true,
          width: 90,
          cell: true,
          align: 'center',
          // type: 'select',
          showOverflowTooltip: true,
          // dicUrl: '',
          // dicFlag: true,
          // dicFormatter:(res)=>{     
          //   return res.data.records
          // },
          // dicQuery: {
          //   current: 1,
          //   size: 99999,
          //   yearAndMonth: ''
          // },
          // props: {
          //   label: 'name',
          //   value: 'id',
          // },
          disabled: true,
          rules: [
            {
              required: true,
              message: '请选择技术人员',
              trigger: 'blur',
            },
          ],
        },
        {
          label: '工号',
          prop: 'number',
          type: 'input',
          span: 24,
          width: 90,
          align: 'center',
          search: true,
          disabled: true,
          showOverflowTooltip: true,
        },
        {
          label: '身份证号',
          prop: 'idCard',
          type: 'input',
          span: 24,
          search: true,
          disabled: true,
          width: 150,
          align: 'center',
          showOverflowTooltip: true,
        },
        {
          label: '科研人员类别',
          prop: 'personnelType',
          type: 'select',
          span: 24,
          width: 100,
          align: 'center',
          search: true,
          disabled: true,
          dicFlag: true,
          dicUrl: '/api/kd-system/dict/dictionary?code=renyuanleixing',
          props: {
            label: 'dictValue',
            value: 'dictKey',
          },
          showOverflowTooltip: true,
        },
      ],

      oldMonthData: [],

      wideTableColumns: [],
      printTitle: "",

    };
  },
  watch: {
    'params.yearAndMonth'(newVal) {
      this.refreshTableCol(newVal);
      this.page.currentPage = 1;
      this.getList(this.page);
    }
  },
  computed: {
    ...mapGetters(['tag']),
    pageTitle() {
      let yearAndMonthCN = this.params.yearAndMonth ? moment(this.params.yearAndMonth).format('yyyy年MM月') : '';
      return `${yearAndMonthCN}${this.tag.label}`.replace(/每月/g, '');
    }
  },
  methods: {
    handleBeforeOpen(done, type) {
      this.oldMonthData = this.form.dailyAttendances || [];
      done();
    },
    refreshTableCol(yearAndMonth) {
      this.option.column = [];
      let yearMonth = moment(yearAndMonth).format("YYYY-MM").split("-");
      const monthDays = getMonthDatesWithMarkers(Number(yearMonth[0]), Number(yearMonth[1]));
      for (let i=monthDays.length; i<31; i++) {
        let _day = i+1
        monthDays.push({
          day: _day,
          display: false,
          hide: true
        });
      }
      let newColumns = deepClone(this.defaultColumns);
       monthDays.forEach((item, index) => {
        let col = {};
        if (item.hide) {
          col = {
            hide: true,
            display: false,
          };
        } else {
          col = {
            prop: moment(item.dateString).format('yyyyMMDD'),
            label:  item.dayName + "" + item.day.toString(),
            type: 'number',
            precision: 1,
            min: 0,
            width: 50,
            align: 'center',
            isWorkDay: ChineseHoliday.isWorkday(item.dateString),
            showOverflowTooltip: true,
          };
        }
        if (!ChineseHoliday.isWorkday(item.dateString)) {
          col.labelClassName = 'red';
          col.labelClassName = 'red';
        }
        newColumns.push(col);
      });

      // newColumns.push({
      //   prop: "monthlyHours",
      //   label: "研发出勤/小时",
      //   type: 'number',
      //   precision: 1,
      //   min: 0,
      //   width: 70,
      //   align: 'center',
      //   showOverflowTooltip: true,
      //   display: false,
      //   search: true,
      // }, {
      //   prop: "monthlyDays",
      //   label: "研发出勤/天",
      //   type: 'number',
      //   precision: 1,
      //   min: 0,
      //   width: 70,
      //   align: 'center',
      //   showOverflowTooltip: true,
      //   display: false,
      // });

      this.option.column = newColumns;
    },
    handleImport() {
      let excelParams = { yearAndMonth: this.params.yearAndMonth };
      this.$refs.uploadExcelDialog.open('/api/kd-scientific/xm/technician/hours/import', excelParams);
    },
    uploadAfter() {
      this.page.currentPage = 1;
      this.getList(this.page);
    },
    getFormData() {
      const newFormData = { ...this.form, yearAndMonth: this.params.yearAndMonth  };
      let dailyAttendances = [];
      let _oldMonthData = this.oldMonthData;
      Object.keys(this.form).forEach(key => {
        if (key.indexOf(this.params.yearAndMonth) > -1) {
          let oldObj = _oldMonthData.find(old => old.workDate == key) || {};
          if (this.form[key] || oldObj.workHours || oldObj.workHours === 0) {
            let workHours = this.form[key];
            if (workHours === undefined || workHours === null || workHours === '') {
              workHours = null;
            }
            dailyAttendances.push({
              workDate: key,
              workHours
            });
          }
          delete newFormData[key];
        }
      });

      // 获取最新修改过的数据
      let updatedMonthData = [];
      dailyAttendances.forEach(item => {
        let oldObj = _oldMonthData.find(old => item.workDate === old.workDate);
        if (!!oldObj && item.workHours !== oldObj.workHours) {
          updatedMonthData.push(item);
        } else if (!oldObj) {
          updatedMonthData.push(item);
        }
      })

      newFormData.dailyAttendances = updatedMonthData;
      return newFormData;
    },
    getDelParams(row) {
      return { yearAndMonth: this.params.yearAndMonth, xmAndUnicodeList: [{ xmId: row.xmId, unicode: row.unicode }] };
    },
    getBatchDelParams() {
      let xmAndUnicodeList = [];
      this.data.forEach(item => {
        if (this.ids.indexOf(item.id) > -1) {
          xmAndUnicodeList.push({ xmId: item.xmId, unicode: item.unicode });
        }
      });
      return { yearAndMonth: this.params.yearAndMonth, xmAndUnicodeList };
    },
    handleExport() {
      exportBloByPost(`/api/kd-scientific/xm/technician/hours/export?${this.website.tokenHeader}=${getToken()}`, this.params).then(res => {
        downloadXls(res.data, `${this.pageTitle}.xlsx`);
      });
    },
    /**
     * 打印表格
     * @param isLandscape 是否横向打印
     */
    printTable(isLandscape) {
      this.wideTableColumns = this.$refs.crud.columnOption;
      this.$nextTick(() => {
        this.$refs.printWideTable.printTable(isLandscape);
      })
    },
    headerCellStyle ({ column }) {
      let color = column.labelClassName ? 'red' : 'rgba(0,0,0,.85)';
      return {
        color
      }
    }
  },
}, {
  // 模块路径
  name: 'yfCostManage/basicDataSetting/workHoursRecords',
  res: ({ data }) => {
    let newList = [];
    data.records.forEach((item) => {
      let objData = {
        ...item,
        id: item.unicode+'_'+item.xmId,
        monthlyHours: (item.monthlyHours || 0).toFixed(1),
        monthlyDays: (item.monthlyDays || 0).toFixed(1)
      };
      item.dailyAttendances.forEach(hourItem => {
        objData[hourItem.workDate] = (hourItem.workHours || 0).toFixed(1);
      });
      newList.push(objData);
    });
    data.records = newList;
    return data;
  },
});
</script>
