<!--
  @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="from_table">
        <tr>
          <td>
            <el-form-item ref="voucherCode" label="收款单号" prop="voucherCode" />
          </td>
          <td>
            <el-input
              v-model="formData.voucherCode"
              disabled="disabled"
              placeholder="请选择"
              style="width: calc(90% - 102px)"
            />
            <el-button type="primary" @click="selectBill">
              选择收款单
            </el-button>
          </td>
          <td>
            <el-form-item label="供应商名称" prop="supplierName" />
          </td>
          <td>{{ formData.supplierName }}</td>
        </tr>
        <tr>
          <td>
            <el-form-item label="入账银行账号" prop="bankno" />
          </td>
          <td>
            {{ formData.bankno }}
          </td>
          <td>
            <el-form-item label="入账时间" prop="createTime" />
          </td>
          <td>{{ formData.createTime }}</td>
        </tr>
        <tr>
          <td>
            <el-form-item label="入账金额(元)" prop="payMoney" />
          </td>
          <td>
            {{ numFilter(formData.payMoney) }}
          </td>
          <td>
            <el-form-item label="本次确认缴费金额(元)" prop="thisHandMoney" />
          </td>
          <td>
            {{ numFilter(formData.thisHandMoney) }}
          </td>
        </tr>
        <tr>
          <td>
            <el-form-item label="未处理金额(元)" prop="surplusMoney" />
          </td>
          <td>
            {{ numFilter(formData.surplusMoney) }}
          </td>
          <td>
            <el-form-item label="已处理金额(元)" prop="useMoney" />
          </td>
          <td>
            {{ numFilter(formData.useMoney) }}
          </td>
        </tr>
        <tr>
          <td>
            <el-form-item label="异常原因" prop="remarks" />
          </td>
          <td colspan="3">
            <gx-input
              v-model.trim="formData.remarks"
              :autosize="{ minRows: 3, maxRows: 3 }"
              type="textarea"
              gx-maxlength="varchar200"
            />
          </td>
        </tr>
        <tr>
          <td>
            <el-form-item label="说明文件" />
          </td>
          <td colspan="3">
            <upload
              ref="upload"
              :data="upLoadData"
              :auto-delete="true"
              :auto-upload="true"
              title=""
              file-ref="fileRef"
            />
          </td>
        </tr>
      </table>
    </el-form>
    <div class="mt10 mb10">
      <el-button type="primary" :disabled="!formData.voucherCode" @click="chooseOrder">
        选择订单
      </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="160"
        />
        <el-table-column
          :formatter="formatterOrderTotalMoney"
          prop="orderTotalMoney"
          label="订单金额（元）"
          min-width="120"
          header-align="center"
          align="right"
        />
        <el-table-column
          :formatter="formatterOrderTotalMoney"
          prop="actualChargeMoney"
          label="服务费金额（元）"
          min-width="120"
          header-align="center"
          align="right"
        />
        <el-table-column
          :formatter="formatterOrderTotalMoney"
          prop="paidMoney"
          label="已缴金额（元）"
          min-width="120"
          header-align="center"
          align="right"
        />
        <el-table-column
          prop="confirmMoney"
          label="确认缴费金额（元）"
          min-width="150"
          header-align="center"
          align="right"
        >
          <template slot="header">
            <span class="red-star">*</span>
            <span>确认缴费金额（元）</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'tableData.' + scope.$index + '.confirmMoney'" :rules="formTable.rules.confirmMoney">
              <money
                :money-value="scope.row"
                width="auto"
                size="mini"
                name="confirmMoney"
                @input="getConfirmMoney()"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          :formatter="formatterOrderStatus"
          prop="status"
          label="缴费状态"
          min-width="100"
          header-align="center"
          align="center"
        />
      </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="ensure">
          提 交
        </el-button>
      </div>
    </div>
    <!--选择收费单-->
    <selectBillDialog ref="selectBill" @selectBillData="selectBillData" />
    <!--选择订单-->
    <voucherOrderListDialog ref="voucherOrder" @selectedServiceOrder="selectedServiceOrder" />
    <!--工作流选择节点组件-->
    <processNode-com
      ref="processNode"
      :process-definition-key="processDefinitionKey"
      @processNodeData="processNodeData"
    />
    <!--工作流流程节点/获取审核用户-->
    <depart-dialog
      ref="departDialog"
      :process-node="processNode"
      @isSingleUser="isSingleUser"
      @processInitData="processInitData"
      @submit="sureAbnormalCollection"
    />
  </div>
</template>

<script>
/* api*/
import { manualHandleExcepPay, payeeSingleExcepDetails } from '@/api/procurement/procurementOrder'
/* 公用方法*/
import { characters1_auto } from '@/assets/js/validate'// 校验输入内容
import { cloneObject } from '@/assets/js/utils' // 字典方法
/* 组件*/
import upload from '@comp/common/updownload/upload'// 文件上传组件
import money from '@comp/common/money/money'// 金额
import voucherOrderListDialog from './voucherOrderList-dialog' // 选择订单
import selectBillDialog from './selectBill-dialog'
import { orderServeFeeMixins } from '../../mixins/orderServeFeeMixins'
/* ==========工作流===========*/
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' // 选择审核人员
/* ============================*/

export default {
  name: 'ProcurementServeOrderReceiptSureDialog',
  components: {
    upload, // 文件上传
    money, // 金额
    selectBillDialog, // 选择收费单弹框
    voucherOrderListDialog, // 选择订单
    processNodeCom,
    departDialog
  },
  mixins: [orderServeFeeMixins, workCommonMixins],
  props: {
    orderReceiptInfo: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      flowStatus: this.$route.query.flowStatus, // true 工作流进入驳回编辑
      confirmLoading: false, // 控制按钮重复点击Loding
      processDefinitionKey: '', // 工作流流程key
      voucherAuditConfig: false, // 是否启动工作流配置
      abnormalPayVisibleDialog: false, // 是否打开弹框
      formTable: {
        tableData: [],
        rules: {
          confirmMoney: [{ required: true, validator: characters1_auto, trigger: 'blur' }]
        }
      },
      formData: {
        bankno: '', // 账号（入账账号）
        createTime: '', // 创建时间（入账时间）
        processInitDto: {}, // 工作流信息
        listExceptionServiceFeeOrderInfoDtoList: [
          /*         {
            paidMoney: 0, // 实际收取保证金金额（已缴费）
            confirmMoney: 0, // 确认缴费金额
            id: '', // 服务费主键id
            orderCode: '', // 订单编号
            orderTotalMoney: 0, // 订单总额(元)
            recordId: '', // 异常费用ID
            shouldChargeMoney: 0, // 应该收取服务费金额(元)(服务费金额（元）
            status: '', // 00待确认 01待缴费 02全部缴费 03已取消缴费 04部分缴费
            supplierId: '', // 供应商ID
            voucherId: '' // 收款单主键id
          }*/
        ],
        recordId: '', // 异常费用ID
        payMoney: 0, // 入账金额
        remarks: '', // 备注
        supplierId: '', // 供应商ID
        supplierName: '', // 供应商名称
        surplusMoney: 0, // 剩余金额
        useMoney: 0, // 已使用金额
        voucherCode: '', // 收款单编号
        voucherId: '', // 收款单ID
        thisHandMoney: 0 // 待确认缴费
      },
      upLoadData: {
        bizId: '',
        fileType: 'excep_pay_handle'
      },
      // 校验输入内容
      rules: {
        remarks: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 异常原因
        voucherCode: [{ required: true, validator: characters1_auto, trigger: 'blur' }] // 收款单号
      }
    }
  },
  created() {
    this.processDefinitionKey = workconstant.receiptModelCreateCombinOrder // 工作流流程key
    this.getSystemConfig() // 获取配置是否启动工作流
  },
  mounted() {
    // 获取字典信息
    this.getGroupType()
    // 工作流进入编辑获取详情
    if (this.flowStatus) {
      const id = this.$route.query.packId
      this.getExcepPayeeHandDetailsInfo(id)
    } else {
      this.initData()
    }
  },
  methods: {
    // 异常缴费处理记录详情
    getExcepPayeeHandDetailsInfo(id) {
      payeeSingleExcepDetails(id).then(res => {
        this.formData = res.data
        this.formTable.tableData = res.data.listExceptionServiceFeeOrderInfoDtoList
      }).catch(() => {
      })
    },
    // 初始化数据
    initData() {
      this.formData.supplierId = this.orderReceiptInfo.supplierId // 供应商ID
      this.formData.supplierName = this.orderReceiptInfo.supplierName // 供应商名称
      this.formData.bankno = this.orderReceiptInfo.bankno// 账号（入账账号）
      this.formData.createTime = this.orderReceiptInfo.createTime // 创建时间（入账时间）
      this.formData.useMoney = this.orderReceiptInfo.useMoney // 已使用费用额度
      this.formData.payMoney = this.orderReceiptInfo.payMoney // 入账金额
      this.formData.surplusMoney = this.orderReceiptInfo.surplusMoney // 剩余费用额度
      this.formData.recordId = this.orderReceiptInfo.id // 异常费用id
      this.abnormalPayVisibleDialog = true
    },
    // 确认异常缴费接口方法
    sureAbnormalCollection() {
      const paramsList = []
      this.formTable.tableData.map((item) => {
        paramsList.push({
          actualChargeMoney: item.actualChargeMoney, // 实际收取保证金金额（已缴费）
          paidMoney: item.paidMoney, // 已缴纳金额
          orderCode: item.orderCode, // 订单编号
          confirmMoney: item.confirmMoney ? item.confirmMoney : 0, // 确认缴费金额
          orderTotalMoney: item.orderTotalMoney, // 订单总额
          recordId: '', // 异常费用id
          shouldChargeMoney: item.shouldChargeMoney, // 应该收取服务费金额(元)(服务费金额（元）
          supplierId: item.supplierId,
          id: item.id,
          voucherId: this.formData.voucherId
        })
      })
      this.formData.listExceptionServiceFeeOrderInfoDtoList = paramsList
      // 启动工作流添加工作流参数
      if (this.voucherAuditConfig) {
        this.processInitDto.type = '01' // 01：初次提交 02：审核驳回再次提交
        this.formData.processInitDto = this.processInitDto // 审核人信息传回得信息
      }
      this.confirmLoading = true
      manualHandleExcepPay(this.formData).then(response => {
        this.confirmLoading = false
        this.handelClose()
      }).catch(() => {
        this.confirmLoading = false
      })
    },
    // 根据键获取配置 是否工作流审核
    getSystemConfig() {
      this.$store.dispatch('getSystemConfigValue', 'voucher-audit-config').then(() => {
        this.voucherAuditConfig = this.$store.getters.systemConfigVo.configType
      }).catch(() => {
      })
    },
    // 确认
    ensure() {
      const verifyAmountList = this.verifyAmountList()
      if (verifyAmountList) {
        // 同时表单必填项是否通过校验
        Promise.all([this.$refs.formData.validate(), this.$refs.formTable.validate()]).then((valid) => {
          if (valid) { // 校验通过
            // 是否选择订单
            if (this.formTable.tableData && this.formTable.tableData.length > 0) {
              // 是否启动工作流
              if (this.voucherAuditConfig) {
                if (JSON.stringify(this.processNode) !== '{}' && this.processNode.nodeId) {
                  this.$refs.departDialog.getUserDepart(this.processNode)
                }
              } else {
                this.sureAbnormalCollection()
              }
            } else {
              this.$message.warning('请选择订单')
            }
          } else {
            this.$message.warning('请注意页面提示信息')
            return false
          }
        })
      }
    },
    // 提交时校验 输入的确认缴费金额+已缴费金额，不能大于服务费金额
    verifyAmountList() {
      let verifyAmount = true
      if (this.formData.thisHandMoney > Number(this.formData.surplusMoney)) {
        this.$message({
          type: 'warning',
          message: '本次缴费金额，不能大于未处理金额'
        })
        verifyAmount = false
      }
      this.formTable.tableData.map(item => {
        if ((Number(item.confirmMoney) + Number(item.paidMoney)) > Number(item.shouldChargeMoney)) {
          this.$message({
            type: 'warning',
            message: '确认缴费金额+已缴费金额，不能大于服务费金额'
          })
          verifyAmount = false
        }
        if (Number(item.confirmMoney) === '') {
          this.$message({
            type: 'warning',
            message: '请输入确认缴费金额'
          })
          verifyAmount = false
        }
      })
      return verifyAmount
    },
    // 选择订单
    chooseOrder() {
      this.$refs.voucherOrder.openDialogVoucherOrder(this.formData)
    },
    // 已选订单
    selectedServiceOrder(data) {
      const tableData = cloneObject(this.formTable.tableData)// 深拷贝-当前勾选标段（包）
      const tableDataArr = tableData.concat(data)
      this.formTable.tableData = tableDataArr
    },
    // 选择收款单
    selectBill() {
      this.$refs.selectBill.openDialog(this.formData.supplierId)
    },
    // 已选择收费单
    selectBillData(data) {
      this.formData.voucherCode = data.voucherCode
      this.formData.voucherId = data.id
    },
    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.$refs.formData.resetFields()
        this.$refs.formTable.resetFields()
        this.formTable.tableData = []
        this.abnormalPayVisibleDialog = false
      }
    },
    getConfirmMoney() {
      let confirmMoneys = 0
      this.formTable.tableData.map(item => {
        if (item.confirmMoney) {
          confirmMoneys += Number(item.confirmMoney)
        }
      })
      this.formData.thisHandMoney = confirmMoneys.toFixed(2)
    }
  }
}
</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>
