<template>
  <basic-container>
    <avue-crud
      v-bind="bindVal"
      v-on="onEvent"
      v-model="form"
      :page.sync="page"
      :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"
          @click="handleReadyDevData"
        >
          直接引用
        </el-button>
        <print-table-btn @click="printTable" />

      </template>

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

      <template slot="sysmSearch">
        <div style="display: flex; align-items: center;">
          <span>使用寿命：</span>
          <avue-input-number v-model="extraParams.sysmMin" :min="0" style="width: 90px !important;"></avue-input-number>
          <span style="width: 20px; text-align: center;">至</span>
          <avue-input-number v-model="extraParams.sysmMax" :min="0" style="width: 90px !important;"></avue-input-number>
        </div>
      </template>

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

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

      <template slot="yzjeSearch">
        <div style="display: flex; align-items: center;">
          <span>月折旧额(每台/套)：</span>
          <avue-input-number v-model="extraParams.yzjeMin" :min="0" style="width: 90px !important;"></avue-input-number>
          <span style="width: 20px; text-align: center;">至</span>
          <avue-input-number v-model="extraParams.yzjeMax" :min="0" style="width: 90px !important;"></avue-input-number>
        </div>
      </template>

      <template slot="xmIdForm">
        <project-select v-model="form.xmId" :params="{ yearAndMonth: params.yearAndMonth }" :noDetail="true" @change="handleProjectChange"></project-select>
      </template>

      <template slot="zcbm_formForm">
        <asset-select
          v-model="form.zcbm_form"
          :params="{ yearAndMonth: params.yearAndMonth, zclb: '软件,专利权,非专利技术,其他' }"
          valueKey="zcbm"
          @change="handleAssetChange"
        ></asset-select>
      </template>

      <template slot="userUnicodeForm">
        <el-select
          v-model="form.userUnicode"
          filterable
          placeholder="请选择 使用人"
          style="width: 100%;"
        >
          <el-option
            v-for="item in cyPersonList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </template>
      
    </avue-crud>

    <upload-excel-dialog ref="uploadExcelDialog" templateKey="研发资产管理-每月无形资产明细" :uploadAfter="uploadAfter"/>

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

<script>
import { fetchDeviceData } from "@/api/yfCostManage/basicDataSetting/wxzcDetail";
import { getList as getCyPersonList } from "@/api/techPerson/cyPersonSumList"
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 { 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: "",
      },
      isSelAnnual: false,

      cyPersonList: [],

      wideTableColumns: [],
      wideTableData: [],
    };
  },
  watch: {
    'params.yearAndMonth'(newVal) {
      if (newVal.length > 4) {
        // 是否勾选未全年
        this.isSelAnnual = false;
      } else {
        this.isSelAnnual = true;
      }
      this.page.currentPage = 1;
      this.getList(this.page);
    },
  },
  computed: {
    ...mapGetters(['tag']),
    permissionList() {
      return {
        addBtn: !this.isSelAnnual,
        editBtn: !this.isSelAnnual,
        delBtn: !this.isSelAnnual,
      };
    },
    pageTitle() {
      let yearAndMonthCN = '';
      if (this.params.yearAndMonth) {
        let formatTemp = this.isSelAnnual ? "yyyy年" : "yyyy年MM月";
        yearAndMonthCN = moment(this.params.yearAndMonth).format(formatTemp);
      }

      return `${yearAndMonthCN}${this.tag.label}`.replace(/每月/g, '');
    }
  },
  methods: {
    handleImport() {
      let excelParams = { yearAndMonth: this.params.yearAndMonth };
      this.$refs.uploadExcelDialog.open('/api/kd-scientific/asset/intangible/import', excelParams);
    },
    uploadAfter() {
      this.page.currentPage = 1;
      this.getList(this.page);
    },
    handleExport() {
      exportBloByPost(`/api/kd-scientific/asset/intangible/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.wideTableData = [...this.$refs.crud.list];
      this.$nextTick(() => {
        this.$refs.printWideTable.printTable(isLandscape);
      })
    },
    handleReadyDevData() {
      const _pageLoading = this.getPageLoading("数据读取中，请耐心等待...");
      fetchDeviceData({ yearAndMonth: this.params.yearAndMonth}).then(res => {
        _pageLoading.close();
        let data = res.data;
        if (data.success) {

          this.$message.success('引用成功!');
          this.page.currentPage = 1;
          this.getList(this.page);
        }
      }).catch(err => {
        _pageLoading.close();
      });
    },
    handleAssetChange({ assetId }) {
      this.form = { ...this.form, assetId };
    },
    getFormData() {
      const { id, xmId, assetId, zcbm_form, userUnicode } = this.form;
      let userName;
      if (!!userUnicode) {
        let personObj = this.cyPersonList.find(item => item.unicode === userUnicode);
        userName = personObj ? personObj.name : undefined;
      }
      return { id, xmId, assetId, zcbm: zcbm_form, userUnicode, userName, yearAndMonth: this.params.yearAndMonth };
    },
    handleProjectChange(data) {
      this.getCyPersonListFunc(data.xmmc);
    },
    // 获取项目参研人员列表
    getCyPersonListFunc(xmmc) {
      getCyPersonList(1, 99999, { xmmc, yearAndMonth: this.params.yearAndMonth }).then(({ data }) => {
        if (data.code == 200) {
          let list = data.data.records && data.data.records.length ? data.data.records[0].technicianList : [];
          this.cyPersonList = list.map(item => {
            let nameArr = [item.name, item.number || '-', item.idCard || '-'];
            return {
              label: nameArr.join(' \\ '),
              value: item.unicode,
              ...item
            }
          });
        }
      });
    }
  },
}, {
  // 模块路径
  name: 'yfCostManage/basicDataSetting/wxzcDetail',
  res: ({ data }) => {
    data.records = data.records.map(item => {
      item.zcbm_form = item.zcbm;
      item.zcmc = item.asset ? item.asset.zcmc : '';
      item.zclb = item.asset ? item.asset.zclb : '';
      item.gl = item.asset ? item.asset.gl : '';
      item.yt = item.asset ? item.asset.yt : '';
      item.kssj = item.asset ? item.asset.kssj : '';
      item.sysm = item.asset ? item.asset.sysm : '';
      item.ysysm = item.asset ? item.asset.ysysm : '';
      item.zcyz = item.asset ? item.asset.zcyz : '';
      item.jcz = item.asset ? new Decimal(item.asset.jcz || 0).mul(new Decimal(100)) : '';
      item.yzje = item.asset ? item.asset.yzje : '';
      item.status = item.asset ? item.asset.status : '';
      return item;
    });
    console.log(data.records)
    return data;
  },
});
</script>
