<template>
  <!-- 自有资金放款信息编辑 -->
  <div>
    <dialog-edit width="95%" :visible.sync="dialogVisible" :form="forms" :closeLabel="$t('common.cancel')" :saveLabel="$t('common.confirm')" :formRules="formRules" :autoSave="autoSave" :editModel="editModel"
      :api="api" :appendToBody="appendToBody" :title="editModel === 'C' ? $t('selfPayLoan.addTitle') : $t('selfPayLoan.editTitle')"
      @onSaved="handleSubmit">
      <div class="selfPayAddModPop" v-loading="assetpkgmgrButtonLoading">
        <!-- 基础信息 -->
        <dym-form :formValue.sync="forms" :componentList="componentList" @otherData="handleClick" @checkChange="checkChange"></dym-form>
        <!-- 设置资金来源表格 -->
        <data-table :operateBtnLayout="operateBtnLayout" v-bind="{maxHeight:400}" selectable="false" :queryParas="queryParas"
          :sourceData="modifyData" :toolMenuFlag="toolMenuFlag" :columns="modifyColumns" :showPage="false"
          :loadCount.sync="loadCount" :menuFlag="menuFlag"
          :loadingFlag="loadingFlag">
          <template slot="headButton">
            <div align="left">
              <!-- <span style="color: #ff3333;margin-right: 6px;">*</span> -->
              <auth-button :size="'medium'" icon="iconfont iconpiliangshezhichanpinxinxi" :label="$t('selfPayLoan.setBtn')" @click="handleSet" type="primary"></auth-button>
            </div>
          </template>
          <template slot="paginationLeft">
            <div align="left">
              <div>{{$t('common.pagePromptOne') + modifyData.length + $t('common.pagePromptTwo') + modifyData.length + $t('common.pagePromptThree')}}</div>
              <div style="width: 33.3%;margin-top: 10px;">
                <el-form-item label-width="125px" :label="$t('selfPayLoan.loanAmountTotal')">
                  <el-input v-model="totalPrice" disabled></el-input>
                </el-form-item>
              </div>
            </div>
          </template>
          <el-table-column align="center" min-width="150px" :label="$t('common.operate')" fixed="right">
            <template slot-scope="scope">
              <auth-button class="iconCircle" icon="iconfont iconbianji" :title="$t('common.edit')" @click="checkInfo(0,scope)"></auth-button>
              <auth-button class="iconCircle iconCircleDel" icon="iconfont iconycjian" :title="$t('common.delete')" @click="checkInfo(1,scope)"></auth-button>
            </template>
          </el-table-column>
        </data-table>
      </div>
    </dialog-edit>
    <!-- 资金来源 -->
    <funds-provide-pop v-if="isSet" :visible.sync="isSet" :editModel="editType" :form="form" :currentRow="chooseRow" @onSaved="saveItem" :tagId="tagId"></funds-provide-pop>
  </div>
</template>

<script>
import BaseEdit from '@/pages/baseEditPage'
import * as format from '@/filters/index.js'
import {
  DialogEdit,
  DataTable,
  authButton,
  validate,
  amountInput,
  dymForm
} from 'newepoch-components'
import formBandButton from '@/components/element/assetpkgmgr/formBandButton.vue' // 自定义表单
import fundsProvidePop from './fundsProvidePop' // 资金来源
import selfPayLoan from '@/api/assetpkgmgr/selfPayLoanApi.js'
import externalApi from '@/api/assetpkgmgr/externalApi'

export default {
  extends: new BaseEdit(),
  name: 'selfPayAddModPop',
  components: {
    DialogEdit,
    DataTable,
    authButton,
    fundsProvidePop,
    amountInput,
    dymForm
  },
  props: {
    autoSave: {
      type: [Boolean],
      default: true
    },
    currentRow: {
      type: [Object],
      default () {
        return null
      }
    }
  },
  data () {
    // 费率表单校验
    let checkPercent = (rule, value, callback) => {
      let num = parseFloat(value)
      // 费率必须在0到100之间
      if (num >= 100 || num < 0) {
        callback(new Error(this.$t('bankPrice.feeRange')))
      } else {
        callback()
      }
    }
    return {
      showPage: false, // 是否分页
      chooseIndex: '', // 选中项索引值
      appendToBody: true,
      tagId: '', // 核心企业id
      toolMenuFlag: true,
      isSet: false,
      loadCount: 0,
      menuFlag: false,
      chooseRow: {},
      operateBtnLayout: '',
      loadingFlag: false, // 加载动画控件
      queryParas: {},
      modifyData: [], // 资金来源列表
      contactData: [],
      editType: 'C',
      forms: {},
      // 基本信息表单验证
      formRules: {
        assetCode: [{
          required: true,
          validator: validate.payNumValidate,
          trigger: 'blur'
        }, {
          required: true,
          message: this.$t('selfPayLoan.assetCodePrompt'),
          trigger: 'blur'
        }],
        loanDateFactoring: [{
          required: true,
          message: this.$t('selfPayLoan.timePrompt'),
          trigger: 'blur'
        }],
        feeRateDate: [{
          validator: checkPercent,
          trigger: 'blur'
        }],
        feeRate: [{
          validator: checkPercent,
          trigger: 'blur'
        }]
      },
      componentList: [
        {
        // 付款确认书编号
          label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.payCode,
          disabled: false,
          value: 'assetCode',
          prop: 'assetCode',
          // placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
          labelWidth: '200px',
          cols: [12, 12, 12, 8],
          clearable: true,
          btnDisplay: true,
          componentName: formBandButton
        },
        {
        // 供应商名称
          label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.creditor,
          disabled: true,
          value: 'creditor',
          prop: 'creditor',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.noForm,
          labelWidth: '200px',
          cols: [12, 12, 12, 8],
          clearable: true,
          componentName: 'el-input'
        },
        {
        // 核心企业
          label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.coreEnterpriseName,
          disabled: true,
          value: 'coreEnterpriseName',
          prop: 'coreEnterpriseName',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.noForm,
          labelWidth: '200px',
          cols: [12, 12, 12, 8],
          clearable: true,
          componentName: 'el-input'
        },
        {
        // 再保理银行
          label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.planOrBankName,
          disabled: true,
          value: 'planOrBankName',
          prop: 'planOrBankName',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.noForm,
          labelWidth: '200px',
          cols: [12, 12, 12, 8],
          clearable: true,
          componentName: 'el-input'
        },
        {
        // 原始权益人
          label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.initialOwnersName,
          disabled: true,
          value: 'initialOwnersName',
          prop: 'initialOwnersName',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.noForm,
          labelWidth: '200px',
          cols: [12, 12, 12, 8],
          clearable: true,
          componentName: 'el-input'
        },
        {
        // 应收账款金额
          label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.factoringMoney,
          disabled: true,
          value: 'factoringMoney',
          prop: 'factoringMoney',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.noForm,
          labelWidth: '200px',
          cols: [12, 12, 12, 8],
          clearable: true,
          componentName: 'el-input'
        },
        {
        // 费率
          label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.factoringRate,
          disabled: true,
          value: 'factoringRate',
          prop: 'factoringRate',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.noForm,
          labelWidth: '200px',
          cols: [12, 12, 12, 8],
          clearable: true,
          precision: '%',
          componentName: formBandButton
        },
        {
        // 放款时间
          label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.loanDateFactoring,
          disabled: false,
          value: 'loanDateFactoring',
          prop: 'loanDateFactoring',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect,
          labelWidth: '200px',
          cols: [12, 12, 12, 8],
          clearable: true,
          // pickerOptions: {
          //   disabledDate: function () {
          //     return true
          //   }
          // },
          componentName: 'el-date-picker'
        },
        {
        // 手续费费率(需要日期加权)
          label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.feeRateDate,
          disabled: false,
          value: 'feeRateDate',
          prop: 'feeRateDate',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
          labelWidth: '200px',
          cols: [12, 12, 12, 8],
          clearable: true,
          precision: '%',
          componentName: formBandButton
        },
        {
        // 手续费费率(不需要日期加权)
          label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.feeRate,
          disabled: false,
          value: 'feeRate',
          prop: 'feeRate',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
          labelWidth: '200px',
          cols: [12, 12, 12, 8],
          precision: '%',
          clearable: true,
          componentName: formBandButton
        },
        {
        // 手续费
          label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.fee,
          disabled: true,
          value: 'fee',
          prop: 'fee',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.noForm,
          labelWidth: '200px',
          cols: [12, 12, 12, 8],
          clearable: true,
          componentName: 'el-input'
        },
        {
        // 放款量
          label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.loanAmountFactoring,
          disabled: true,
          value: 'loanAmountFactoring',
          prop: 'loanAmountFactoring',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.noForm,
          labelWidth: '200px',
          cols: [12, 12, 12, 8],
          clearable: true,
          componentName: 'el-input',
          format: (row) => {
            return format.thousandFilter(row.loanAmountFactoring)
          }
        }
      ],
      modifyColumns: [
        // 资金来源
        {
          prop: 'fundsProvideName',
          headerAlign: 'center',
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.ownerName,
          width: '150px'
        },
        // 可用额度（元）
        {
          prop: 'approvalLimit',
          headerAlign: 'center',
          align: 'right',
          label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.restLimit,
          width: '150px',
          format: (row) => {
            return format.thousandFilter(row.approvalLimit)
          }
        },
        // 放款金额（元）
        {
          prop: 'loanAmountFactoring',
          headerAlign: 'center',
          align: 'right',
          label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.loanAmount,
          width: '150px',
          format: (row) => {
            return format.thousandFilter(row.loanAmount)
          }
        }
      ],
      addData: [],
      modData: [],
      delData: [],
      number: 0 // 初次打开时，手续费和放款金额不计算，大于1时才计算手续费和放款金额
    }
  },
  computed: {
    // 创建新资产包
    api () {
      return selfPayLoan.selfPayLoan
    },
    // 放款金额合计
    totalPrice () {
      let modifyData = this.modifyData // 选中项
      let totalPrice = modifyData.length > 0 ? modifyData
        .map(item => {
          return Number(item.loanAmount)
        })
        .reduce((total, num) => {
          return total + num
        })
        : 0
      return totalPrice.toFixed(2)
    },
    // 监听表单对象
    FormList () {
      const {
        factoringMoney,
        loanDateFactoring,
        feeRate,
        feeRateDate
      } = this.forms
      return {
        factoringMoney,
        loanDateFactoring,
        feeRate,
        feeRateDate
      }
    }
  },
  methods: {
    // 处理日期选择范围
    checkChange (e, t) {
      let dueDate = this.forms.dueDate
      console.log(this.forms)
      if (dueDate) {
        this.componentList[7].pickerOptions = {
          disabledDate: function (time) {
            return time.getTime() > dueDate
          }
        }
      } else {
        this.componentList[7].pickerOptions = {
          disabledDate: function () {
            return true
          }
        }
      }
    },
    // 新增和编辑资金来源列表
    saveItem (e, n) {
      if (this.editType === 'C') {
        for (let index in this.modifyData) {
          let item = this.modifyData[index]
          if (e.fundsProvideCode === item.fundsProvideCode) {
            this.warning(this.$t('selfPayLoan.fundsProvidePrompt'))
            return false
          }
        }
        this.success(this.$t('common.addSuccess'))
        this.modifyData.unshift(e)
        if (this.editModel === 'E') {
          this.addData.push(e)
        }
      } else {
        for (let index in this.modifyData) {
          let item = this.modifyData[index]
          if (e.fundsProvideCode === item.fundsProvideCode && e.fundsProvideCode !== n) {
            this.warning(this.$t('selfPayLoan.fundsProvidePrompt'))
            return false
          }
        }
        this.success(this.$t('common.updateSuccess'))
        // console.log(this.chooseIndex)
        this.modifyData.splice(this.chooseIndex, 1, e)
        if (this.editModel === 'E') {
          // 若编辑项是已存在项
          if (e.keyId) {
            for (let index in this.modData) {
              let item = this.modData[index]
              if (e.keyId === item.keyId) {
                item = e
                return false
              }
            }
            this.modData.push(e)
          // 若编辑项是新增项
          } else {
            this.addData = this.addData.map(item => {
              return e.fundsProvideCode === item.fundsProvideCode ? e : item
            })
          }
        }
      }
    },
    // 设置资金来源
    handleSet () {
      if (this.tagId) {
        this.isSet = true
        this.editType = 'C'
      } else {
        this.warning(this.$t('selfPayLoan.initialOwnersPrompt'))
      }
    },
    // 操作表格
    checkInfo (type, params) {
      let that = this
      if (type === 0) {
        // console.log(that.tagId)
        that.editType = 'E'
        that.chooseIndex = params.$index
        that.chooseRow = params.row
        that.isSet = true
      } else {
        that.$confirm(that.$t('common.confirm') + that.$t('common.delete') + '？', that.$t('common.tip'), {
          type: 'warning'
        }).then(() => {
          that.success(that.$t('common.delSuccess'))
          that.modifyData.splice(params.$index, 1)
          if (that.editModel === 'E') {
            that.delData.push(params.row.keyId)
            // console.log(that.delData)
          }
        }).catch((e) => {})
      }
    },
    // 重置表单
    clearParam () {
      this.queryParas = {}
    },
    // 付款确认书检测
    handleClick () {
      let that = this
      let assetCode = that.forms.assetCode
      if (assetCode) {
        that.assetpkgmgrButtonLoading = true
        that.api.checkAssetCode(assetCode).then(res => {
          that.assetpkgmgrButtonLoading = false
          if (res.success) {
            that.success(that.$t('selfPayLoan.checkPrompt'))
            let forms = that.UtilJs.cloneDeep(that.forms)
            forms.loanDateFactoring = that.forms.loanDateFactoring
            this.tagId = res.data.coreEnterpriseId
            that.forms = Object.assign(forms, res.data)
            that.forms.factoringRate = (res.data.factoringRate * 100).toFixed(2)
            that.checkChange()
          } else {
            that.error(res.message)
          }
        }).catch(res => {
          that.assetpkgmgrButtonLoading = false
        })
      } else {
        that.warning(that.$t('selfPayLoan.assetCodePrompt'))
      }
    },
    // 提交表单
    handleSubmit (e) {
      // console.log(this.addData, this.delData, this.modData)
      let loanAmountFactoring = Number(e.loanAmountFactoring).toFixed(2)
      let totalPrice = Number(this.totalPrice).toFixed(2)
      if (!e.fee) {
        this.warning(this.$t('selfPayLoan.feeTotalPrompt'))
        return
      }
      // 资金来源放款总金额和计算放款金额是否一致
      if (loanAmountFactoring === totalPrice) {
        if (this.editModel === 'C') {
          e.datas = this.modifyData
        } else {
          e.keyId = this.currentRow.keyId
          e.mod = this.modifyData
          // e.add = this.addData
          // e.del = this.delData
          // e.mod = this.modData
        }
        // 检测的字段名和本地字段名有差异，此处做转换处理，后期可能改表，此处理可删除
        let form = this.UtilJs.cloneDeep(e)
        form.loanDateFactoring = e.loanDateFactoring.getTime().toString()
        form.feeRateDate = e.feeRateDate ? (e.feeRateDate / 100).toString() : ''
        form.feeRate = e.feeRate ? (e.feeRate / 100).toString() : ''
        form.factoringRate = (e.factoringRate / 100).toString()
        form.factorBankId = e.planOrBankId
        delete form.planOrBankId
        form.factorBankName = e.planOrBankName
        delete form.planOrBankName
        form.supplierName = e.creditor
        delete form.creditor
        form.supplierId = e.creditorId
        delete form.creditorId
        form.loanTotal = e.loanAmountFactoring
        delete form.loanAmountFactoring
        form.loanAmountFactoring = totalPrice
        delete form.totalPrice
        // form.feeRateDate = (e.factoringRate / 100).toString()
        // delete form.factoringRate
        form.factoringMoneyTotal = e.factoringMoney
        delete form.factoringMoney
        // 去保存
        this.$emit('onSaved', form)
      } else {
        // 放款金额和放款量不一致
        this.warning(this.$t('selfPayLoan.comparePrompt'))
      }
    },
    // 格式化表单
    formatForm () {
      let forms = this.forms
      let factoringMoney = forms.factoringMoney // 应收总额
      let loanDateFactoring = forms.loanDateFactoring // 放款时间
      let feeRate = forms.feeRate / 100 // 手续费费率(不需要日期加权)
      let feeRateDate = forms.feeRateDate / 100 // 手续费费率(需要日期加权)
      // 费率超过1不予计算
      if (feeRate >= 1 || feeRateDate >= 1) {
        return false
      }
      // 应收账款，放款日期存在才进行计算
      if (loanDateFactoring && factoringMoney && this.number > 1) {
        // console.log(loanDateFactoring)
        let factoryPeriods = forms.factorPeriods // 保理天数
        let countPeriods = forms.countPeriods || 360 // 计算天数
        let dueDate = Number(forms.dueDate) // 到期时间
        let factoringRate = (forms.factoringRate ? forms.factoringRate : 0) / 100 // 费率
        let date = ((new Date(dueDate) - loanDateFactoring) / (1000 * 60 * 60 * 24)) // 时间差
        let feeTwo = factoringMoney * feeRateDate * (date < factoryPeriods ? date : factoryPeriods) / countPeriods
        let feeOne = factoringMoney * feeRate
        // console.log(dueDate, loanDateFactoring)
        // ※放款日期、手续费费率(需要日期加权)、手续费费率(不需要日期加权)输入后，自动计算放款量和手续费。
        // ※不需日期加权的时候：
        // 手续费1 = 应收账款金额*费率；
        // ※需要日期加权的时候：
        // 手续费2 = 保理金额*需日期加权费率*保理天数（根据配置，是365，还是到期日 - 实际放款日期（供应商）的差）/360；
        // ※获取最终的手续费：
        // 手续费1+手续费2的和与0比较，大于0，则为和，小于0，则为空
        // ※放款量 = 应收账款金额 － （应收账款金额 * （到期日 - 实际放款日期（供应商））/ 360 * 供应商利率）-手续费（如果有的话，要减去）
        if (feeRate && feeRateDate) {
          forms.fee = feeOne + feeTwo > 0 ? (feeOne + feeTwo).toFixed(2) : ''
        } else if (feeRate && !feeRateDate) {
          forms.fee = feeOne > 0 ? feeOne.toFixed(2) : ''
        } else if (!feeRate && feeRateDate) {
          forms.fee = feeTwo > 0 ? feeTwo.toFixed(2) : ''
        } else if (!feeRate && !feeRateDate) {
          forms.fee = ''
        }
        // console.log(factoringMoney, factoringMoney * date / countPeriods * factoringRate)
        forms.loanAmountFactoring = (factoringMoney - (factoringMoney * date / countPeriods * factoringRate) - (forms.fee ? forms.fee : 0)).toFixed(2)
      }
    }
  },
  watch: {
    visible (val) {
      if (val) {
        this.number = 0
        let $this = this
        // 编辑
        if ($this.editModel === 'E') {
          $this.loadingFlag = true
          let keyId = $this.currentRow.keyId
          // 使付款确认书不可编辑
          $this.componentList[0].disabled = true
          $this.componentList[0].btnDisplay = false
          $this.formRules.assetCode[0].required = false
          $this.addData = []
          $this.delData = []
          $this.modData = []
          $this.modifyData = []
          $this.tagId = ''
          $this.forms = {}
          $this.$nextTick(() => {
          // 获取编辑详情且获取核心企业id
            $this.assetpkgmgrButtonLoading = true
            $this.api.getInfo(keyId).then(res => {
              if (res.success) {
                if (res.data) {
                  let forms = $this.UtilJs.cloneDeep($this.forms)
                  $this.forms = Object.assign(forms, res.data)
                  $this.forms.factoringRate = (res.data.factoringRate * 100).toFixed(2)
                  $this.forms.feeRate = res.data.feeRate * 100
                  $this.forms.feeRateDate = res.data.feeRateDate * 100
                }
                // 若放款日期有则赋值
                if ($this.forms.loanDateFactoring) {
                  $this.$set($this.forms, 'loanDateFactoring', new Date($this.forms.loanDateFactoring))
                }
                // 处理日期选择范围
                this.checkChange()
                $this.tagId = res.data.coreEnterpriseId
                externalApi.bridcroquot.getList({ coreEnterpriseId: $this.tagId }).then(ress => {
                  $this.assetpkgmgrButtonLoading = false
                  if (ress.success) {
                    if (res.data.datas) {
                      for (let index in res.data.datas) {
                        let item = res.data.datas[index]
                        for (let index2 in ress.data) {
                          let item2 = ress.data[index2]
                          if (item.fundsProvideCode === item2.keyId) {
                            item.approvalLimit = item2.approvalLimit
                          }
                        }
                      }
                    }
                    $this.modifyData = res.data.datas
                    $this.loadingFlag = false
                  }
                }).catch(res => {
                  $this.assetpkgmgrButtonLoading = false
                  $this.loadingFlag = false
                })
              }
            }).catch(res => {
              $this.assetpkgmgrButtonLoading = false
              $this.loadingFlag = false
            })
          })
        // 新增
        } else {
          // 重置表单
          $this.forms = {
            loanDateFactoring: ''
            // assetCode: 'PAYXGFYXGSJD20200021029',
            // factoringMoney: 1000000,
            // factorPeriods: 365,
            // countPeriods: 360,
            // dueDate: new Date().getTime(),
            // factoringRate: 0.02
          }
          $this.clearParam()
          // 重置核心企业编号
          $this.tagId = ''
          // 重置表格
          $this.modifyData = []
          // 使付款确认书可编辑
          $this.componentList[0].disabled = false
          $this.componentList[0].btnDisplay = true
          $this.formRules.assetCode[0].required = true
        }
      }
    },
    // 监听应收账总额、放款日期、手续费费率(需要日期加权)、手续费费率(不需要日期加权)，动态计算放款量和手续费
    FormList () {
      this.number++
      this.formatForm()
    }
  }
}
</script>

<style scoped>
  @import '~@/styles/assetpkgmgr/selfPayLoan/selfPayAddModPop.scss';
</style>
