<template>
  <basic-container>
    <div style="margin-top: 6px;">
      <el-form :inline="true">
        <el-form-item label="研发项目名称">
          <project-select v-model="params.xmId" clearable :noDetail="true" @change="handleProjectChange"></project-select>
        </el-form-item>
        <el-form-item label="研发项目编号">
          {{ selProject.xmbh }}
        </el-form-item>
      </el-form>
    </div>

    <avue-crud
      ref="crud"
      v-bind="bindVal"
      v-on="onEvent"
      v-model="form"
      :page.sync="page"
      :before-open="handleBeforeOpen"
      :permission="permissionList"
      @row-dblclick="handleRowDbClick"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-position" @click="handleAddChange">
          发起变更
        </el-button>
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          @click="handleExport"
        >
          导出
        </el-button>
        <print-table-btn @click="printTable" />
      </template>
      
    </avue-crud>

    <WideTablePrinter
      v-if="!hidePrintTable"
      ref="printWideTable"
      :columns="wideTableColumns"
      :data="wideTableData"
      :print-title="pageTitle"
      :rows-per-page="30"
      :default-landscape="true"
      :zoom="80"
    />

    <el-drawer
      v-if="drawerVisible"
      :title="drawerTitle"
      :visible.sync="drawerVisible"
      modal-append-to-body
      append-to-body
      size="960px"
    >
      
      <change-form
        :projectId="params.xmId"
        :data="changeFormData"
        :disabled="isFormReadonly"
        @success="handleChangeSucc"
      >
      </change-form>
    </el-drawer>
  </basic-container>
</template>

<script>
import {exportBloByPost} from "@/api/common";
import {getToken} from "@/util/auth";
import projectSelect from "@/components/project-select";
import {downloadXls} from "@/util/util";
import changeForm from "./components/change-form.vue";
import Decimal from "decimal.js";


export default window.$crudCommon({
  props: {
    projectId: [String, Number],
    hidePrintTable: {
      type: Boolean,
      default: false
    }
  },
  components: {
    changeForm,
    projectSelect
  },
  data() {
    return {
      params: {
        xmId: ''
      },
      selProject: {},

      drawerTitle: "",
      drawerVisible: false,

      wideTableColumns: [],
      wideTableData: [],

      changeFormData: {},
      isFormReadonly: false,
    };
  },
  watch: {
    "params.xmId"() {
      this.page.currentPage = 1;
      this.getList(this.page);
    }
  },
  computed: {
    pageTitle() {
      return `${this.selProject.xmmc || ''}项目变更列表`;
    }
  },
  created() {
    this.params.xmId = this.projectId;
  },
  methods: {
    handleProjectChange(data) {
      this.selProject = data;
    },
    handleExport() {
      exportBloByPost(`/api/kd-scientific/xm-bgrz/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(false);
      })
    },
    handleAddChange() {
      this.drawerVisible = true;
      this.isFormReadonly = false;
      this.drawerTitle = "发起变更";
      this.changeFormData = {};
    },
    handleRowDbClick(data) {
      this.drawerVisible = true;
      this.isFormReadonly = true;
      this.drawerTitle = "变更详情";
      this.changeFormData = {
        ...data,
        attachment: data.attachment ? JSON.parse(data.attachment) : []
      };
    },
    handleChangeSucc() {
      this.drawerVisible = false;
      this.getList();
    },
  },
}, {
  // 模块路径
  name: 'projectManage/change',
  res: ({data}) => {
    // 计算预算总额
    const calcXmAmountTotal = list => {
      let total = new Decimal(0);
      list.forEach(item => {
        total = total.add(new Decimal(item.amount || 0));
      });
      return total;
    };
    const formatXmysLabel = list => {
      let yearAmountCN = list.map(item => {
        return `${item.year}年${item.amount}万元`;
      }).join('、');
      let total = calcXmAmountTotal(list);
      return `总计:${total}万元；其中${yearAmountCN}`
    }
    data.records = data.records.map(item => {
      // 项目预算
      if (item.zdmc === 'XMYSZEMX') {
        // 变更前的值
        let bgqmx = JSON.parse(item.bgqdz);
        item.bgqdzJSON = bgqmx;
        item.bgqdz = formatXmysLabel(bgqmx);

        // 变更后的值
        let bghmx = JSON.parse(item.bghdz);
        item.bghdzJSON = bghmx;
        item.bghdz = formatXmysLabel(bghmx)
      } else if (item.zdmc === 'STATUS') {
        let projectStatusEnum = {
          "1" : "开展中",
          "2" : "已结题",
          "3" : "项目暂停",
          "4" : "项目终止",
        };
        item.bgqdz = projectStatusEnum[item.bgqdz];
        item.bghdz = projectStatusEnum[item.bghdz];
      }

      return item;
    });
    return data;
  }
});
</script>
