<template>
  <basic-container>
    <avue-crud
      v-bind="bindVal"
      v-on="onEvent"
      v-model="form"
      :spanMethod="spanMethod"
    >
      <template slot="menuLeft">
        <!-- <el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          @click="handleDelete"
        >
          删 除
        </el-button> -->
        <!-- <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          @click="handleExport"
        >
          导出
        </el-button> -->
        <el-button
          type="primary"
          size="small"
          plain
          @click="handleDownFileAll"
        >
          一键下载
        </el-button>
        <print-table-btn @click="printTable" />
      </template>

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

      <template slot="menu" slot-scope="{ row, size }">
        <el-button
          type="text"
          :size="size"
          icon="el-icon-delete"
          :disabled="!row.isDel"
          @click="rowDel(row)"
        >
          删 除
        </el-button> 
      </template>

      <template slot="zdwjdzSearch">
        <el-input placeholder="请输入制度文件关键字" v-model="params.zdwjmc"></el-input>
      </template>

      <template slot="createTimeSearch">
        <el-date-picker
          v-model="params.createTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 240px !important"
        >
        </el-date-picker>
      </template>

      <template slot="zdwjdz" slot-scope="{row}">
        <div v-for="(item, index) of row.zdwjdz" :key="index">
          <el-link type="primary" @click="handleDownFile(item)">{{ item.label }}</el-link>
        </div>
      </template>

      <template slot="zdsszm" slot-scope="{row}">
        <div v-for="(item, index) of row.zdsszm" :key="index">
          <el-link type="primary" @click="handleDownFile(item)">{{ item.label }}</el-link>
        </div>
      </template>
      
    </avue-crud>

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

<script>
import {exportBloByPost, exportBlob} from "@/api/common";
import YearMonthSelect from "@/components/year-month-select";
import moment from "moment";
import {getToken} from "@/util/auth";
import {downloadXls, downloadFileByUrl} from "@/util/util";
import { mapGetters } from "vuex";


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

      wideTableColumns: [],
      wideTableData: [],
    };
  },
  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年') : ''
      return `${yearAndMonthCN}${this.tag.label}`
    }
  },
  created() {
    this.option.column.forEach(item => {
      if (item.prop == 'zdwjdz') {
        item.uploadBefore = (file, done, loading) => {
          if (this.form.zdwjdz.some(item => item.label == file.name)) {
            this.$message.error(`${file.name}文件已存在!`);
            return;
          }
          done();
        }
      }
      if (item.prop == 'zdsszm') {
         item.uploadBefore = (file, done, loading) => {
          console.log(file.name, this.form.zdsszm)
          if (this.form.zdsszm.some(item => item.label == file.name)) {
            this.$message.error(`${file.name}文件已存在!`);
            return;
          }
          done();
        }
      }
    })
  },
  methods: {
    getSearchParams() {
      let searchParams = { ...this.params };
      if (!!searchParams.createTime) {
        searchParams.createTimeStart = searchParams.createTime[0];
        searchParams.createTimeEnd = searchParams.createTime[1];
      }

      return searchParams;
    },
    spanMethod({ row, column, rowIndex, columnIndex }) {
      let fields = ["wjlx"];
      let cellValue = row[column.property];
      if (cellValue && fields.includes(column.property)) {
        let prevRow = this.data[rowIndex - 1];
        let nextRow = this.data[rowIndex + 1];
        if (prevRow && prevRow[column.property] === cellValue) {
          return { rowspan: 0, colspan: 0 };
        } else {
          let countRowspan = 1;
          while (nextRow && nextRow[column.property] === cellValue) {
            nextRow = this.data[++countRowspan + rowIndex];
          }
          if (countRowspan > 1) {
            row.hbFlag = true;
            return { rowspan: countRowspan, colspan: 1 };
          }
        }
      }
    },
    getFormData() {
      const params = { ...this.form };
      let zdwjmc = [];
      params.zdwjdz.forEach(item => {
        zdwjmc.push(item.label);
      });
      params.zdwjdz = JSON.stringify(params.zdwjdz);
      params.zdwjmc = zdwjmc.join(',');
      params.zdsszm = JSON.stringify(params.zdsszm);
      params.yearAndMonth = this.params.yearAndMonth;
      return params;
    },
    handleExport() {
      exportBloByPost(`/api/kd-scientific/technician/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 = JSON.parse(JSON.stringify(this.$refs.crud.list)).map(item => {
        if (item.zdwjdz && item.zdwjdz instanceof Array) {
          item.zdwjdz = item.zdwjdz.map(item => item.label).join('、')
        }
        if (item.zdsszm && item.zdsszm instanceof Array) {
          item.zdsszm = item.zdsszm.map(item => item.label).join('、')
        }

        return item;
      });

      this.$nextTick(() => {
        this.$refs.printWideTable.printTable(isLandscape);
      })
    },
    handleDownFile(file) {
      downloadFileByUrl(file.value, file.label);
    },
    handleDownFileAll() {
      let downParams = { year: this.params.yearAndMonth };
      exportBlob(`/api/kd-scientific/yfzd/download?${this.website.tokenHeader}=${getToken()}`, downParams).then(res => {
        downloadXls(res.data, `${this.pageTitle}.zip`);
      });
    },
  },

}, {
  // 模块路径
  name: 'RDSystemManage/list',
  res: ({ data }) => {
    let newList = [];
    Object.keys(data).forEach(fileType => {
      if (data[fileType].length) {
        data[fileType].forEach(item => {
          newList.push({
            wjlx: fileType,
            ...item,
            zdwjdz: !!item.zdwjdz ? JSON.parse(item.zdwjdz) : [],
            zdsszm: !!item.zdsszm ? JSON.parse(item.zdsszm) : [],
            isDel: true
          });
        });
      } else {
        newList.push({ wjlx: fileType, isDel: false, });
      }
    });

    data.records = newList;
    return data;
  },
});
</script>
