<template>
  <div class="refund-apply-content">
    <cy-info-title>基础信息</cy-info-title>
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-position="top" label-width="120px" class="rule-form-orange">
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="ruleForm.projectName" placeholder="请输入项目名称" :disabled="disabled" />
      </el-form-item>
      <el-form-item label="核心企业名称" prop="customerName">
        <el-input v-model="ruleForm.customerName" placeholder="请输入核心企业名称" :disabled="disabled" />
      </el-form-item>
      <el-form-item label="供应商（主体）名称" prop="supplierName">
        <el-input v-model="ruleForm.supplierName" placeholder="请输入供应商（主体）名称" :disabled="disabled" />
      </el-form-item>
      <el-form-item label="贸易平台" prop="platformName">
        <el-input v-model="ruleForm.platformName" placeholder="请输入贸易平台" :disabled="disabled" />
      </el-form-item>
      <el-form-item label="业务编号" prop="businessNumber">
        <el-input v-model="ruleForm.businessNumber" placeholder="请输入业务编号" :disabled="disabled" />
      </el-form-item>
      <el-form-item label="保理合同编号" prop="contractNumber">
        <el-input v-model="ruleForm.contractNumber" placeholder="请输入保理合同编号" :disabled="disabled" />
      </el-form-item>
      <el-form-item label="支用批次" prop="quotaDisburseBatch">
        <el-input v-model="ruleForm.quotaDisburseBatch" placeholder="请输入支用批次" :disabled="disabled" />
      </el-form-item>
      <div v-for="(item, index) in refundDetails" :key="index" style="width: 100%;">
        <cy-info-title> {{ `第${index + 1}笔应退明细` }} </cy-info-title>
        <div style="width: 100%; margin-top: 20px">
          <cy-comm-table
            ref="commTable"
            :columns="columns"
            :data="item"
            :count="0"
          />
        </div>
      </div>
      <cy-info-title style="margin-top: 20px">收放款执行</cy-info-title>
      <div style="width: 100%">
        <cy-comm-table
          ref="commTable"
          :columns="implementColumns"
          :data="payPlanData"
          :count="0"
        />
      </div>
      <div v-for="(item, index) in ruleForm.refundsApplyDetails" :key="index + 1" style="width: 100%; display: flex; flex-wrap: wrap;">
        <cy-info-title style="margin-top: 20px">{{ getApplyDetailsDesc(item) }}</cy-info-title>
        <el-form-item label="申请类型" class="form-required">
          <el-radio-group v-model="item.applyType">
            <el-radio :label="1" :disabled="disabled">退款</el-radio>
            <el-radio :label="2" :disabled="disabled">抵扣</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="item.applyType !== 2" label="表单类型">
          <el-input v-model="item.formListTypeName" placeholder="请输入表单类型" :disabled="disabled" />
        </el-form-item>
        <el-form-item v-if="item.applyType !== 2" label="付款主体公司" class="form-required">
          <el-select v-model="item.oaCompanyEntityInfoId" placeholder="请选择付款主体公司" :disabled="disabled">
            <el-option
              v-for="single in mainCompanyList"
              :key="single.value"
              :label="single.label"
              :value="single.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="item.applyType !== 2" label="付款事项">
          <el-input v-model="item.paymentMatterDic.name" placeholder="请输入付款事项" :disabled="disabled" />
        </el-form-item>
        <el-form-item v-if="item.applyType !== 2" label="项目类型">
          <el-input v-model="item.projectTypeDic.name" placeholder="请输入项目类型" :disabled="disabled" />
        </el-form-item>
        <el-form-item v-if="item.applyType !== 2" label="付款事由" class="form-required">
          <el-input v-model="item.paymentReason" placeholder="请输入付款事由" :disabled="disabled" />
        </el-form-item>
        <el-form-item v-if="item.applyType !== 2" label="付款总金额">
          <el-input v-model="item.paymentAmountTotal" placeholder="请输入付款总金额" :disabled="disabled" />
        </el-form-item>
        <el-form-item v-if="item.applyType !== 2" label="币种">
          <el-input v-model="item.currency" placeholder="请输入币种" :disabled="disabled" />
        </el-form-item>
        <el-form-item v-if="item.applyType !== 2" label="付款方式" class="form-required">
          <el-select v-model="item.paymentMethod" placeholder="请选择付款方式" :disabled="disabled">
            <el-option
              v-for="single in payMentOptions"
              :key="single.value"
              :label="single.label"
              :value="single.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="item.applyType !== 2" label="支付日期" class="form-required">
          <el-date-picker
            v-model="item.paymentDate"
            type="date"
            placeholder="请选择选择支付日期"
            value-format="yyyy-MM-dd"
            :disabled="disabled"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item v-if="item.applyType !== 2" label="收方账户信息" prop="name" style="width: 100%;">
          <cy-comm-table
            ref="commTable"
            :columns="accountColumns"
            :data="item.accountInfoList"
            :count="0"
          />
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { queryApplyContent, queryMainCompany } from '@/api/refundManage'

export default {
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    detailsInfo: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      ruleForm: {
        refundsApplyDetails: []
      },
      rules: {

      },
      refundDetails: [], // 应退名细
      payPlanData: [], // 收放款执行
      accountTableData: [], // 收款方账户信息
      columns: [
        {
          label: '序号',
          index: true
        },
        {
          label: '分账单号',
          prop: 'ledgerNumber',
          showTooltip: true
        },
        {
          label: '入账时间',
          prop: 'ledgerDate',
          showTooltip: true
        },
        {
          label: '入账标签',
          prop: 'label',
          render: (h, row) => {
            if (row.label === '' || row.label === null) {
              return (h('div', ''))
            }
            return row.label === 1 ? (h('div', '上游回购')) : (h('div', '下游回款'))
          }
        },
        {
          label: '金额类型',
          prop: 'amountTypeDic.name',
          showTooltip: true
        },
        {
          label: '金额',
          prop: 'amount',
          showTooltip: true
        },
        {
          label: '选中',
          prop: 'amount',
          render: (h, row) => {
            return (
              <el-checkbox disabled={this.disabled} onChange={ () => { this.refundTableChange(row) } } v-model={row.selected}></el-checkbox>
            )
          }
        }
      ],
      implementColumns: [
        {
          label: '序号',
          index: true
        },
        {
          label: '金额类型',
          prop: 'amountTypeName',
          showTooltip: true
        },
        {
          label: '收放款类型',
          prop: 'paymentCollectionTypeName',
          showTooltip: true
        },
        {
          label: '约定日期',
          prop: 'planDate',
          showTooltip: true
        },
        {
          label: '应收/付金额',
          prop: 'amount',
          showTooltip: true
        },
        {
          label: '实收/付日期',
          prop: 'postName',
          render: (h, row) => {
            if (row && row.amountAllocationList.length) {
              return (
                row.amountAllocationList.map(item => {
                  return h('div', item.actualDate)
                })
              )
            }
          }
        },
        {
          label: '实收/付金额',
          prop: 'postName',
          render: (h, row) => {
            if (row && row.amountAllocationList.length) {
              return (
                row.amountAllocationList.map(item => {
                  return h('div', item.actualAmount)
                })
              )
            }
          }
        },
        {
          label: '状态',
          prop: 'statusStr',
          showTooltip: true
        },
        {
          label: '选中',
          prop: 'amount',
          render: (h, row) => {
            return (
              <el-checkbox disabled={this.disabled} onChange={ () => { this.paymentTableChange(row) } } v-model={row.selected}></el-checkbox>
            )
          }
        }
      ],
      accountColumns: [
        {
          label: '序号',
          index: true
        },
        {
          label: '收款账户名称',
          prop: 'collectionAccountName',
          // showTooltip: true,
          ruleRequired: true,
          render: (h, row) => {
            return (
              <el-input disabled={this.disabled} v-model={row.collectionAccountName}></el-input>
            )
          }
        },
        {
          label: '收款账号',
          prop: 'collectionAccount',
          // showTooltip: true
          ruleRequired: true,
          render: (h, row) => {
            return (
              <el-input disabled={this.disabled} v-model={row.collectionAccount}></el-input>
            )
          }
        },
        {
          label: '收款账号开户行',
          prop: 'collectionBankName',
          // showTooltip: true
          ruleRequired: true,
          render: (h, row) => {
            return (
              <el-input disabled={this.disabled} v-model={row.collectionBankName}></el-input>
            )
          }
        }
      ],
      mainCompanyList: [], // 主体公司
      payMentOptions: [] // 付款方式
    }
  },
  computed: {
    ...mapGetters(['constant'])
  },
  watch: {
    detailsInfo: {
      handler(val) {
        console.log(!this.isEmptyObj(val))
        if (val && !this.isEmptyObj(val)) {
          this.setViewData(val)
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.queryPaymentOptions()
    this.getMainCompanyList()
  },
  methods: {
    queryPaymentOptions() {
      this.$store.dispatch('getConstant', ['oaBillPaymentType']).then(() => {
        if (this.constant.oaBillPaymentType.length) {
          this.constant.oaBillPaymentType.forEach(el => {
            this.payMentOptions.push({
              value: el.code,
              label: el.name
            })
          })
        }
      })
    },
    // 设置对应数据
    setViewData(data) {
      this.groupBaseInfoData(data)
      this.refundDetails = data.ledgerDetails || []
      this.payPlanData = data.paymentCollectionPlanFactorings || []
      this.ruleForm.refundsApplyDetails = data.refundsApplyDetails || []
      // if (!this.disabled) {
      //   this.queryApply()
      // } else {
      //   this.ruleForm.refundsApplyDetails = data.refundsApplyDetails
      // }
    },
    // 获取申请内容标题文案
    getApplyDetailsDesc(row) {
      if (row.paymentMatter === 'oaRefundMatter') {
        return `申请内容（履约保证金+质保金+收放款执行）`
      }
      return `申请内容（实退金额）`
    },
    // 重组基础信息数据
    groupBaseInfoData(targetData) {
      const formItems = ['projectName', 'customerName', 'supplierName', 'platformName', 'businessNumber', 'contractNumber', 'quotaDisburseBatch', 'businessStatus']
      formItems.forEach(el => {
        if (el in targetData && targetData[el]) {
          this.ruleForm[el] = targetData[el]
        } else {
          this.ruleForm[el] = ''
        }
      })
    },
    // 应退明细表格选中单项change
    refundTableChange() {
      this.queryApply()
    },
    // 收放款执行表格change
    paymentTableChange() {
      this.queryApply()
    },
    // 获取申请内容
    queryApply() {
      const queryParams = {
        Loading: true,
        ledgerDetails: this.refundDetails,
        paymentCollectionPlanFactorings: this.payPlanData,
        businessNumber: this.ruleForm.businessNumber
      }
      queryApplyContent(queryParams).then((res) => {
        console.log('queryApplyContent res: ---------')
        console.log(res)
        if (res.data && res.data.length) {
          for (let i = 0; i < res.data.length; i++) {
            // 如果默认抵扣的话那么只显示申请类型其他信息隐藏
            if (res.data[i] && res.data[i].overdue) {
              res.data[i].applyType = 2
            }
          }
        }
        this.ruleForm.refundsApplyDetails = res.data || []
      })
    },
    // 获取主题公司列表
    getMainCompanyList() {
      queryMainCompany().then((res) => {
        if (res.data) {
          res.data.forEach(el => {
            this.mainCompanyList.push({
              ...el,
              label: el.companyName,
              value: el.id
            })
          })
        }
      })
    },
    // 提交前的校验
    beforeSubmitValidate() {
      if (this.ruleForm.refundsApplyDetails && this.ruleForm.refundsApplyDetails.length > 0) {
        const validateFields = ['applyType', 'oaCompanyEntityInfoId', 'paymentReason', 'paymentMethod', 'paymentDate']
        const validFormDesc = {
          'applyType': '请选择申请类型',
          'oaCompanyEntityInfoId': '请选择付款主体公司',
          'paymentReason': '请输入付款事由',
          'paymentMethod': '请选择付款方式',
          'paymentDate': '请选择支付日期'
        }
        return new Promise((resolve, reject) => {
          for (let el = 0; el < this.ruleForm.refundsApplyDetails.length; el++) {
            if (!this.ruleForm.refundsApplyDetails[el].applyType || this.ruleForm.refundsApplyDetails[el].applyType === 1) {
              for (let it = 0; it < validateFields.length; it++) {
                if (!this.ruleForm.refundsApplyDetails[el][validateFields[it]] || this.ruleForm.refundsApplyDetails[el][validateFields[it]] === '') {
                  this.$message.warning(validFormDesc[validateFields[it]])
                  return reject({ status: 'fail' })
                }
              }
              // 当申请内容的申请类型为抵扣时不校验收款账户信息

              // 申请内容基础表单信息校验完成后开始检验对应的收款账户信息
              if (this.ruleForm.refundsApplyDetails && this.ruleForm.refundsApplyDetails[el].accountInfoList) {
                if (this.ruleForm.refundsApplyDetails[el].accountInfoList.length === 0) {
                  this.$message.warning('收款方账户信息不能为空')
                  return reject({ status: 'fail' })
                } else {
                  const validateRes = this.checkArrayObjects(this.ruleForm.refundsApplyDetails[el].accountInfoList)
                  if (!validateRes) {
                    this.$message.warning('请填写完整的收方账户信息')
                    return reject({ status: 'fail' })
                  }
                }
              } else {
                this.$message.warning('请填写完整的收方账户信息')
                return reject({ status: 'fail' })
              }
            }
          }
          return resolve({ status: 'success' })
        })
      }
    },
    // 判断申请内容的收房账户信息是否为空
    checkArrayObjects(array) {
      for (let i = 0; i < array.length; i++) {
        const obj = array[i]
        for (const key in obj) {
          if (['collectionAccount', 'collectionAccountName', 'collectionBankName'].includes(key) && !obj[key]) {
            return false
          }
        }
      }
      return true
    },
    isEmptyObj(obj) {
      for (const i in obj) {
        return false
      }
      return true
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
