<!--
  @description: 减免收费单-新增
  @Modifier：王俊楠
  @routerPath:
  @date：  2020-11-03 09:31:27
-->
<template>
  <div>
    <el-form
      ref="formData"
      label-position="left"
      :model="formData"
      :rules="rules"
      :inline-message="true"
    >
      <table class="tableData">
        <tr>
          <td>流水号</td>
          <td>自动生成</td>
          <td>供应商名称</td>
          <td>{{ formData.supplierName }}</td>
        </tr>
        <tr>
          <td>应收服务费金额（元）</td>
          <td>
            {{ numFilter(formData.shouldChargeMoney) }}
          </td>
          <td>减免服务费金额（元）</td>
          <td>
            {{ numFilter(formData.reliefMoney) }}
          </td>
        </tr>
        <tr>
          <td>收取服务费金额（元）</td>
          <td colspan="3">
            {{ numFilter(formData.voucherMoney) }}
          </td>
        </tr>
        <tr>
          <td>
            <el-form-item label="减免收费原因" prop="remark" />
          </td>
          <td colspan="3">
            <gx-input
              v-model.trim="formData.remark"
              :autosize="{ minRows: 3, maxRows: 3 }"
              type="textarea"
              gx-maxlength="varchar200"
            />
          </td>
        </tr>
        <tr>
          <td>说明文件</td>
          <td colspan="3">
            <upload
              ref="upload"
              :data="jmskdFileTypeData"
              :auto-delete="true"
              :auto-upload="true"
              title=""
              file-ref="fileRef"
            />
          </td>
        </tr>
      </table>
    </el-form>
    <div class="mt10 mb10">
      <el-button type="primary" @click="serviceOrderCollected">
        选择待收取服务费
      </el-button>
    </div>
    <el-form ref="formTable" :model="formTable" :rules="formTable.rules" inline-message>
      <el-table
        ref="singleTable"
        :data="formTable.tableData"
      >
        <el-table-column
          type="index"
          label="序号"
          align="center"
          width="50"
        />
        <el-table-column
          prop="orderCode"
          label="订单编号"
          align="center"
          width="180"
        />
        <el-table-column
          :formatter="formatterOrderTotalMoney"
          prop="taxOrderTotalMoney"
          label="订单含税金额（元）"
          align="right"
          min-width="120"
          header-align="center"
        />
        <el-table-column
          :formatter="formatterOrderTotalMoney"
          prop="shouldChargeMoney"
          label="应收服务费金额（元）"
          align="right"
          min-width="150"
          header-align="center"
        />
        <el-table-column
          prop="reliefMoney"
          label="减免金额"
          min-width="200"
          header-align="center"
          align="center"
        >
          <template slot="header">
            <span class="red-star">*</span>
            <span>减免金额</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'tableData.' + scope.$index + '.reliefMoney'" :rules="formTable.rules.reliefMoney">
              <money
                :unit-fixed="2"
                :money-value="scope.row"
                width="auto"
                size="mini"
                name="reliefMoney"
                @input="getSummaries()"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          prop="tenderNo"
          label="采购单结果"
          min-width="200"
          header-align="center"
          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>
    </el-form>
    <!--保存按钮-->
    <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="cancelCollection"
    />
  </div>
</template>

<script>
/* api*/
import { generateProcurementReceipt, payeeSingleDetails, removeServiceSingle } from '@/api/procurement/procurementOrder'
/* 公用方法*/
import { characters1_auto } from '@/assets/js/validate'// 校验输入内容
/* 组件*/
import upload from '@comp/common/updownload/upload' // 附件上传组件
import money from '@comp/common/money/money'// 金额
import serviceOrderCollectedDialog from '../procurementOrderServeFeeReceive/serviceOrderCollected-dialog'
/* ==========工作流===========*/
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 { orderServeFeeMixins } from '../../mixins/orderServeFeeMixins'
/* 常用方法*/
import { randomData } from '@/assets/js/utils/index'
export default {
  name: 'ProcurementServeOrderReceiptSureDialog',
  components: {
    money, // 金额
    upload, // 文件上传
    serviceOrderCollectedDialog, // 选择待收取服务费
    processNodeCom,
    departDialog
  },
  mixins: [workCommonMixins, orderServeFeeMixins],
  props: {
    orderReceiptInfo: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      flowStatus: this.$route.query.flowStatus, // true 工作流进入驳回编辑
      confirmLoading: false, // 控制按钮重复点击Loding
      processDefinitionKey: '', // 工作流流程key
      voucherAuditConfig: false, // 是否启动工作流配置
      formTable: {
        tableData: [],
        rules: {
          reliefMoney: [{ required: true, validator: characters1_auto, trigger: 'blur' }]
        }
      },
      formData: {
        fileId: '',
        ifRelief: '1', // 是否减免 0 否 1是
        purchaseDepartName: '', // 采购单位名称
        // 服务费明细
        reductionServiceFeeDtos: [],
        taxOrderTotalMoney: 0, // 含税订单总金额
        remark: '', // 备注
        serviceFeeIds: '', // 服务费详情Id 用逗号分隔
        supplierId: '', // 供应商id
        supplierName: '', // 供应商名称
        voucherMoney: 0, // 服务费金额
        reliefMoney: 0, // 减免金额
        shouldChargeMoney: 0, // 应收服务费金额
        id: '', // 收款单ID
        auditRecordId: ''// 审核记录ID
      },
      // 校验输入内容
      rules: {
        remark: [{ required: true, validator: characters1_auto, trigger: 'blur' }] // 取消收费原因
      }
    }
  },
  created() {
    this.processDefinitionKey = workconstant.receiptModelCreateJm // 工作流流程key
    this.getSystemConfig() // 获取配置是否启动工作流
  },
  mounted() {
    // 工作流进入编辑获取详情
    if (this.flowStatus) {
      const id = this.$route.query.packId
      this.getPayeeSingleDetails(id)
    } else {
      this.formData.fileId = randomData()// 随机生成ID
      this.jmskdFileTypeData.bizId = this.formData.fileId
      this.initData()
    }
  },
  methods: {
    // 审批详情--收款单、减免收款单
    getPayeeSingleDetails(id) {
      payeeSingleDetails(id).then(res => {
        this.formData = res.data
        this.formData.id = this.formData.bizId
        this.jmskdFileTypeData.bizId = this.formData.bizId
        this.formData.auditRecordId = res.data.proProjectProcurementVoucherAuditRecordEntityVo.id
        this.formTable.tableData = res.data.reductionServiceFeeDtos
        this.formTable.tableData.map(item => {
          item.shouldChargeMoney = item.amountServiceFeeMoney // 应收服务费金额
        })
      }).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.formTable.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.handelBizTotalMoney()
      }
    },
    // 取消收费接口方法
    cancelCollection() {
      const reductionServiceFeeDtos = []
      const list = []
      let reductionServiceFee = {}
      this.formTable.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, // 含税订单总金额(元)
          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 => {
        if (response.data < 50) {
          this.$message.warning('虚拟收款卡的剩余数量小于50,请尽快补充!')
        }
        this.handelClose()
        this.confirmLoading = false
      }).catch(() => {
        this.confirmLoading = false
      })
    },
    // 校验减免金额
    validateReliefMoney() {
      let verify = true
      this.formTable.tableData.map((item) => {
        if (item.reliefMoney && item.reliefMoney > item.shouldChargeMoney) {
          this.$message.warning('减免服务费金额不能大于实际服务费金额！')
          verify = false
        } else {
          verify = true
        }
      })
      return verify
    },
    // 确认取消
    submit() {
      if (this.formTable.tableData && this.formTable.tableData.length > 0) {
        const verify = this.validateReliefMoney()
        if (verify) {
          // 同时校验
          Promise.all([this.$refs.formData.validate(), this.$refs.formTable.validate()]).then((valid) => {
            // 校验通过
            if (valid) {
              // 是否启动工作流
              if (this.voucherAuditConfig) {
                if (JSON.stringify(this.processNode) !== '{}' && this.processNode.nodeId) {
                  this.$refs.departDialog.getUserDepart(this.processNode)
                }
              } else {
                this.cancelCollection()
              }
            } else {
              this.$message.warning('请注意页面提示信息')
              return false
            }
          })
        }
      } else {
        this.$message.warning('请选择待收取服务费')
      }
    },
    // 选择待收取服务费
    serviceOrderCollected() {
      this.$refs.serviceOrderCollected.openDialog(this.formData, this.formTable.tableData)
    },
    // 已选服务单
    selectedServiceOrder(data) {
      this.formTable.tableData = [...this.formTable.tableData, ...data]
      this.handelBizTotalMoney()
    },
    // 移除服务单
    remove(row, index) {
      this.$confirm('确认移除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'confirmBtn',
        cancelButtonClass: 'cancelBtn',
        type: 'warning'
      }).then(() => {
        removeServiceSingle(row.id).then(res => {
          this.formTable.tableData.splice(index, 1)
          this.handelBizTotalMoney()
          this.getSummaries()
        }).catch(() => {})
      }).catch(() => {
      })
    },
    // 计算应收服务费金额
    handelBizTotalMoney() {
      let amountServiceFeeMoney = 0
      this.formTable.tableData.map((item) => {
        amountServiceFeeMoney += Number(item.shouldChargeMoney)
        this.formData.taxOrderTotalMoney += Number(item.taxOrderTotalMoney)
      })
      this.formData.shouldChargeMoney = amountServiceFeeMoney
      // 实际服务费金额 = 应收服务费金额 - 减免金额
      this.formData.voucherMoney = this.formData.shouldChargeMoney - this.formData.reliefMoney
    },
    // 减免金额计算
    getSummaries() {
      let reliefMoney = 0
      this.formTable.tableData.map(item => {
        if (item.reliefMoney) {
          reliefMoney += Number(item.reliefMoney)
        }
      })
      this.formData.reliefMoney = reliefMoney
      // 实际服务费金额 = 应收服务费金额 - 减免金额
      this.formData.voucherMoney = this.formData.shouldChargeMoney - this.formData.reliefMoney
    },
    //  关闭弹框
    handelClose() {
      // 工作流进入
      if (this.flowStatus) {
        const routePathStatus = sessionStorage.getItem('routePathStatus') // 工作流处理 00桌面进入 01待办列表进入
        this.$router.push({
          path: routePathStatus === '00' ? '/home' : '/work/todo'
        })
      } else {
        this.$emit('close')
        this.formData.remark = ''
        this.$refs.formData.clearValidate()
      }
    }
  }
}
</script>

<style scoped lang="less">
  /deep/.from_table{
    .file-list{
      .fileBtn{
        margin-bottom: 0;
      }
    }
  }
  /deep/.el-form-item--small.el-form-item{
    margin-bottom: 0;
  }
</style>
