<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" />
        
        <div style="display: flex; align-items: center;">
          <year-month-select v-model="params.yearAndMonth"></year-month-select>
        </div>
      </template>

      <!-- 开始时间 -->
      <template slot="kssjSearch">
        <el-date-picker
          v-model="params.kssjRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </template>

      <!-- 使用寿命 -->
      <template slot="sysmSearch">
        <div style="display: flex; align-items: center;">
          <avue-input-number v-model="params.startSysm" :min="0"></avue-input-number>
          <span style="width: 70px; text-align: center;">至</span>
          <avue-input-number v-model="params.endSysm" :min="0"></avue-input-number>
        </div>
      </template>
      
    </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/kyAssetList";
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";


export default window.$crudCommon({
  components: {
    YearMonthSelect,
    UploadExcelDialog,
  },
  data() {
    return {
      params: {
        yearAndMonth: moment(new Date()).format('YYYYMM'),
      },
      isSelAnnual: false, // 是否选择全年

      wideTableColumns: [],
      printTitle: "",
    };
  },
  watch: {
    'params.yearAndMonth'(newVal) {
      if (newVal.length > 4) {
        // 是否勾选未全年
        this.isSelAnnual = false;
      } else {
        this.isSelAnnual = true;
      }
      this.page.currentPage = 1;
      this.getList(this.page);
    }
  },
  computed: {
    permissionList() {
      return {
        addBtn: !this.isSelAnnual,
        editBtn: !this.isSelAnnual,
        delBtn: !this.isSelAnnual,
      };
    },
  },
  methods: {
    searchChange(params, done) {
      if (done) done();
      if (this.validatenull(params)) {
        Object.keys(this.params).forEach(ele => {
          if (!['createTime_dategt', 'createTime_datelt', 'yearAndMonth', 'kssjRange', 'startSysm', 'endSysm'].includes(ele)) {
            delete this.params[ele];
          }
        })
      } else {
        Object.keys(params).forEach(ele => {
          if (this.validatenull(params[ele])) {
            delete this.params[ele];
            delete params[ele];
          }
        })
      }
      this.params = Object.assign(this.params, params);
      if (this.params.kssjRange && this.params.kssjRange.length) {
        this.params.startTime = this.params.kssjRange[0];
        this.params.endTime = this.params.kssjRange[1];
      }
      this.page.currentPage = 1;
      this.getList();
    },
    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/zc/import', excelParams);
    },
    uploadAfter() {
      this.page.currentPage = 1;
      this.getList(this.page);
    },
    handleExport() {
      exportBloByPost(`/api//kd-scientific/zc/export-zc?${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);
          }
        });
      });
    },
    /**
     * 打印表格
     * @param isLandscape 是否横向打印
     */
    printTable(isLandscape) {
      this.wideTableColumns = this.$refs.crud.columnOption;
      this.printTitle = `科研资产清单${this.params.yearAndMonth}`;
      this.$nextTick(() => {
        this.$refs.printWideTable.printTable(isLandscape);
      })
    },
  },
}, {
  // 模块路径
  name: 'basicResource/kyAssetList',
  res: ({ data }) => {
    return data;
  },
});
</script>
