<template>
  <basic-container>
    <avue-crud
      v-bind="bindVal"
      v-on="onEvent"
      v-model="form"
      :page.sync="page"
    >
      <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"
          @click="handleReadyLastData"
        >
          读取上个月数据
        </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="txksrqSearch">
        <span>摊销开始时间：</span>
        <el-date-picker
          v-model="extraParams.txksrq"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          style="width: 220px !important;"
        >
        </el-date-picker>
      </template>

      <template slot="zcyzSearch">
        <div style="display: flex; align-items: center;">
          <span>资产原值：</span>
          <avue-input-number v-model="extraParams.zcyzStart" :min="0" style="width: 90px !important;"></avue-input-number>
          <span style="width: 20px; text-align: center;">至</span>
          <avue-input-number v-model="extraParams.zcyzEnd" :min="0" style="width: 90px !important;"></avue-input-number>
        </div>
      </template>

      <template slot="ysyysSearch">
        <div style="display: flex; align-items: center;">
          <span>已使用月数：</span>
          <avue-input-number v-model="extraParams.ysyysStart" :min="0" style="width: 90px !important;"></avue-input-number>
          <span style="width: 20px; text-align: center;">至</span>
          <avue-input-number v-model="extraParams.ysyysEnd" :min="0" style="width: 90px !important;"></avue-input-number>
        </div>
      </template>

      <template slot="ytxeSearch">
        <div style="display: flex; align-items: center;">
          <span>月摊销额（每节点/套）：</span>
          <avue-input-number v-model="extraParams.ytxeStart" :min="0" style="width: 90px !important;"></avue-input-number>
          <span style="width: 20px; text-align: center;">至</span>
          <avue-input-number v-model="extraParams.ytxeEnd" :min="0" style="width: 90px !important;"></avue-input-number>
        </div>
      </template>

      <template slot="xmIdForm">
        <project-select v-model="form.xmId" :params="{ yearAndMonth: params.yearAndMonth }"></project-select>
      </template>
      
    </avue-crud>

    <upload-excel-dialog ref="uploadExcelDialog" templateKey="研发费用管理-折旧费用与长期待摊费用-每月长期待摊费用分配表" :uploadAfter="uploadAfter"/>

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

<script>
import { fetchLastMonthData } from "@/api/yfCostManage/basicDataSetting/dtCostAllocationList"
import YearMonthSelect from "@/components/year-month-select";
import UploadExcelDialog from "@/components/upload-excel-dialog";
import projectSelect from "@/components/project-select";
import assetSelect from "@/components/asset-select";
import moment from "moment";
import Decimal from "decimal.js";
import { isAlphanumericCombination } from "@/util/regex";
import { mapGetters } from "vuex";
import {exportBloByPost} from "@/api/common";
import {getToken} from "@/util/auth";
import {downloadXls} from "@/util/util";


export default window.$crudCommon({
  components: {
    YearMonthSelect,
    projectSelect,
    assetSelect,
    UploadExcelDialog,
  },
  data() {
    return {
      params: {
        yearAndMonth: "",
      },

      wideTableColumns: [],
      printTitle: "",
    };
  },
  watch: {
    'params.yearAndMonth'(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: {
    getSearchParams() {
      const newParams = { ...this.params, ...this.extraParams };
      if (newParams.txksrq && newParams.txksrq.length) {
        newParams.txksrqStart = newParams.txksrq[0];
        newParams.txksrqEnd = newParams.txksrq[1];
      }
      delete newParams.txksrq;
      return newParams;
    },
    getFormData() {
      let syzb = new Decimal(this.form.syzb || 0).div(100).toNumber();
      return { ...this.form, syzb,  yearAndMonth: this.params.yearAndMonth }
    },
    validCustom() {
      if (this.form.ctdtfybm && !isAlphanumericCombination(this.form.ctdtfybm)) {
        this.$message.warning("长期待摊费用编号必须是英文字母加数字组合!");
        return false;
      }
      return true;
    },
    addBefore(loading, callback) {
      if (!this.validCustom()) {
        loading();
        return;
      }
      callback && callback();
    },
    updateBefore(loading, callback) {
      if (!this.validCustom()) {
        loading();
        return;
      }
      callback && callback();
    },
    handleImport() {
      let excelParams = { yearAndMonth: this.params.yearAndMonth };
      this.$refs.uploadExcelDialog.open('/api/kd-scientific/xm/cqdtfy/import', excelParams);
    },
    uploadAfter() {
      this.page.currentPage = 1;
      this.getList(this.page);
    },
    handleExport() {
      exportBloByPost(`/api/kd-scientific/xm/cqdtfy/export?${this.website.tokenHeader}=${getToken()}`, this.params).then(res => {
        downloadXls(res.data, `${this.pageTitle}.xlsx`);
      });
    },
    /**
     * 打印表格
     * @param isLandscape 是否横向打印
     */
    printTable(isLandscape) {
      this.wideTableColumns = this.printOption.column;
      this.$nextTick(() => {
        this.$refs.printWideTable.printTable(isLandscape);
      })
    },
    handleReadyLastData() {
      fetchLastMonthData({ yearAndMonth: this.params.yearAndMonth}).then(res => {
        let data = res.data;
        if (data.success) {

          this.$message.success('读取成功!');
          this.page.currentPage = 1;
          this.getList(this.page);
        }
      });
    },
  },
}, {
  // 模块路径
  name: 'yfCostManage/basicDataSetting/dtCostAllocationList',
  res: ({ data }) => {
    data.records = data.records.map(item => {      
      item.syzb = new Decimal(item.syzb || 0).mul(new Decimal(100)).toNumber();
      let syzbNum = new Decimal(Number(item.syzb)).div(new Decimal(100));
      item.yftxe = new Decimal(item.ytxe || 0).mul(new Decimal(syzbNum)).toFixed(2);

      return item;
    });

    return data;
  },
});
</script>
