<template>
  <el-dialog
    title="选择核价单"
    :visible.sync="visible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    top="5vh"
    :close-on-press-escape="false"
    append-to-body
    width="70%"
  >
    <el-card shadow="never">
      <searchProduct @search="reload"></searchProduct>
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="datasource"
        :selection.sync="selection"
        cache-key="eomContactPageTable"
        height="calc(100vh - 480px)"
        class="dict-table"
      >

      </ele-pro-table>
    </el-card>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" size="small" @click="selected"
      >生成合同
      </el-button
      >
      <el-button size="small" @click="handleClose">关闭</el-button>
    </div>


  </el-dialog>
</template>

<script>
import {generateContract, getTableList, isHasGeneratedContractPI} from '@/api/purchasingManage/inquiryManage';
import searchProduct from '@/views/purchasingManage/inquiryManage/components/searchQuotation.vue';
import generateContractsDialog from "@/views/purchasingManage/inquiryManage/components/generateContractsDialog.vue";

export default {
  components: {
    generateContractsDialog,
    searchProduct
  },

  data() {
    return {
      visible: false,
      currentIndex: null,
      selection: [],
      columns: [
        {
          width: 45,
          type: 'selection',
          columnKey: 'selection',
          align: 'center'
        },
        {
          columnKey: 'index',
          label: '序号',
          type: 'index',
          width: 55,
          align: 'center',
          showOverflowTooltip: true,
          fixed: 'left'
        },
        {
          prop: 'inquiryName',
          slot: 'inquiryName',
          label: '采购询价名称',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 200
        },
        {
          prop: 'inquiryCode',
          slot: 'inquiryCode',
          label: '采购询价编码',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 200
        },
        {
          prop: 'planCode',
          slot: 'planCode',
          label: '采购计划编码',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 200
        },
        {
          prop: 'supplierNames',
          label: '供应商名称',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 200
        },
        {
          prop: 'winnerSupples',
          label: '中标供应商',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 200
        },
        {
          prop: 'createTime',
          label: '创建时间',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 180
        },
        {
          prop: 'remark',
          label: '备注',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 170
        }
      ]
    };
  },

  watch: {},
  methods: {
    open() {
      this.visible = true;
    },

    /* 表格数据源 */
    datasource({page, limit, where, order}) {
      return getTableList({
        pageNum: page,
        size: limit,
        ...where,
        status: 2
      });
    },

    /* 刷新表格 */
    reload(where) {
      this.$refs.table.reload({pageNum: 1, where: where});
    },
    async selected() {
      let data = await this.addGenerateContract();
      await this.setContractInfo(data);
    },
    //新增合同
    async addGenerateContract() {
      let {verify, text, ids, isOnly} = this.verify();
      if (!verify) return this.$message.warning(text);
      if (isOnly) {
        return await this.getContractInfo(ids)
      } else {
        let sourceId = this.selection.map(item => item.id).join(',')
        let sourceName = this.selection.map(item => item.inquiryName).join(',');
        this.$emit('changeParent', {data:null,sourceId,sourceName});
        this.handleClose();
      }
    },
    async getContractInfo(ids) {
      //核价单是否生成过合同
      let res = await isHasGeneratedContractPI(
        {inquiryIds: ids, supplierId: this.selection[0].winnerSuppleIds}
      )
      if (res.result) this.$message.warning(res.message)
      return await generateContract({inquiryIds: ids, supplierId: this.selection[0].winnerSuppleIds});
    },
    async setContractInfo(data) {
      if (data) {
        data.contractVO.contractName = data.contractVO.partbName
        //获取优惠金额和总计的差价
        let diffPrice = Number(data.contractVO.totalPrice) - Number(data.contractVO.discountTotalPrice)
        data.productList.forEach((item) => {
          if (data.contractVO.discountTotalPrice === 0) {
            item.discountTotalPrice = 0
            item.discountSinglePrice = 0
            return
          }
          if (!data.contractVO.discountTotalPrice) {
            item.discountTotalPrice = item.totalPrice
            item.discountSinglePrice = item.singlePrice
            return
          }
          //获取详情每条的小计
          // 使用小计除以总价得出该条数据小计占比 在乘以差价或的该条数据应承担的差价 在小计-应承担差价获得折让后的小计
          item.discountTotalPrice = (Number(item.totalPrice) - Number(item.totalPrice) / Number(data.contractVO.totalPrice) * diffPrice).toFixed(2)
          //使用折让后的小计除以数量得到单价
          item.discountSinglePrice = (Number(item.discountTotalPrice) / Number(item.totalCount)).toFixed(2)
        })
        let sourceId = this.selection.map(item => item.id).join(',')
        let sourceName = this.selection.map(item => item.inquiryName).join(',');
        let winnerSupples = this.selection.map(item => item.winnerSupples).join(',');
        this.$emit('changeParent', {data, sourceName,sourceId,winnerSupples});
        this.handleClose();
      }
    },

    // 合同验证
    verify() {
      let verify = true;
      let text = '';
      let ids = [];
      let isOnly = true;
      if (this.selection.length == 0) {
        verify = false;
        text = '请至少选择一条数据';
      }
      if (this.selection.length > 1) {
        if (this.selection.some(item => item.winnerSuppleIds.split(',').length > 1)) {
          verify = false;
          text = '多核价单且含有多个核价清单的数据不允许批量生成合同';
        } else if (this.selection.some(item => !item.winnerSuppleIds.split(',').filter(item => item).length)) {
          verify = false;
          text = '所选核价单中标供应商为空';
        } else if (this.selection.some(item => this.selection[0].winnerSuppleIds !== item.winnerSuppleIds)) {
          verify = false;
          text = '所选核价单中标供应商不一致';
        } else {
          isOnly = true
        }
      } else {
        isOnly = this.selection[0].winnerSuppleIds.split(',').filter(item => item).length == 1
        if (!this.selection[0].winnerSuppleIds.split(',').filter(item => item).length) {
          verify = false;
          text = '核价单中标供应商为空';
        }
      }
      if (verify) {
        ids = this.selection.map((item) => item.id);
      }
      return {verify, text, ids, isOnly};
    },

    handleClose() {
      this.visible = false;
      this.current = null;
    },


  }
};
</script>

<style lang="scss" scoped>
.tree_col {
  border: 1px solid #eee;
  padding: 10px 0;
  box-sizing: border-box;
  height: 500px;
  overflow: auto;
}

.table_col {
  padding-left: 10px;

  ::v-deep .el-table th.el-table__cell {
    background: #f2f2f2;
  }
}

.pagination {
  text-align: right;
  padding: 10px 0;
}

.btns {
  text-align: center;
  padding: 10px 0;
}

.topsearch {
  margin-bottom: 15px;
}
</style>
