<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-scope="{row}" slot="menu">
        <el-button v-if="[1,2].indexOf(row.status) > -1" type="text" size="mini" @click="handleChangeStatus(row, 0)">恢复</el-button>
        <el-button v-if="row.status === 0" type="text" size="mini" @click="handleChangeStatus(row, 1)">停用</el-button>
        <el-button v-if="row.status === 0" type="text" size="mini" @click="handleChangeStatus(row, 2)">已足额折旧</el-button>
      </template>

      <template slot="gl" slot-scope="{row}">
        <span v-if="'软件,专利,非专利技术'.indexOf(row.zclb) > -1">/</span>
        <span v-else>{{ row.gl }}</span>
      </template>

      <!-- <template slot="glForm" slot-scope="{row}">
        <el-input-number v-if="'软件,专利,非专利技术'.indexOf(row.zclb) === -1" type="number" />
      </template> -->

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

      <!-- 使用寿命 -->
      <template slot="sysmSearch">
        <div style="display: flex; align-items: center;">
          <span>使用寿命：</span>
          <avue-input-number v-model="params.startSysm" :min="0" style="width: 100px !important;"></avue-input-number>
          <span style="width: 20px; text-align: center;">至</span>
          <avue-input-number v-model="params.endSysm" :min="0" style="width: 100px !important;"></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,
      };
    },
  },
  mounted() {
    let newOption = { ...this.option };
    // 资产类别下拉框，设置监听事件
    newOption.column.forEach(item => {
      if (item.prop == "zclb") {
        item.change = ({ item }) => {
          if (!!item && "软件,专利权,非专利技术".indexOf(item.dictValue) > -1) {
            newOption.column[3].display = false;
          } else {
            newOption.column[3].display = true;
          }
        }
      }
    });
    this.option = { ...newOption };
  },
  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();
    },
    getFormData() {
      return { ...this.form, yearAndMonth: this.params.yearAndMonth };
    },
    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/asset/import', excelParams);
    },
    uploadAfter() {
      this.page.currentPage = 1;
      this.getList(this.page);
    },
    handleExport() {
      exportBloByPost(`/api//kd-scientific/asset/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);
          }
        });
      });
    },
    handleChangeStatus(rowData, status) {
      let msgText = '';
      if (status === 0) {
        msgText = `确认恢复资产“${rowData.zcmc}”吗?`
      } else if (status === 1) {
        msgText = `确认停用资产“${rowData.zcmc}”吗?`
      } else if (status === 2) {
        msgText = `确认将资产“${rowData.zcmc}”设置为已足额折旧吗?`
      }

      this.$confirm(msgText, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const params = { ...rowData, status };
        this.api.update(params).then(({ data }) => {
          if (data.success) {
            this.$message.success("操作成功!");
            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>
