<template>
  <div class="financing-plan">
    <div class="info-title">
      <cy-info-title>收放款计划（融资款）</cy-info-title>
      <div>
        <el-button v-if="isTradeFactoring && !disabled" type="primary" @click="getFinancingCalc">一键计算</el-button>
      </div>
    </div>
    <div class="table-box" style="margin-top: 20px;">
      <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
        <el-table-column v-if="oa && !tradeFactoring" type="selection" width="50" :selectable="selectable" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="planDate" label="约定日期" width="160">
          <template slot-scope="{row}">
            <el-date-picker
              v-model="row.planDate"
              style="width: 100%"
              type="date"
              :disabled="disabled || !row.allowedChange || isTradeFactoring"
              placeholder="请选择约定日期"
              :picker-options="pickerOptions(row)"
              @change="getIrrCalc"
            />
          </template>
        </el-table-column>
        <el-table-column prop="amountType" label="金额类型" width="120">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.amountType"

              placeholder="请选择金额类型"
              :disabled="disabled || !scope.row.allowedChange || isTradeFactoring"
              style="width: 100%"
              @change="amountCollectionTypeChange({ index: scope.$index, amountType: scope.row.amountType, paymentCollectionType: scope.row.paymentCollectionType, rowData: scope.row })"
            >
              <el-option
                v-for="item in incormeExpenditureType"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="paymentCollectionType" label="收放款类型" width="120">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.paymentCollectionType"

              placeholder="请选择收放款类型"
              :disabled="disabled || !scope.row.allowedChange || isTradeFactoring"
              style="width: 100%"
              @change="amountCollectionTypeChange({ index: scope.$index, amountType: scope.row.amountType, paymentCollectionType: scope.row.paymentCollectionType, rowData: scope.row })"
            >
              <el-option
                v-for="item in constant.payCollType"
                :key="item.id"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" width="150">
          <template slot-scope="scope">
            <div style="display: flex; align-items: center">
              <span>{{ scope.row.currencyTypeCode }}</span>
              {{ formatMoney(scope.row.amount) }}
              <!-- <cy-amount-input
                v-model="scope.row.amount"
                placeholder="请输入金额"
                :disabled="disabled || !scope.row.allowedChange || isTradeFactoring"
                :clearable="false"
                @change="amountChange(scope.row, scope.$index)"
              /> -->
            </div>

          </template>
        </el-table-column>
        <el-table-column prop="actualCashFlow" label="实际现金流" width="150">
          <template slot-scope="{row}">
            <div style="display: flex; align-items: center">
              <span>{{ row.currencyTypeCode }}</span>
              {{ formatMoney(row.actualCashFlow) }}
              <!-- <cy-amount-input
                v-model="row.actualCashFlow"
                placeholder="请输入实际现金流"
                disabled
              /> -->
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="receivingSubject" label="收款主体" width="110">
          <template slot-scope="{row}">
            <el-select
              v-if="row.receivingSubject"
              v-model="row.receivingSubject"

              placeholder="请选择收款主体"
              style="width: 100%"
              :disabled="disabled || !row.allowedChange || isTradeFactoring"
            >
              <el-option
                v-for="item in constant.receivingSubjectList"
                :key="item.id"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="实收/付日期">
          <template slot-scope="{row}">
            <div v-for="(item, index) in row.paymentCollectionType === 'pay_coll_payment'? row.loanRecordList : row.collRecordList" :key="index">
              {{ row.paymentCollectionType === 'pay_coll_payment' ? item.thisLoanDate : item.actualDate }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="实收/付总金额">
          <template slot-scope="{row}">
            <div v-for="(item, index) in row.paymentCollectionType === 'pay_coll_payment'? row.loanRecordList : row.collRecordList" :key="index">
              {{ row.currencyTypeCode }}  {{ row.paymentCollectionType === 'pay_coll_payment' ? formatMoney(item.thisLoanAmount) : formatMoney(item.actualAmount) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="type !== 'planChange'" prop="overDate" label="宽限到期日" width="160">
          <template slot-scope="{row}">
            <el-date-picker
              v-model="row.overDate"
              style="width: 100%"
              type="date"
              :disabled="disabled || !row.allowedChange || isTradeFactoring"
              placeholder="请选择宽限到期日"
            />
          </template>
        </el-table-column>
        <el-table-column prop="graceType" label="宽限期类型" width="100">
          <template slot-scope="{row}">
            <!-- <el-select
              v-model="row.graceType"

              placeholder="请选择宽限期类型"
              :disabled="disabled || !row.allowedChange || isTradeFactoring"
              style="width: 100%"
            >
              <el-option
                v-for="item in constant.graceTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.value"
              />
            </el-select> -->
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template slot-scope="{row}">
            {{ row.status }}
            <!-- <el-select
              v-model="row.status"

              placeholder="请选择状态"
              :disabled="disabled || !row.allowedChange || isTradeFactoring"
              style="width: 100%"
            >
              <el-option
                v-for="item in paymentCollectionPlanStatus(row)"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select> -->

          </template>
        </el-table-column>
        <el-table-column v-if="!disabled && type === 'planChange' && !isTradeFactoring" label="操作" width="60">
          <template slot-scope="scope">
            <div style="color: #5AC4FC; cursor: pointer;">
              <span @click="modifyClick('add', scope.$index)">新增</span>
              <span v-if="scope.row.allowedDelete" @click="modifyClick('delete', scope.$index)">删除</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-position="top"
      class="rule-form-orange"
    >
      <el-form-item v-if="isMoneyAdvanced" label="原债务种类：">
        <el-select
          v-model="ruleForm.origDbtCate"

          placeholder="请选择原债务种类"
          :disabled="disabled"
        >
          <el-option
            v-for="item in constant.quotaDisburseDebtType"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="isMoneyAdvanced" label="债权转移时的还款状态：">
        <el-select
          v-model="ruleForm.initRpySts"

          placeholder="请选择债权转移时的还款状态"
          class="form-item-border"
        >
          <el-option
            v-for="item in constant.quotaDisburseTransferStatus"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="IRR：">
        <el-input
          v-model="ruleForm.irr"
          placeholder="请输入IRR"
          disabled
        >
          <template slot="append">%</template>
        </el-input>
      </el-form-item>
      <el-form-item label="授信-预期IRR：">
        <el-input
          v-model="ruleForm.contractIrr"
          placeholder="请输入授信-预期IRR"
          disabled
        >
          <template slot="append">%</template>
        </el-input>
      </el-form-item>
      <el-form-item label="额度支用-预期IRR：">
        <el-input
          v-model="ruleForm.quotaIrr"
          placeholder="请输入额度支用-预期IRR"
          disabled
        >
          <template slot="append">%</template>
        </el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { endPickerDate, formatMoney, parseTime, filterListData, codeChangeName } from '@/utils'
export default {
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    financingPlan: {
      type: Object,
      default: () => []
    },
    // type:  planChange: 计划变更
    type: {
      type: String,
      default: ''
    },
    // 是否是贸理通项目
    isTradeFactoring: {
      type: Boolean,
      default: false
    },
    tradeFactoring: {
      type: Boolean,
      default: false
    },
    oa: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      tableData: [],
      selection: [],
      ruleForm: {
        irr: '',
        contractIrr: '',
        quotaIrr: '',
        occupationFlag: '',
        reportDataFlag: '',
        basicId: '',
        origDbtCate: '',
        initRpySts: ''
      },
      rules: {

      },
      loading: false,
      isMoneyAdvanced: false
    }
  },
  computed: {
    ...mapGetters(['constant']),
    formatMoney() {
      return (val) => {
        return formatMoney(val)
      }
    },

    pickerOptions() {
      return (row) => {
        // 修改后逻辑
        const pickerDate = endPickerDate(row.minChangeDate, row.maxChangeDate, true)

        const { reportDataFlag } = this.ruleForm
        // 上报过征信-手动生成未上报征信
        if (reportDataFlag === 2) {
          return {}
        } else {
          return {
            ...pickerDate
          }
        }
      }
    },
    // 金额类型
    incormeExpenditureType() {
      // 占用公司资金-是-金额类型下拉框没有垫款
      if (this.ruleForm.occupationFlag === 1) {
        return filterListData(this.constant.incormeExpenditureType, 'money_advanced')
      } else {
        return this.constant.incormeExpenditureType
      }
    },
    // 状态
    paymentCollectionPlanStatus() {
      return (row) => {
        const amountType = codeChangeName(this.constant.incormeExpenditureType, row.amountType, 'id', 'code')
        // 金额类型-是-逾期利息-修改范围为已豁免、计划中
        if (amountType === 'overdue_interest') {
          if (row.status === 'pay_coll_plan_overdue') {
            return filterListData(this.constant.paymentCollectionPlanStatus, ['pay_coll_plan_executing', 'pay_coll_plan_part_allocate', 'pay_coll_plan_part_completed', 'pay_coll_plan_overdue_completed', 'pay_coll_plan_notneed_completed', 'pay_coll_plan_deduction', 'pay_coll_plan_deduction_completed', 'pay_coll_plan_completed'])
          } else if (row.status === 'pay_coll_planning' || row.status === 'pay_coll_plan_notneed') {
            return filterListData(this.constant.paymentCollectionPlanStatus, ['pay_coll_plan_executing', 'pay_coll_plan_overdue', 'pay_coll_plan_part_allocate', 'pay_coll_plan_part_completed', 'pay_coll_plan_overdue_completed', 'pay_coll_plan_notneed_completed', 'pay_coll_plan_deduction', 'pay_coll_plan_deduction_completed', 'pay_coll_plan_completed'])
          } else {
            return this.constant.paymentCollectionPlanStatus
          }
        } else {
          // 保证金-是-状态下拉框增加抵扣中、抵扣完成
          if (amountType === 'margin') {
            return this.constant.paymentCollectionPlanStatus
          } else {
            return filterListData(this.constant.paymentCollectionPlanStatus, ['pay_coll_plan_deduction', 'pay_coll_plan_deduction_completed'])
          }
        }
      }
    }
  },
  watch: {
    financingPlan: {
      handler(newV) {
        if (Object.keys(newV).length) {
          const financingPlan = JSON.parse(JSON.stringify(newV))
          this.tableData = financingPlan.planFactoringList.map(item => {
            item.amountType = item.amountType.id
            item.status = item.status.name
            item.currencyTypeCode = item.currencyType.code
            return item
          })
          const { irr, contractIrr, quotaIrr, occupationFlag, reportDataFlag, basicId, origDbtCate, initRpySts } = financingPlan
          this.ruleForm = {
            irr: ((irr * 10000) / 100).toFixed(2),
            contractIrr: (contractIrr * 10000) / 100,
            quotaIrr: (quotaIrr * 10000) / 100,
            occupationFlag,
            reportDataFlag,
            basicId,
            origDbtCate,
            initRpySts
          }
        }
      },
      immediate: true,
      deep: true
    },
    tableData: {
      handler(newV) {
        this.isMoneyAdvanced = this.tableData.some(item => {
          const amountType = codeChangeName(this.constant.incormeExpenditureType, item.amountType, 'id', 'code')
          return amountType === 'money_advanced'
        })
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.$store.dispatch('getConstant', ['incormeExpenditureType', 'payCollType'])
    // this.$store.dispatch('getConstant', ['incormeExpenditureType', 'payCollType', 'receivingSubjectList', 'paymentCollectionPlanStatus', 'graceTypeList', 'quotaDisburseDebtType', 'quotaDisburseTransferStatus'])
  },
  methods: {
    modifyClick(type, index) {
      if (type === 'add') {
        // 新增默认状态为计划种
        // const statusId = this.$utils.codeChangeName(this.constant.paymentCollectionPlanStatus, 'pay_coll_planning', 'code', 'id')
        const obj = {
          planDate: '',
          amountType: '',
          paymentCollectionType: 'pay_coll_collection',
          amount: '',
          actualCashFlow: '',
          receivingSubject: 'debtor',
          overDate: '',
          graceType: 0,
          status: 'pay_coll_planning',
          allowedChange: true,
          allowedDelete: true,
          id: null,
          currencyType: this.tableData[0].currencyType,
          currencyTypeCode: this.tableData[0].currencyType.code,
          collRecordList: [],
          loanRecordList: []
        }
        this.tableData.splice(index + 1, 0, obj)
      } else if (type === 'delete') {
        this.tableData.splice(index, 1)
        this.getIrrCalc()
      }
    },
    amountChange(row, index) {
      if (row.paymentCollectionType === 'pay_coll_payment') {
        if (Number(row.amount) < 0) {
          this.tableData[index].actualCashFlow = Math.abs(Number(row.amount))
        } else {
          this.tableData[index].actualCashFlow = -Number(row.amount)
        }
      } else {
        this.tableData[index].actualCashFlow = row.amount
      }
      this.getIrrCalc()
      // this.getMoneyAdvanced()
    },
    // 是否包含垫付
    getMoneyAdvanced() {
      this.isMoneyAdvanced = this.tableData.some(item => {
        const amountType = codeChangeName(this.constant.incormeExpenditureType, item.amountType, 'id', 'code')
        return amountType === 'money_advanced'
      })
    },
    // 金额类型发生变化
    amountCollectionTypeChange(row) {
      const { index, amountType, paymentCollectionType, rowData } = row
      const amountTypeCode = codeChangeName(this.constant.incormeExpenditureType, amountType, 'id', 'code')
      if (amountTypeCode === 'margin' && paymentCollectionType === 'pay_coll_payment') {
        this.tableData[index].receivingSubject = ''
      } else {
        this.tableData[index].receivingSubject = 'debtor'
      }
      this.amountChange(rowData, index)
    },
    async getIrrCalc() {
      for (let i = 0; i < this.tableData.length; i++) {
        const { planDate, amount } = this.tableData[i]
        if (!planDate) {
          this.$message.warning(`请选择第${i + 1}条的约定日期`)
          return
        }
        if (!amount) {
          this.$message.warning(`请输入第${i + 1}条的金额`)
          return
        }
      }
      const params = this.tableData.map(item => {
        const obj = {
          planDate: item.planDate,
          actualCashFlow: item.actualCashFlow,
          amountType: {
            id: item.amountType
          },
          paymentCollectionType: item.paymentCollectionType
        }
        if (item.paymentCollectionType === 'pay_coll_payment') {
          obj.loanRecordList = item.loanRecordList.map(item => {
            return {
              thisLoanAmount: item.thisLoanAmount,
              thisLoanDate: item.thisLoanDate
            }
          })
        } else {
          obj.collRecordList = item.collRecordList.map(item => {
            return {
              actualAmount: item.actualAmount,
              actualDate: item.actualDate
            }
          })
        }
        return obj
      })
      this.$api.customManage.collectionLoanManage.getIrrCalc(params).then((data) => {
        this.ruleForm.irr = (data.data * 100).toFixed(2)
        Promise.resolve()
      })
    },
    handleSelectionChange(val) {
      this.$emit('financing-funds', val)
      this.$nextTick(() => {
        this.tableData.forEach(row => {
          row.tradePlanFactoringList.forEach(data => {
            data.planFactoringList.forEach(list => {
              if (val.some(item => item.id === list.id)) {
                this.$refs.tradePlanFactoring.toggleRowSelection(val)
              }
            })
          })
        })
      })
    },
    async getFinancingCalc() {
      const receivableList = []
      this.$emit('get-accounts-receivable', (data) => {
        data.forEach(item => {
          item.tradePlanFactoringList.forEach(tradeItem => {
            tradeItem.planFactoringList.forEach(planItem => {
              receivableList.push({
                ...planItem,
                underlyingAccountReceivableId: item.underlyingAccountReceivableId,
                billingFactoringBusinessLoanRecordId: tradeItem.billingFactoringBusinessLoanRecordId
              })
            })
          })
        })
      })
      for (let i = 0; i < receivableList.length; i++) {
        const { planDate, amountType, amount, status, paymentCollectionType, receivingSubject } = receivableList[i]
        if (!planDate) {
          this.$message.warning('请选择约定日期')
          return
        }
        if (!amountType) {
          this.$message.warning('请选择金额类型')
          return
        }
        if (!amount) {
          this.$message.warning('请输入金额')
          return
        }
        if (paymentCollectionType === 'pay_coll_collection' && !receivingSubject) {
          this.$message.warning('请选择收款主体')
          return
        }
        if (!status) {
          this.$message.warning('请选择状态')
          return
        }
      }
      const paramsList = receivableList.map(item => {
        const { planDate, amountType, paymentCollectionType, amount, actualCashFlow, receivingSubject, actualId, status, id, contractIncomeExpenditurePlanId, currencyType, graceType, allowedChange, allowedDelete, underlyingAccountReceivableId, billingFactoringBusinessLoanRecordId } = item
        const obj = {
          planDate: parseTime(new Date(planDate), 'y-m-d'),
          amountType: {
            id: amountType
          },
          paymentCollectionType,
          amount,
          actualCashFlow,
          receivingSubject,
          status: {
            code: status
          },
          actualId: actualId || id,
          id,
          contractIncomeExpenditurePlanId,
          basic: {
            id: this.ruleForm.basicId
          },
          currencyType: {
            id: currencyType.id
          },
          graceType,
          allowedChange,
          allowedDelete,
          underlyingAccountReceivableId,
          billingFactoringBusinessLoanRecordId
        }
        return obj
      })
      this.loading = true
      const { data } = await this.$api.customManage.collectionLoanManage.changePlanOneCalc(paramsList)
      this.loading = false
      this.tableData = data.map(item => {
        item.amountType = item.amountType.id
        item.status = item.status.code
        item.currencyTypeCode = item.currencyType.code
        return item
      })
      await this.getIrrCalc()
    },
    selectable(row, index) {
      if (row.oaSelect === 0) {
        return false
      } else {
        return true
      }
    }
  }
}
</script>

<style scoped>
.financing-plan .info-title {
  display: flex;
  justify-content: space-between;
}
</style>
