<!--
  @description: 申请退款
  @Modifier: sunxinman/haofengxian
  @routerPath: /fee/applyRefund
  @date: 2020/03/31-10:45
-->
<template>
  <div>
    <section v-if="!flowStatus" class="title p0-16 clearfix">
      <!-- 返回 -->
      <div class="title-back pointer" @click="back()">
        <i class="iconfont icon-fanhui mr10" />申请退款
      </div>
    </section>
    <!-- 表格部分 -->
    <section :class="flowStatus?'':'p0-16'">
      <div>
        <el-table
          ref="smallTable"
          v-loading="loading"
          :data="tableData"
          @selection-change="selectionChange"
        >
          <el-table-column
            type="selection"
            width="55"
          />
          <el-table-column
            type="index"
            label="序号"
            fixed="left"
            width="60px"
            align="center"
          />
          <!-- 投标人  -->
          <el-table-column

            prop="supplierName"
            fixed="left"
            label="投标人"
            min-width="220"
          />
          <!-- 错误来款 -->
          <el-table-column
            v-if="bailShowShielding"
            :formatter="formatErrorStatus"
            header-align="center"
            prop="errorStatus"
            label="错误来款"
            align="center"
            min-width="80"
          />
          <!-- 子账号 -->
          <el-table-column

            header-align="center"
            label="子账号"
            prop="accountNo"
            min-width="160"
          />
          <!-- 可用退款金额（元） -->
          <el-table-column
            header-align="center"
            prop="toRefundedAmount"
            label="可用退款金额（元）"
            min-width="120"
            align="right"
          />
          <!-- 当前退款金额（元） -->
          <el-table-column
            header-align="center"
            prop="refundedAmount"
            label="当前退款金额（元）"
            min-width="120"
            align="right"
          >
            <template slot-scope="scope">
              <money :money-value="scope.row" width="auto" name="refundedAmount" @input="verifyAmount(scope.row)" />
            </template>
          </el-table-column>
          <!-- 退款账户名称 -->
          <el-table-column

            header-align="center"
            prop="payerName"
            label="退款账户名称"
            min-width="120"
          />
          <!-- 退款账号 -->
          <el-table-column
            header-align="center"
            prop="payerNo"
            label="退款账号"
            min-width="160"
            align="center"
          />
          <!-- 退款开户行 -->
          <el-table-column
            header-align="center"
            label="退款开户行"
            prop="payerBankName"
            align="left"
            min-width="200"
          />
          <!-- 退款联行号 -->
          <el-table-column
            label="退款联行号"
            prop="payerBankNo"
            min-width="110"
          />
          <!-- 备注 -->
          <el-table-column
            label="备注"
            prop="remark"
            min-width="110"
          >
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" />
            </template>
          </el-table-column>

          <!-- 附件 -->
          <el-table-column
            align="center"
            label="附件"
            min-width="500"
          >
            <template slot-scope="scope">
              <upload
                ref="uploadFed"
                :auto-delete="true"
                :auto-upload="true"
				:limit="1"
                :data="scope.row.uploadFileData"
                title=""
              />
            </template>
          </el-table-column>

          <!-- 操作 -->
          <el-table-column
            header-align="center"
            label="操作"
            fixed="right"
            align="center"
            width="80"
          >
            <template slot-scope="scope">
              <el-link
                type="primary"
                @click.stop="handleChange(scope.row, scope.$index)"
              >
                [变更]
              </el-link>
            </template>
          </el-table-column>
        </el-table>
        <p class="allTotal">
          合计退款金额（元）：<span>{{ refundMoneyFormat(refundAmountTotal) }}</span>
        </p>
      </div>
    </section>
    <!--操作按钮-->
    <div class="but_footer">
      <div class="but_footer-h">
        <div class="but_footer-but">
          <el-button :loading="confirmLoading" type="primary" @click="submitAudit('form')">
            提交审批
          </el-button>
          <el-button @click="back">
            关闭
          </el-button>
        </div>
      </div>
    </div>
    <!-- 变更信息弹框 -->
    <changeInfoDialog ref="changeInfo" @childrenChangeInfo="childrenChangeInfo" />
    <!--工作流选择节点组件-->
    <processNode-com
      ref="processNode"
      :process-definition-key="processDefinitionKey"
      @processNodeData="processNodeData"
    />
    <!--工作流流程节点/获取审核用户-->
    <depart-dialog
      ref="departDialog"
      :process-node="processNode"
      @isSingleUser="isSingleUser"
      @processInitData="processInitData"
      @submit="submit"
    />
  </div>
</template>
<script>
/* 接口*/
import { queryPackRefundBillList, applyRefundDeposit, queryEditRefundBillInfo } from '@api/fee/bailfee'
/* 混合开发方法-参数字段*/
import { ListMixin } from '@/mixins/ListMixin'// 分页
import { cashDepositGroupMixin } from '../../mixins/cashDepositGroupMixin'
import { depositSystemConfig } from '../../mixins/depositSystemConfig'
import processNodeCom from '@views/work/processNodeCom' // 工作流节点组件
import departDialog from '@views/work/depart-dialog' // 工作流审核人员组件
import { workCommonMixins } from '@views/work/mixins/workCommonMixins' // 工作流公共方法
/* 公共方法*/
import workconstant from '@/assets/js/workutils/workconstant' // 工作流存放key文件
/* 组件*/
import changeInfoDialog from './changeInfo-dialog'
import money from '@comp/common/money/money'// 金额
/* 公用方法*/
import { moneyFormat } from '@assets/js/utils'// 常用方法
import upload from '@comp/common/updownload/upload' // 附件上传组件
export default {
  name: 'ApplyRefund',
  components: {
    money, // 金额
    upload,
    changeInfoDialog,
    'processNode-com': processNodeCom,
    'depart-dialog': departDialog
  },
  mixins: [cashDepositGroupMixin, ListMixin, depositSystemConfig, workCommonMixins],
  data() {
    return {
      flowStatus: this.$route.query.flowStatus, // 01 工作流进入驳回编辑
      processDefinitionKey: '', // 工作流流程id
      bailfeeApplyRefundConfigType: this.$store.getters.systemConfigVo.configType, // 保证金退款审批配置true启动工作流 false普通审核
      refundMoneyFormat: moneyFormat, // 金额添加千分位
      confirmLoading: false, // 提交按钮Loding
      packId: '', // 标段id
      refundDetailId: '', // 退款明细id
      loading: true,
      tableData: [], // 可退款交易明细列表
      checkedTr: [], // 已勾选需提交审批的信息
      refundAmountTotal: 0 // 退款金额总计
    }
  },
  created() {
    // 工作流进入
    if (this.flowStatus) {
      this.packId = this.$route.query.packId // 标段id
      this.refundDetailId = this.$route.query.bizId // 退款明细id
    } else {
      this.packId = this.$route.params.packId // 标段id
      this.refundDetailId = this.$route.params.refundDetailId // 退款明细id
    }
    // 根据键获取正式配置
    this.$store.dispatch('getSystemConfigValue', 'docfee-audit-config').then(() => {
      this.bailfeeApplyRefundConfigType = this.$store.getters.systemConfigVo.configType // true启动工作流 false普通审核
    }).catch(() => {
    })
    const editorStatus = this.$route.params.editorStatus ? this.$route.params.editorStatus : false // 用来区分是否编辑
    /* editorStatus true为编辑 false 是初始化
    * editorStatus && refundDetailId存在明细id 为编辑*/
    if (editorStatus && this.refundDetailId) {
      this.getDetailInfo()
    } else {
      // 获取包组下可退款交易明细列表
      this.getPackRefundBillList()
    }
  },
  methods: {
    /* ========================申请退款/编辑获取列表处理start=================================*/
    // 获取包组下可退款交易明细列表（申请退款初始化数据）
    getPackRefundBillList() {
      const params = {
        pageNo: this.paginationData.pageNo,
        pageSize: this.paginationData.pageSize,
        packId: this.packId
      }
      queryPackRefundBillList(params).then(response => {
        this.loading = false
        this.tableData = response.data.records
        this.tableDataAddUploadParam(this.tableData)
      }).catch(() => {
        this.loading = false
      })
    },
    // 编辑退款申请（查看保证金退款详细信息）
    getDetailInfo() {
      queryEditRefundBillInfo(this.refundDetailId).then(response => {
        this.loading = false
        this.tableData = response.data.records
        this.tableDataAddUploadParam(this.tableData)
      }).catch(() => {
        this.loading = false
      })
    },

    tableDataAddUploadParam(tableData) {
      tableData.forEach(item => {
        item['uploadFileData'] = {
          bizId: item.refundDetailId,
          fileType: 'refund_audit_file'
        }
      })
    },

    /* ========================申请退款/编辑获取列表处理start=================================*/
    // 复选框事件（勾选需要提交审批的信息）
    selectionChange(val) {
      this.checkedTr = val
      this.handleRefundAmount()
    },
    // 合计退款金额
    handleRefundAmount() {
      let contractBudget = 0
      this.checkedTr.forEach(item => {
        if (item.refundedAmount) {
          contractBudget += Number(item.refundedAmount)
        }
      })
      this.refundAmountTotal = contractBudget
    },
    // 判断是否来款错误
    verifyWrong() {
      let verify = true
      const selectedRowErrorStatus = this.checkedTr.map(item => item.errorStatus) // 已勾选是否错误来款状态
      const statusArr = []
      selectedRowErrorStatus.map(item => {
        if (!statusArr.includes(item)) {
          statusArr.push(item)
        }
      })
      if (statusArr.length > 1) { // 既选择了是 也选择了 否
        this.$message({
          type: 'warning',
          message: '错误来款不能与非错误来款同时发起审批'
        })
        verify = false
        return verify
      }
      // 判断 如果长度是1的话 并且数组中的值 是00 那么就是正常款项  如果是01的话 就是 错误款项
      if (statusArr[0] === '01') {
        this.processDefinitionKey = workconstant.feeDepositErrorOfAudit // 保证金错误来款工作流key
        verify = true
      } else {
        this.processDefinitionKey = workconstant.feedepositeTrueOfaduit // 保证金正确来款工作流key
        verify = true
      }
      return verify
    },
    // 填写输入框提示 控制退款金额不能大于可退款金额
    verifyAmount(row) {
      if (row.refundedAmount > row.toRefundedAmount) {
        this.$message({
          type: 'warning',
          message: '退款金额不能大于可退款金额'
        })
      }
      this.handleRefundAmount()
    },
    // 提交时校验 控制退款金额不能大于可退款金额
    verifyAmountList() {
      let verifyAmount = true
      this.checkedTr.map(item => {
        if (item.refundedAmount > item.toRefundedAmount) {
          this.$message({
            type: 'warning',
            message: '退款金额不能大于可退款金额'
          })
          verifyAmount = false
        }
      })
      return verifyAmount
    },
    // 提交审批
    submitAudit() {
      if (this.checkedTr.length) {
        const verify = this.verifyWrong()
        const verifyAmountList = this.verifyAmountList()
        if (verify && verifyAmountList) {
          this.$confirm('确认提交保证金退款审批吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            confirmButtonClass: 'confirmBtn',
            cancelButtonClass: 'cancelBtn',
            type: 'warning'
          }).then(() => {
            /* bailfeeApplyRefundConfigType true启动工作流 false普通审核*/
            if (this.bailfeeApplyRefundConfigType) {
              // 启动工作流
              if (JSON.stringify(this.processNode) !== '{}' && this.processNode.nodeId) {
                this.$refs.departDialog.getUserDepart(this.processNode)
              }
            } else {
              // 直接提交
              this.submit()
            }
          }).catch(() => {
          })
        }
      } else {
        this.$message({
          type: 'warning',
          message: '至少选择一条记录'
        })
      }
    },
    // 提交调用接口方法
    submit() {
      const params = {
        processInitDto: {},
        refundApplyList: this.checkedTr
      }
      /* bailfeeApplyRefundConfigType true启动工作流 添加工作流参数*/
      if (this.bailfeeApplyRefundConfigType) {
        this.processInitDto.type = '01' // 01：初次提交 02：审核驳回再次提交
        params.processInitDto = this.processInitDto // 审核人信息传回得信息
      }
      this.confirmLoading = true
      applyRefundDeposit(params).then(() => {
        this.$message({
          type: 'success',
          message: '提交成功'
        })
        this.back()
        this.confirmLoading = false
      }).catch(() => {
        this.confirmLoading = false
      })
    },
    /* =======================变更start=======================*/
    // 点击变更事件
    handleChange(row, index) {
      // 触发子组件方法
      this.$refs.changeInfo.openDialogGetDetail(row, index)
    },
    // 接收子组件变更传回参数
    childrenChangeInfo(formData, index) {
      const refundApplyData = {
        changeId: formData.refundDetailChangeId, // 退款变更Id
        changeStatus: formData.changeStatus ? formData.changeStatus : '00', // 退款变更状态00无变更01有变更
        payerBankName: formData.desBankName, // 退款开户行
        payerBankNo: formData.desBankNo, // 退款联行号
        payerName: formData.desName, // 退款账户名称
        payerNo: formData.desNo // 退款账号
      }
      this.tableData[index] = Object.assign(this.tableData[index], refundApplyData) // 合并变更信息展示到表格
    },
    /* =======================变更end=======================*/
    // 返回
    back() {
      // 工作流进入返回待办列表
      if (this.flowStatus) {
        this.$router.push({
          path: '/work/todo'
        })
      } else {
        const queryData = {
          ...this.$route.params
        }
        delete queryData.refundDetailId
        this.$router.push({
          path: '/fee/refundManage',
          name: 'RefundManageList',
          params: {
            ...queryData
          }
        })
      }
    }
  }
}
</script>
<style lang="less" scoped>
.allTotal{
  line-height: 36px;
  margin-left: 16px;
  span {
    color:red
  }
}
</style>
