<template>
  <basic-container>
    <avue-crud
      ref="crud"
      v-bind="bindVal"
      v-on="onEvent"
      v-model="form"
      :page.sync="page"
      :before-open="handleBeforeOpen"
      :permission="permissionList"
    >
      <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>
        <el-button
          type="primary"
          size="small"
          plain
        >
          引用当月研发人员名单
        </el-button>
        <print-table-btn @click="printTable" />
        <div>
          <year-month-select v-model="params.yearAndMonth"></year-month-select>
        </div>
      </template>

      <!-- <div v-for="key of watchUpdateKey" :slot="key" slot-scope="scope" :key="key">
        <updated-text v-if="scope.row[key+'Edit'] === 1" :text="scope.row[key]"></updated-text>
        <span v-else>{{ scope.row[key] }}</span>
      </div> -->
      
    </avue-crud>

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


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

<script>
import { getLastMonthData } from "@/api/basicResource/technicianMonthAvgSales";
import {exportBloByPost} from "@/api/common";
import YearMonthSelect from "@/components/year-month-select";
import UpdatedText from "@/components/updated-text";
import UploadExcelDialog from "@/components/upload-excel-dialog";
import moment from "moment";
import {getToken} from "@/util/auth";
import {downloadXls} from "@/util/util";
import Decimal from "decimal.js";
import PrintTableBtn from "@/components/print-table-btn";
import WideTablePrinter from '@/components/print-wide-table'

export default window.$crudCommon({
  components: {
    YearMonthSelect,
    UpdatedText,
    UploadExcelDialog,
    WideTablePrinter,
    PrintTableBtn
  },
  data() {
    return {
      params: {
        yearAndMonth: moment(new Date()).format('yyyyMM'),
      },

      operateType: '',
      watchUpdateKey: ["averageMonthlySalary", "pensionInsurance", "medicalInsurance", "unemploymentInsurance", "injuryInsurance", "maternityInsurance", "providentFund"],
      beforeUpdatedData: {},
      updatedFormData: {},

      wideTableColumns: [],
      printTitle: "",
    };
  },
  watch: {
    'params.yearAndMonth'(newVal) {
      this.page.currentPage = 1;
      this.getList(this.page);
    }
  },
  created() {
    let newOption = { ...this.option };
    // 姓名下拉框，设置监听事件
    newOption.column.forEach(item => {
      if (item.prop == "name") {
        item.change = ({ item }) => {
          if (!!item) {
            this.form = {
              ...this.form,
              name: item.name,
              number: item.number,
              identityCard: item.identityCard,
              department: item.department,
              personnelType: item.personnelType,
            };
          }
        }
      }
    });
    this.option = { ...newOption };
  },
  methods: {
    handleBeforeOpen(done, type) {
      this.operateType = type;
      this.beforeUpdatedData = { ...this.form };
      this.option.column.forEach(item => {
        if (item.prop == "name") {
          item.dicUrl = '/api/kd-scientific/technician/page';
          item.dicQuery.yearAndMonth = this.params.yearAndMonth;
        }
      });
      done();
    },
    getFormData() {
      if (this.operateType === 'edit') {
        return this.updatedFormData
      }
      return this.form;
    },
    updateBefore(loading, callback) {
      let updatedData = {};
      this.watchUpdateKey.forEach(key => {
        if (Number(this.form[key]) != Number(this.beforeUpdatedData[key])) {
          updatedData[key] = this.form[key];
        }
      });
      this.updatedFormData = {
        technicianId: this.form.technicianId,
        yearAndMonth: this.params.yearAndMonth,
        ...updatedData
      };
      callback && callback();
    },
    getDelParams(row) {
      return [{ yearAndMonth: this.params.yearAndMonth, technicianId: row.technicianId }]
    },
    getBatchDelParams() {
      let delArr = [];
      this.data.forEach(item => {
        if (this.ids.indexOf(item.id) > -1) {
          delArr.push({ yearAndMonth: this.params.yearAndMonth, technicianId: item.technicianId });
        }
      });
      return delArr;
    },
    handleImport() {
      let excelParams = { yearAndMonth: this.params.yearAndMonth };
      this.$refs.uploadExcelDialog.open('/api/kd-scientific/salary/import', excelParams);
    },
    uploadAfter() {
      this.page.currentPage = 1;
      this.getList(this.page);
    },
    handleExport() {
      exportBloByPost(`/api/kd-scientific/salary/export-salary?${this.website.tokenHeader}=${getToken()}`, this.params).then(res => {
        downloadXls(res.data, `技术人员${this.params.yearAndMonth}年度平均工资.xlsx`);
      });
    },
    handleReadyLastMonData() {
      this.$confirm("确认读取上年度工资明细吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        getLastMonthData({ yearAndMonth: this.params.yearAndMonth}).then(res => {
          let data = res.data;
          if (data.success) {
            this.$message.success('读取成功!');
            this.page.currentPage = 1;
            this.getList(this.page);
          }
        });
      });
    },
    printTable(isLandscape) {
      this.wideTableColumns = this.$refs.crud.columnOption;
      this.printTitle = `技术人员${this.params.yearAndMonth}年度平均工资`;
      this.$nextTick(() => {
        this.$refs.printWideTable.printTable(isLandscape);
      });
    },
  },
}, {
  // 模块路径
  name: 'yfCostManage/basicDataSetting/monthSalaryList',
  res: ({ data }) => {
    data.records = data.records.map(item => {
      // 处理id为空的时候，批量清除数据无法获取数据的问题
      item.id = !item.id ? (item.number || item.identityCard) : item.id;
      item.averageMonthlySalary = Number(item.averageMonthlySalary || 0).toFixed(2);
      item.pensionInsurance =  Number(item.pensionInsurance || 0).toFixed(2);
      item.medicalInsurance =  Number(item.medicalInsurance || 0).toFixed(2);
      item.unemploymentInsurance =  Number(item.unemploymentInsurance || 0).toFixed(2);
      item.injuryInsurance =  Number(item.injuryInsurance || 0).toFixed(2);
      item.maternityInsurance = Number(item.maternityInsurance || 0).toFixed(2);
      item.providentFund =  Number(item.providentFund || 0).toFixed(2);

      let pensionInsurance = new Decimal(item.pensionInsurance);
      let medicalInsurance = new Decimal(item.medicalInsurance);
      let unemploymentInsurance = new Decimal(item.unemploymentInsurance);
      let injuryInsurance = new Decimal(item.injuryInsurance);
      let maternityInsurance = new Decimal(item.maternityInsurance);
      let providentFund = new Decimal(item.providentFund);

      // 社保合计
      let socialInsurance = pensionInsurance.add(medicalInsurance).add(unemploymentInsurance).add(injuryInsurance).add(maternityInsurance);
      // 总计
      let total = socialInsurance.add(providentFund);

      item.socialInsurance = socialInsurance.toFixed(2);
      item.total = total.toFixed(2);
      return item;
    });
    return data;
  },
});
</script>
