<template>
  <basic-container v-loading="loading">
    <avue-form ref="searchForm" v-model="params" :option="searchOption" class="cl-search-form">
      <template slot="useDate">
        <span>日期：</span>
        <el-date-picker
          v-model="params.useDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          style="width: 220px !important;"
        >
        </el-date-picker>
      </template>
      <template slot-scope="{size}" slot="menuForm">
        <el-button type="primary" :size="size" icon="el-icon-search" @click="handleSearchBtn">查询</el-button>
        <el-button :size="size" icon="el-icon-delete" @click="handleResetBtn">清空</el-button>
      </template>
    </avue-form>
    <h3 class="page-title">{{ pageTitle }}</h3>
    <div style="display: flex; align-items: center;">
      <year-month-select v-model="yearAndMonth" :showAllYear="false" style="margin: 6px 0 20px;"></year-month-select>
    </div>
    <template v-if="listData.length">
      <common-list
        v-for="(item, index) of listData"
        :data="item"
        :type="type"
        :key="index"
        style="margin-bottom: 25px;" 
        @printClick="handlePrintClick"
        @exportClick="handleExportClick"
      ></common-list>
    </template>
    <el-empty v-else description="暂无数据"></el-empty>

    <WideTablePrinter
      ref="printWideTable"
      :columns="wideTableColumns"
      :data="wideTableData"
      :print-title="pageTitle"
      :rows-per-page="30"
      :default-landscape="true"
      :zoom="95"
    >
      <template slot="tableHeader">
        <div>
          <span style="margin-right: 140px;">{{ `研发项目编号：${currProject.xmbh}` }}</span>
          <span>{{ `研发项目名称：${currProject.xmmc}` }}</span>
        </div>
      </template>
      <template slot="tableFooter">
        <div>
          <span style="margin-right: 140px;">发料人：</span>
          <span>发料人：</span>
        </div>
        <div style="margin-top: 6px;">
          <span>项目负责人：</span>
        </div>
      </template>
    </WideTablePrinter>
  </basic-container>
</template>

<script>
import YearMonthSelect from "@/components/year-month-select";
import commonList from "./common-list.vue";
import { getList } from "@/api/yfCostManage/yfCostStatistics/clCost";
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 {
  props: {
    type: {
      type: String,
      // 材料、动力、燃料
      default: "材料"
    }, 
  },
  components: {
    YearMonthSelect,
    commonList
  },
  data() {
    return {
      loading: false,
      searchOption: {
        submitBtn:false,
        emptyBtn:false,
        column: [{
          label: '项目名称',
          prop: 'xmmc',
          type: 'input',
        }, {
          label: '材料名称',
          prop: 'name',
        }, {
          label: '型号规格',
          prop: 'model',
          display: this.type === '材料' ? true : false,
        }, {
          label: '日期',
          prop: 'useDate',
          type: 'date',
        }]
      },
      listData: [],

      yearAndMonth: "",
      params: {},

      wideTableColumns: [],
      wideTableData: [],
      currProject: {}
    }
  },
  watch: {
    yearAndMonth() {
      this.loadData();
    }
  },
  computed: {
    ...mapGetters(['tag']),
    pageTitle() {
      let yearAndMonthCN = this.yearAndMonth ? moment(this.yearAndMonth).format('yyyy年MM月') : '';
      return `${yearAndMonthCN}${this.tag.label}`.replace(/每月/g, '');
    }
  },
  methods: {
    loadData() {
      let params = { ...this.params };
      if (params.useDateRange && params.useDateRange.length) {
        params.dateMin = params.useDateRange[0];
        params.dateMax = params.useDateRange[1];
      }
      delete params.useDateRange;
      this.loading = true;
      getList({
        ...params,
        yearAndMonth: this.yearAndMonth,
        type: this.type,
      }).then(({ data }) => {
        this.loading = false;
        if (data.code == 200) {
          let allList = [];
          data.data.map(item => {
            Object.keys(item).map(key => {
              console.log(item[key])
              let newList = item[key].map(childItem => {
                childItem.amount = new Decimal(childItem.unitPrice || 0).mul(new Decimal(childItem.useQuantity || 0)).toFixed(2);
                return childItem;
              })
              allList.push(newList);
            });
          });

          this.listData = allList;
        }
      }).catch(() => {
        this.loading = false;
      });
    },
    handleSearchBtn() {
      this.loadData();
    },
    handleResetBtn() {
      this.params = {};
      this.$refs.searchForm.resetForm();
      this.loadData();
    },
    handlePrintClick({ column, data, projectData }) {
      this.wideTableColumns = [...column];
      this.wideTableData = data;
      this.currProject = projectData;
      this.$nextTick(() => {
        this.$refs.printWideTable.printTable(true);
      })
    },
    handleExportClick({ xmId, useDate, yearAndMonth }) {
      const exportParams = { useDate, xmId, yearAndMonth, type: this.type };
      exportBloByPost(`/api/kd-scientific/goods/yanfalingliaodan/export?${this.website.tokenHeader}=${getToken()}`, exportParams).then(res => {
        downloadXls(res.data, `${this.pageTitle}.xlsx`);
      });
    },
  },
}
</script>

<style lang="scss">
.cl-search-form {
  .el-form-item--small .el-form-item__label {
    display: none;
  }
  .el-form-item--small .el-form-item__content {
    margin-left: 8px !important;
  }
  .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item  {
    margin-bottom: 6px;
  }
  .avue-form__group .el-col {
    width: auto !important;
    padding-top: 0 !important;
  }
}
</style>
