<!--
  @description: 服务费单管理-生成收款单-弹窗
  @Modifier：王俊楠
  @routerPath:
  @date：  2020-11-03 09:31:27
-->
<template>
  <div>
    <table class="tableData">
      <tr>
        <td>收款单号</td>
        <td>自动生成</td>
        <td>供应商名称</td>
        <td>{{ formData.supplierName }}</td>
      </tr>
      <tr>
        <td>订单含税总额（元）</td>
        <td>
          {{ numFilter(formData.taxOrderTotalMoney) }}
        </td>
        <td>收取服务费金额（元）</td>
        <td>
          {{ numFilter(formData.voucherMoney) }}
        </td>
      </tr>
      <tr>
        <td>说明文件</td>
        <td colspan="3">
          <upload
            ref="upload"
            :data="skdFileTypeData"
            :auto-delete="true"
            :auto-upload="true"
            title=""
            file-ref="fileRef"
          />
        </td>
      </tr>
    </table>
    <div class="mt10 mb10">
      <el-button type="primary" @click="serviceOrderCollected">
        选择待收取服务费
      </el-button>
    </div>
    <el-table ref="singleTable" :data="tableData">
      <el-table-column
        type="index"
        label="序号"
        align="center"
        width="50"
      />
      <el-table-column
        prop="orderCode"
        label="订单编号"
        align="center"
        width="160"
      />
      <el-table-column
        :formatter="formatterOrderTotalMoney"
        prop="taxOrderTotalMoney"
        label="订单含税金额（元）"
        align="right"
        width="130"
        header-align="center"
      />
      <el-table-column
        :formatter="formatterOrderTotalMoney"
        prop="shouldChargeMoney"
        label="服务费金额（元）"
        align="right"
        width="120"
        header-align="center"
      />
      <el-table-column
        prop="supplierName"
        label="供应商名称"
        header-align="center"
        min-width="180"
      />
      <el-table-column
        prop="tenderNo"
        label="采购单结果"
        header-align="center"
      />
      <el-table-column
        :formatter="formatterIfRelief"
        prop="ifRelief"
        label="有无减免"
        align="center"
        header-align="center"
      />
      <el-table-column
        prop="remark"
        label="减免原因"
        header-align="center"
      />
      <el-table-column
        label="操作"
        width="90"
        header-align="center"
        align="center"
      >
        <template slot-scope="scope">
          <el-link type="primary" @click.stop="remove(scope.row,scope.$index)">
            [移除]
          </el-link>
        </template>
      </el-table-column>
    </el-table>
    <!--保存按钮-->
    <div v-if="flowStatus" class="but_footer">
      <div class="but_footer-h" />
      <div class="but_footer-but">
        <el-button type="primary" :loading="confirmLoading" @click="submit">
          提 交
        </el-button>
      </div>
    </div>
    <!--选择待收取服务费-->
    <serviceOrderCollectedDialog ref="serviceOrderCollected" @selectedServiceOrder="selectedServiceOrder" />
    <!--工作流选择节点组件-->
    <processNode-com
      ref="processNode"
      :process-definition-key="processDefinitionKey"
      @processNodeData="processNodeData"
    />
    <!--工作流流程节点/获取审核用户-->
    <depart-dialog
      ref="departDialog"
      :process-node="processNode"
      @isSingleUser="isSingleUser"
      @processInitData="processInitData"
      @submit="saveProcurementReceipt"
    />
  </div>
</template>

<script>
/* api*/
import { generateProcurementReceipt, payeeSingleDetails, removeServiceSingle } from '@/api/procurement/procurementOrder'
import { orderServeFeeMixins } from '../../mixins/orderServeFeeMixins'
/* 组件*/
import serviceOrderCollectedDialog from '../procurementOrderServeFeeReceive/serviceOrderCollected-dialog'
import money from '@comp/common/money/money'// 金额
import upload from '@comp/common/updownload/upload' // 附件上传组件
/* ==========工作流===========*/
import { workCommonMixins } from '@views/work/mixins/workCommonMixins' // 工作流公共配置
import workconstant from '@/assets/js/workutils/workconstant/purOrder' // 配置流程key
import processNodeCom from '@views/work/processNodeCom' // 工作流选择节点组件
import departDialog from '@views/work/depart-dialog' // 选择审核人员
/* ============================*/
/* 常用方法*/
import { randomData } from '@/assets/js/utils/index'
export default {
  name: 'ProcurementServeOrderReceiptSureDialog',
  components: {
    money, // 金额
    upload, // 文件上传
    serviceOrderCollectedDialog, // 选择待收取服务费
    processNodeCom,
    departDialog
  },
  mixins: [orderServeFeeMixins, workCommonMixins],
  props: {
    orderReceiptInfo: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      flowStatus: this.$route.query.flowStatus, // true 工作流进入驳回编辑
      confirmLoading: false, // 控制按钮重复点击Loding
      processDefinitionKey: '', // 工作流流程key
      voucherAuditConfig: false, // 是否启动工作流配置
      tableData: [],
      formData: {
        auditRecordId: '',
        id: '',
        ifRelief: '0', // 是否减免 0 否 1是
        purchaseDepartName: '', // 采购单位名称
        processInitDto: {}, // 工作流信息
        // 服务费明细
        reductionServiceFeeDtos: [
          /*      {
            actualServiceFeeMoney: '', // 实际服务费金额
            amountServiceFeeMoney: '', // 应收服务费金额
            id: '', // 服务单ID
            reductionServiceFeeMoney: '' // 减免服务费金额
          }*/
        ],
        fileId: '',
        reliefMoney: 0, // 减免 金额
        remark: '', // 备注
        serviceFeeIds: '', // 服务费详情Id 用逗号分隔
        supplierId: '', // 供应商id
        supplierName: '', // 供应商名称
        voucherMoney: 0, // 服务费金额
        taxOrderTotalMoney: 0, // 含税订单总额
        shouldChargeMoney: 0 // 应收服务费金额
      }
    }
  },
  created() {
    this.processDefinitionKey = workconstant.receiptModelCreate // 工作流流程key
    this.getSystemConfig() // 获取配置是否启动工作流
  },
  mounted() {
    // 工作流进入编辑获取详情
    if (this.flowStatus) {
      const id = this.$route.query.packId
      this.getPayeeSingleDetails(id)
    } else {
      this.formData.fileId = randomData()// 随机生成ID
      this.skdFileTypeData.bizId = this.formData.fileId
      this.initData()
    }
  },
  methods: {
    // 审批详情--收款单、减免收款单
    getPayeeSingleDetails(id) {
      payeeSingleDetails(id).then(res => {
        this.formData = res.data
        this.formData.id = this.formData.bizId
        this.formData.auditRecordId = res.data.proProjectProcurementVoucherAuditRecordEntityVo.id
        this.skdFileTypeData.bizId = this.formData.bizId
        this.tableData = res.data.reductionServiceFeeDtos
        this.tableData.map(item => {
          item.shouldChargeMoney = item.amountServiceFeeMoney // 应收服务费金额
          item.reliefMoney = item.reductionServiceFeeMoney // 减免服务费金额
          item.supplierName = this.formData.supplierName
          item.ifRelief = this.formData.ifRelief
          item.remark = this.formData.remark
        })
      }).catch(() => {
      })
    },
    // 根据键获取配置 是否工作流审核
    getSystemConfig() {
      this.$store.dispatch('getSystemConfigValue', 'voucher-audit-config').then(() => {
        this.voucherAuditConfig = this.$store.getters.systemConfigVo.configType
      }).catch(() => {
      })
    },
    // 初始化接口方法
    initData() {
      if (this.orderReceiptInfo.length > 0) {
        this.tableData = this.orderReceiptInfo
        this.formData.purchaseDepartName = this.orderReceiptInfo[0].purchaseDepartName
        this.formData.supplierId = this.orderReceiptInfo[0].supplierId
        this.formData.supplierName = this.orderReceiptInfo[0].supplierName
        this.formData.tenderNo = this.orderReceiptInfo[0].tenderNo
        this.calculationAmount()
        this.handelBizTotalMoney()
      }
    },
    // 选择待收取服务费
    serviceOrderCollected() {
      this.$refs.serviceOrderCollected.openDialog(this.formData, this.tableData)
    },
    // 已选服务单
    selectedServiceOrder(data) {
      this.tableData = [...this.tableData, ...data]
      this.calculationAmount()
      this.handelBizTotalMoney()
    },
    // 移除服务单
    remove(row, index) {
      this.$confirm('确认移除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'confirmBtn',
        cancelButtonClass: 'cancelBtn',
        type: 'warning'
      }).then(() => {
        removeServiceSingle(row.id).then(res => {
          this.tableData.splice(index, 1)
          this.calculationAmount()
          this.handelBizTotalMoney()
        }).catch(() => {})
      }).catch(() => {
      })
    },
    // 计算应收服务费金额
    handelBizTotalMoney() {
      let amountServiceFeeMoney = 0
      this.tableData.map((item) => {
        amountServiceFeeMoney += Number(item.shouldChargeMoney)
      })
      this.formData.shouldChargeMoney = amountServiceFeeMoney
      // 实际服务费金额 = 应收服务费金额 - 减免金额
      this.formData.voucherMoney = this.formData.shouldChargeMoney - this.formData.reliefMoney
    },
    // 计算金额
    calculationAmount() {
      let taxOrderTotalMoney = 0
      this.tableData.map((item) => {
        taxOrderTotalMoney += Number(item.taxOrderTotalMoney)
        this.formData.voucherMoney += Number(item.shouldChargeMoney)
      })
      this.formData.taxOrderTotalMoney = taxOrderTotalMoney
    },
    // 确定生成收款单
    submit() {
      if (this.tableData && this.tableData.length > 0) {
        // 是否启动工作流
        if (this.voucherAuditConfig) {
          if (JSON.stringify(this.processNode) !== '{}' && this.processNode.nodeId) {
            this.$refs.departDialog.getUserDepart(this.processNode)
          }
        } else {
          this.saveProcurementReceipt()
        }
      } else {
        this.$message.warning('请选择待收取服务费')
      }
    },
    // 提交-服务费单管理生成收款单
    saveProcurementReceipt() {
      const list = []
      const reductionServiceFeeDtos = []
      let reductionServiceFee = {}
      this.tableData.map(item => {
        reductionServiceFee = {
          actualServiceFeeMoney: Number(item.shouldChargeMoney - item.reliefMoney), // 实际服务费金额
          amountServiceFeeMoney: item.shouldChargeMoney, // 应收服务费金额
          id: item.id, // 服务单ID
          orderCode: item.orderCode, // 订单编号
          orderTotalMoney: item.orderTotalMoney, // 订单总额(元)
          reductionServiceFeeMoney: item.reliefMoney, // 减免服务费金额
          taxOrderTotalMoney: item.taxOrderTotalMoney, // 含税订单总金额(元)
          supplierName: item.supplierName, // 供应商名称
          ifRelief: item.ifRelief, // 有无减免
          remark: item.remark, // 减免原因
          tenderNo: item.tenderNo // 采购单结果
        }
        list.push(item.id)
        reductionServiceFeeDtos.push(reductionServiceFee)
      })
      this.formData.reductionServiceFeeDtos = reductionServiceFeeDtos
      this.formData.serviceFeeIds = list.join(',')
      // 启动工作流添加工作流参数
      if (this.voucherAuditConfig) {
        this.processInitDto.type = '01' // 01：初次提交 02：审核驳回再次提交
        this.formData.processInitDto = this.processInitDto // 审核人信息传回得信息
      }
      this.confirmLoading = true
      generateProcurementReceipt(this.formData).then(response => {
        this.confirmLoading = false
        this.handelClose()
      }).catch(() => {
        this.confirmLoading = false
      })
    },
    handelClose() {
      // 工作流进入
      if (this.flowStatus) {
        const routePathStatus = sessionStorage.getItem('routePathStatus') // 工作流处理 00桌面进入 01待办列表进入
        this.$router.push({
          path: routePathStatus === '00' ? '/home' : '/work/todo'
        })
      } else {
        this.$emit('close')
      }
    }
  }
}
</script>

<style scoped lang="less">
  /deep/.tableData{
    .file-list{
      .fileBtn{
        margin-bottom: 0;
      }
    }
  }
</style>
