<template>
  <div class="financing-info">
    <cy-info-title>融资信息</cy-info-title>
    <el-form ref="ruleForm" :key="ruleFormKey" :model="ruleForm" :rules="rules" label-position="top" class="rule-form-orange">
      <el-form-item label="融资金额" prop="financingAmount">
        <cy-amount-input v-model="ruleForm.financingAmount" :disabled="disabled" placeholder="请输入融资金额" :clearable="false" />
      </el-form-item>
      <el-form-item label="币种" prop="currencyCode">
        <el-select
          v-model="ruleForm.currencyCode"
          placeholder="请选择币种"
          clearable
          :disabled="disabled"
        >
          <el-option
            v-for="item in constant.currencyType"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="融资比例" prop="financingRatio">
        <el-input v-model="ruleForm.financingRatio" disabled placeholder="请输入融资比例" clearable>
          <template slot="append">%</template>
        </el-input>
      </el-form-item>
      <el-form-item label="融资期限" prop="financingPeriod">
        <el-input v-model="ruleForm.financingPeriod" :disabled="ruleForm.repaymentAdjustment === 'fixed_repayment_date' || disabled" placeholder="请输入融资期限" clearable />
      </el-form-item>
      <el-form-item label="是否占用公司资金" prop="occupation">
        <el-radio-group v-model="ruleForm.occupation" :disabled="disabled">
          <el-radio :label="1">占用</el-radio>
          <el-radio :label="0">不占用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否公司承险" prop="risk">
        <el-radio-group v-model="ruleForm.risk" :disabled="disabled">
          <el-radio :label="1">公司承险</el-radio>
          <el-radio :label="0">公司不承险</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="出资方" prop="institutionName">
        <el-select
          v-model="ruleForm.institutionName"
          placeholder="请选择出资方"
          :disabled="disabled"
          @change="getBusinessTypeInfo"
        >
          <el-option
            v-for="item in institutionNameList"
            :key="item.institutionName"
            :label="item.institutionName"
            :value="item.institutionName"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="业务类型" prop="businessType">
        <el-select
          v-model="ruleForm.businessType"
          placeholder="请选择业务类型"
          :disabled="disabled"
          @change="getCardInfo"
        >
          <el-option
            v-for="item in businessTypeInfo"
            :key="item.businessTypeDic.id"
            :label="item.businessTypeDic.name"
            :value="item.businessTypeDic.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <template v-if="ruleForm.institutionName !== '长银集团自有资金'">
        <el-form-item label="账号名称" prop="accountName">
          <el-select
            v-model="ruleForm.accountName"
            placeholder="请选择账号名称"
            :disabled="disabled"
          >
            <el-option
              v-for="item in bankCard"
              :key="item.accountName"
              :label="item.accountName"
              :value="item.accountName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支用到期日" prop="disburseExpiryDate">
          <el-select
            v-model="ruleForm.disburseExpiryDate"
            placeholder="请选择支用到期日"
            :disabled="disabled"
            clearable
          >
            <el-option
              v-for="item in disburseExpiryDate"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </template>
      <el-form-item label="起算日" prop="startingDateType">
        <el-radio-group v-model="ruleForm.startingDateType" :disabled="disabled">
          <el-radio label="plan_day">自保理融资款实际投放之日</el-radio>
          <el-radio label="clear_day">明确日期</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="ruleForm.startingDateType === 'plan_day'"
        label="预计投放日"
        prop="startingDate"

        :rules="[
          { required: true, message: '请选择预计投放日', trigger: 'blur'},
        ]"
      >
        <el-date-picker
          v-model="ruleForm.startingDate"
          type="date"
          :disabled="disabled"
          placeholder="请选择预计投放日"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item
        v-if="ruleForm.startingDateType === 'clear_day'"
        label="具体日期"
        prop="startingDate"
        :rules="[
          { required: true, message: '请选择具体日期', trigger: 'blur'},
        ]"
      >
        <el-date-picker
          v-model="ruleForm.startingDate"
          :disabled="disabled"
          type="date"
          placeholder="请选择具体日期"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="利息是否计算投放日" prop="interestCalculate">
        <el-radio-group v-model="ruleForm.interestCalculate" :disabled="disabled">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="还款期限调整方式" prop="repaymentAdjustment" class="two-form-item">
        <el-radio-group v-model="ruleForm.repaymentAdjustment" :disabled="disabled">
          <el-radio v-for="(item, index) in constant.repaymentAdjustment" :key="index" :label="item.code">{{ item.name }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="还款方式" prop="payBackMethod" style="width: 100%">
        <el-radio-group v-model="ruleForm.payBackMethod" :disabled="disabled">
          <el-radio v-for="(item, index) in constant.paymentMethodForInterestManagementFee" :key="index" :label="item.code">{{ item.name }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="融资利率（年化）" prop="financingRate">
        <el-input v-model="ruleForm.financingRate" :disabled="disabled" placeholder="请输入融资利率（年化）" clearable>
          <template slot="append">%</template>
        </el-input>
      </el-form-item>
      <el-form-item label="融资利息" prop="financingInterest">
        <el-input v-model="ruleForm.financingInterest" disabled placeholder="请输入融资利息" clearable />
      </el-form-item>
      <el-form-item label="管理费率（年化）" prop="managementFeeRatio">
        <el-input v-model="ruleForm.managementFeeRatio" :disabled="disabled" placeholder="请输入管理费率（年化）" clearable>
          <template slot="append">%</template>
        </el-input>
      </el-form-item>
      <el-form-item label="管理费金额" prop="managementFeeAmount">
        <el-input v-model="ruleForm.managementFeeAmount" disabled placeholder="请输入管理费金额" clearable />
      </el-form-item>
      <el-form-item label="保证金比例" prop="marginRatio">
        <el-input v-model="ruleForm.marginRatio" :disabled="disabled" placeholder="请输入保证金比例" clearable>
          <template slot="append">%</template>
        </el-input>
      </el-form-item>
      <el-form-item label="保证金金额" prop="marginAmount">
        <el-input v-model="ruleForm.marginAmount" disabled placeholder="请输入保证金金额" clearable />
      </el-form-item>
      <el-form-item label="其他费用金额" prop="otherFeeAmount">
        <el-input v-model="ruleForm.otherFeeAmount" :disabled="disabled" placeholder="请输入其他费用金额" clearable />
      </el-form-item>
      <el-form-item label="对外综合报价" prop="comprehensiveQuotation">
        <el-input v-model="ruleForm.comprehensiveQuotation" :disabled="disabled" placeholder="请输入其对外综合报价" clearable>
          <template slot="append">%</template>
        </el-input>
      </el-form-item>
      <el-form-item label="回款方式" prop="repaymentMethod">
        <el-radio-group v-model="ruleForm.repaymentMethod" :disabled="disabled">
          <el-radio v-for="(item, index) in constant.repaymentMethod" :key="index" :label="item.code">{{ item.name }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="逾期利率" prop="overdueInterestRate">
        <el-input v-model="ruleForm.overdueInterestRate" :disabled="disabled" placeholder="请输入逾期利率" clearable>
          <template slot="append">%</template>
        </el-input>
      </el-form-item>
      <el-form-item label="转让通知方式" prop="transferNoticeMethodList" style="width: 100%">
        <el-checkbox-group v-model="ruleForm.transferNoticeMethodList" :disabled="disabled">
          <el-checkbox v-for="(item, index) in constant.transferNoticeMethod" :key="index" :label="item.code" name="transferNoticeMethodList">{{ item.name }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="服务范围" prop="serviceScopeList" style="width: 100%">
        <el-checkbox-group v-model="ruleForm.serviceScopeList" :disabled="disabled">
          <el-checkbox v-for="(item, index) in constant.serviceScope" :key="index" :label="item.code" name="serviceScopeList">{{ item.name }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getInstitutionName } from '@/api/financialManagement/financialManagement'
import { getBusinessTypeByManagement, getBankCard, getExpiration } from '@/api/financingManage'
import { startAndEndValue } from '@/utils'
export default {
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    detailsInfo: {
      type: Object,
      default: () => {}
    },
    endDate: {
      type: String,
      default: ''
    },
    accountsReceivableNetAmountTotal: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      ruleFormKey: 0,
      ruleForm: {
        transferNoticeMethodList: [],
        serviceScopeList: []
      },
      rules: {
        financingAmount: [
          { required: true, message: '请输入融资金额', trigger: 'blur' }
        ],
        currencyCode: [
          { required: true, message: '请输入币种', trigger: 'blur' }
        ],
        financingRatio: [
          { required: true, message: '请输入融资比例', trigger: 'blur' }
        ],
        financingPeriod: [
          { required: true, message: '请输入融资期限', trigger: 'blur' }
        ],
        occupation: [
          { required: true, message: '请选择是否占用公司资金', trigger: 'change' }
        ],
        risk: [
          { required: true, message: '请选择是否公司承险', trigger: 'change' }
        ],
        institutionName: [
          { required: true, message: '请选择出资方', trigger: 'change' }
        ],
        businessType: [
          { required: true, message: '请选择业务类型', trigger: 'change' }
        ],
        accountName: [
          { required: true, message: '请输入账号名称', trigger: 'blur' }
        ],
        // disburseExpiryDate: [
        //   { required: true, message: '请选择支用到期日', trigger: 'change' }
        // ],
        startingDateType: [
          { required: true, message: '请选择起算日', trigger: 'change' }
        ],
        interestCalculate: [
          { required: true, message: '请选择利息是否计算投放日', trigger: 'change' }
        ],
        repaymentAdjustment: [
          { required: true, message: '请选择还款期限调整方式', trigger: 'change' }
        ],
        payBackMethod: [
          { required: true, message: '请选择还款方式', trigger: 'change' }
        ],
        financingRate: [
          { required: true, message: '请选择融资利率（年化）', trigger: 'change' }
        ],
        financingInterest: [
          { required: true, message: '请选择融资利息', trigger: 'change' }
        ],
        managementFeeRatio: [
          { required: true, message: '请选择管理费率（年化）', trigger: 'change' }
        ],
        managementFeeAmount: [
          { required: true, message: '请输入管理费金额', trigger: 'blur' }
        ],
        marginRatio: [
          { required: true, message: '请输入保证金比例', trigger: 'blur' }
        ],
        marginAmount: [
          { required: true, message: '请输入保证金金额', trigger: 'blur' }
        ],
        otherFeeAmount: [
          { required: true, message: '请输入其他费用金额', trigger: 'blur' }
        ],
        comprehensiveQuotation: [
          { required: true, message: '请输入对外综合报价', trigger: 'blur' }
        ],
        repaymentMethod: [
          { required: true, message: '请输入回款方式', trigger: 'blur' }
        ],
        overdueInterestRate: [
          { required: true, message: '请输入逾期利率', trigger: 'blur' }
        ],
        transferNoticeMethodList: [
          { required: true, message: '请输入转让通知方式', trigger: 'blur' }
        ],
        serviceScopeList: [
          { required: true, message: '请输入服务范围', trigger: 'blur' }
        ]
      },
      institutionNameList: [],
      businessTypeInfo: [
        {
          businessTypeDic: {}
        }
      ],
      bankCard: [],
      disburseExpiryDate: []
    }
  },
  computed: {
    ...mapGetters(['constant']),
    refinancingManagement() {
      return this.institutionNameList.find(item => item.institutionName === this.ruleForm.institutionName)
    },
    businessInfo() {
      return this.businessTypeInfo.find(item => item.businessTypeDic.id === this.ruleForm.businessType)
    }
  },
  watch: {
    detailsInfo: {
      handler(newV) {
        if (newV && Object.keys(newV).length) {
          const { transferNoticeMethodList, serviceScopeList } = JSON.parse(JSON.stringify(newV))
          this.$set(this, 'ruleForm', {
            ...JSON.parse(JSON.stringify(newV)),
            transferNoticeMethodList: transferNoticeMethodList || [],
            serviceScopeList: serviceScopeList || []
          })
          this.ruleFormKey += 1
          setTimeout(() => {
            this.getBusinessTypeInfoData()
          }, 300)
        }
      },
      immediate: true,
      deep: true
    },
    'ruleForm.financingAmount'() {
      this.calcFinancingInterest()
      this.calcManagementFee()
      this.calcMarginAmount()
      this.calcFinancingRatio()
    },
    'ruleForm.financingRate'() {
      this.calcFinancingInterest()
      this.calcManagementFee()
      // this.calcMarginAmount()
    },
    'ruleForm.financingPeriod'() {
      this.calcFinancingInterest()
      this.calcManagementFee()
      // this.calcMarginAmount()
    },
    'ruleForm.managementFeeRatio'() {
      this.calcManagementFee()
    },
    'ruleForm.marginRatio'() {
      this.calcMarginAmount()
    },
    'ruleForm.startingDate'() {
      this.calcFinancingTerm()
    },
    'ruleForm.interestCalculate'() {
      this.calcFinancingTerm()
    },
    'ruleForm.repaymentAdjustment'() {
      this.calcFinancingTerm()
    }
  },
  created() {
    this.$store.dispatch('getConstant', ['repaymentMethod', 'transferNoticeMethod', 'serviceScope', 'repaymentAdjustment', 'paymentMethodForInterestManagementFee', 'currencyType'])
    this.getContributor()
  },
  methods: {
    // 计算融资比例
    calcFinancingRatio() {
      const { financingAmount } = this.ruleForm
      if (financingAmount) {
        this.ruleForm.financingRatio = (Number(financingAmount) / Number(this.accountsReceivableNetAmountTotal) * 100).toFixed(2)
      }
    },
    // 计算融资利息
    calcFinancingInterest() {
      const { financingAmount, financingRate, financingPeriod } = this.ruleForm
      if (financingAmount && financingRate && financingPeriod) {
        this.ruleForm.financingInterest = (financingAmount * financingRate / 100 * financingPeriod / 360).toFixed(2)
      }
    },
    // 计算管理费金额
    calcManagementFee() {
      const { financingAmount, financingPeriod, managementFeeRatio } = this.ruleForm
      if (financingAmount && financingPeriod && managementFeeRatio) {
        this.ruleForm.managementFeeAmount = (financingAmount * managementFeeRatio / 100 * financingPeriod / 360).toFixed(2)
      }
    },
    // 计算保证金金额
    calcMarginAmount() {
      const { financingAmount, marginRatio } = this.ruleForm
      if (financingAmount && marginRatio) {
        this.ruleForm.marginAmount = (financingAmount * marginRatio / 100).toFixed(2)
      }
    },
    // 计算融资期限
    calcFinancingTerm() {
      const { repaymentAdjustment, startingDate, interestCalculate } = this.ruleForm
      if (repaymentAdjustment === 'fixed_repayment_date') {
        if (interestCalculate) {
          this.ruleForm.financingPeriod = startAndEndValue(startingDate, this.endDate)
        } else {
          this.ruleForm.financingPeriod = startAndEndValue(startingDate, this.endDate) - 1
        }
      }
    },
    getContributor() {
      getInstitutionName().then(({ data }) => {
        this.institutionNameList = data.data
      })
    },
    getBusinessTypeInfoData() {
      getBusinessTypeByManagement({ refinancingManagementId: this.refinancingManagement.id }).then(({ data }) => {
        this.businessTypeInfo = data.data
      })
    },
    getBusinessTypeInfo() {
      this.ruleForm.businessType = ''
      this.ruleForm.accountName = ''
      this.ruleForm.disburseExpiryDate = ''
      this.ruleFormKey += 1
      this.getBusinessTypeInfoData()
    },
    getCardInfo() {
      this.ruleForm.accountName = ''
      this.ruleForm.disburseExpiryDate = ''
      this.ruleFormKey += 1
      const params = {
        refinancingManagementId: this.refinancingManagement.id,
        businessType: this.businessInfo.businessTypeDic.id,
        businessNumber: this.businessInfo.businessNumberDic.id
      }
      getBankCard(params).then(({ data }) => {
        this.bankCard = data
      })
      this.getExpirationList(params)
    },
    getExpirationList(params) {
      if (this.ruleForm.institutionName === '长银集团自有资金') return
      getExpiration(params).then(({ data }) => {
        this.disburseExpiryDate = data
      })
    },

    getParams(type) {
      return new Promise((resolve, reject) => {
        if (type === 'temp') {
          resolve(this.ruleForm)
        } else {
          this.$refs.ruleForm.validate(valid => {
            if (valid) {
              resolve(this.ruleForm)
            } else {
              reject()
              return false
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
