<template>
  <!-- 银行报价录入 -->
  <div>
    <dialog-edit width="95%" :visible.sync="dialogVisible" :form="form2" :closeLabel="$t('common.cancel')" :saveLabel="$t('common.submit')" :formRules="formRules" :autoSave="autoSave" :editModel="editModel"
      :api="api" :appendToBody="appendToBody" :title="$t('common.bankImport')" @onSaved="handleSubmit">
      <div class="assetpkgmgr-box" v-loading="assetpkgmgrButtonLoading">
        <!-- 基础信息 -->
        <div class="viewForm">
          <dym-form :formValue.sync="forms" :componentList="componentList"></dym-form>
        </div>
        <!-- 表格列表 -->
        <data-table ref="dataTable" v-bind="{maxHeight:300}" :pageAll="true" :operateBtnLayout="operateBtnLayout" selectable="false"
          :queryParas="queryParas" :sourceData="modifyData" :toolMenuFlag="toolMenuFlag" :columns="modifyColumns"
          :showPage="showPage" :loadCount.sync="loadCount" :menuFlag="menuFlag" :headTitle="$t('common.bankImport')"
          :loadingFlag="loadingFlag" @sizeChange="handleFilter" @currentChange="handleFilter">
        </data-table>
        <!-- 银行录入表单 -->
        <dym-form :formValue.sync="form2" :componentList="componentListTwo" style="margin-top: 20px;"></dym-form>
      </div>
    </dialog-edit>
  </div>
</template>

<script>
import BaseEdit from '@/pages/baseEditPage'
import * as format from '@/filters/index.js'
import {
  DialogEdit,
  DataTable,
  dymForm,
  validate,
  amountInput
} from 'newepoch-components'
import bankPrice from '@/api/assetpkgmgr/bankPriceApi.js'
import external from '@/api/assetpkgmgr/externalApi.js'
export default {
  extends: new BaseEdit(),
  name: 'bankPriceInputPop',
  components: {
    DialogEdit,
    DataTable,
    dymForm
  },
  props: {
    autoSave: {
      type: [Boolean],
      default: false
    },
    assetPackageCode: {
      type: [String],
      default: ''
    }
  },
  data () {
    // 银行费率表单校验
    let checkPercent = (rule, value, callback) => {
      let num = parseFloat(value)
      // 费率是否为空
      if (this.UtilJs.isEmpty(num) || isNaN(num)) {
        return callback(new Error(this.$t('bankPrice.isFee')))
      }
      // // 费率是否为整数
      // if (num % 1 !== 0) {
      //   return callback(new Error(this.$t('bankPrice.feeInt')))
      // }
      // 费率必须在0到100之间
      if (num >= 100 || num <= 0) {
        callback(new Error(this.$t('bankPrice.feeRange')))
      } else {
        callback()
      }
    }
    return {
      showPage: true, // 是否分页
      appendToBody: true,
      toolMenuFlag: false,
      loadCount: 0,
      menuFlag: false,
      operateBtnLayout: '',
      loadingFlag: false, // 加载动画控件
      queryParas: {
        pageIndex: 1,
        pageSize: 10
      },
      form2: {},
      selectRows: [], // 选中项
      modifyData: [], // 列表
      contactData: [],
      forms: {},
      // 查看表单
      componentList: [
        {
        // 产品名称
          label: this.$i18n.messages[this.$i18n.locale].bankPrice.projectName,
          disabled: true,
          value: 'projectName',
          prop: 'projectName',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.noForm,
          labelWidth: '140px',
          cols: [12, 12, 12, 8],
          clearable: true,
          componentName: 'el-input'
        },
        {
        // 再保理银行
          label: this.$i18n.messages[this.$i18n.locale].bankPrice.factorBankName,
          disabled: true,
          value: 'factorBankName',
          prop: 'factorBankName',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.noForm,
          labelWidth: '140px',
          cols: [12, 12, 12, 8],
          clearable: true,
          componentName: 'el-input'
        },
        {
        // 原始权益人
          label: this.$i18n.messages[this.$i18n.locale].bankPrice.originalOwner,
          disabled: true,
          value: 'initialOwnersName',
          prop: 'initialOwnersName',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.noForm,
          labelWidth: '140px',
          cols: [12, 12, 12, 8],
          clearable: true,
          componentName: 'el-input'
        },
        {
        // 再保理总金额
          label: this.$i18n.messages[this.$i18n.locale].bankPrice.factoringMoneyTotal,
          disabled: true,
          value: 'factoringMoneyTotal',
          prop: 'factoringMoneyTotal',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.noForm,
          labelWidth: '140px',
          cols: [12, 12, 12, 8],
          clearable: true,
          componentName: 'el-input'
        },
        {
        // 到账日期
          label: this.$i18n.messages[this.$i18n.locale].bankPrice.dueDate,
          disabled: true,
          value: 'dueDate',
          prop: 'dueDate',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.noForm,
          labelWidth: '140px',
          cols: [12, 12, 12, 8],
          clearable: true,
          componentName: 'el-input'
        }
      ],
      // 银行录入表单校验
      formRules: {
        serviceMoney: [{
          validator: checkPercent,
          required: true,
          trigger: 'blur'
        }],
        manageMoney: [{
          validator: checkPercent,
          required: true,
          trigger: 'blur'
        }],
        preLoanDateBank: [{
          type: 'date',
          required: true,
          message: '请选择预计放款日期(保理商)',
          trigger: 'change'
        }],
        preLoanDateFactoring: [{
          type: 'date',
          required: true,
          message: '请选择预计放款日期(保理商)',
          trigger: 'change'
        }],
        assetContractInfoId: [{
          validator: validate.contractNumValidate,
          message: '请输入正确的合同编号',
          trigger: 'blur'
        }]
      },
      // 录入表单
      componentListTwo: [
        {
        // 银行服务费率
          label: this.$i18n.messages[this.$i18n.locale].bankPrice.bankServiceRate,
          disabled: false,
          value: 'serviceMoney',
          prop: 'serviceMoney',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
          labelWidth: '160px',
          cols: [12, 12, 12, 8],
          clearable: true,
          componentName: amountInput
        },
        {
        // 银行管理费率
          label: this.$i18n.messages[this.$i18n.locale].bankPrice.bankManageRate,
          disabled: false,
          value: 'manageMoney',
          prop: 'manageMoney',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
          labelWidth: '160px',
          cols: [12, 12, 12, 8],
          clearable: true,
          componentName: amountInput
        },
        {
        // 预计放款日期(保理商)
          label: this.$i18n.messages[this.$i18n.locale].bankPrice.expectedDisbursementDate,
          disabled: false,
          value: 'preLoanDateBank',
          prop: 'preLoanDateBank',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect,
          labelWidth: '160px',
          cols: [12, 12, 12, 8],
          pickerOptions: {
            disabledDate: function () {
              return true
            }
          },
          componentName: 'el-date-picker'
        },
        {
        // 预计放款日期(供应商)
          label: this.$i18n.messages[this.$i18n.locale].bankPrice.expectedDisbursementDateTwo,
          disabled: false,
          value: 'preLoanDateFactoring',
          prop: 'preLoanDateFactoring',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect,
          labelWidth: '160px',
          cols: [12, 12, 12, 8],
          pickerOptions: {
            disabledDate: function () {
              return true
            }
          },
          componentName: 'el-date-picker'
        // format: 'timestamp'
        },
        {
        // 合同编号
          label: this.$i18n.messages[this.$i18n.locale].bankPrice.constractCode,
          disabled: false,
          showFlag: false,
          value: 'assetContractInfoId',
          prop: 'assetContractInfoId',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
          labelWidth: '160px',
          cols: [12, 12, 12, 8],
          clearable: true,
          componentName: 'el-input'
        }
      ],
      modifyColumns: [
        // 付款确认书编号
        {
          prop: 'assetCode',
          align: 'center',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].bankPrice.payCode,
          width: '250px'
        },
        // 供应商
        {
          prop: 'creditor',
          align: 'left',
          headerAlign: 'center',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].bankPrice.suppliersName,
          width: '200px'
        },
        // 区域
        {
          prop: 'coreAreaName',
          align: 'left',
          headerAlign: 'center',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].bankPrice.district,
          width: '100px'
        },
        // 登记证明编号
        {
          prop: 'registrationCertificateCode',
          showOverflowTooltip: true,
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].bankPrice.registrationNumber,
          width: '200px'
        },
        // 项目公司名称
        {
          prop: 'debtor',
          align: 'left',
          headerAlign: 'center',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].bankPrice.enterpriseName,
          width: '200px'
        },
        // 合同编号
        {
          prop: 'basicContractCode',
          showOverflowTooltip: true,
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].bankPrice.constractCode,
          width: '200px'
        },
        // 合同名称
        {
          prop: 'basicContractName',
          showOverflowTooltip: true,
          align: 'left',
          headerAlign: 'center',
          label: this.$i18n.messages[this.$i18n.locale].bankPrice.constractName,
          width: '230px'
        },
        {
          // 账款到期日
          prop: 'dueDate',
          align: 'center',
          width: '115px',
          label: this.$i18n.messages[this.$i18n.locale].bankPrice.dueDate,
          format: (row) => {
            return format.formatDateTpcModify(row.dueDate)
          }
        },
        {
          // 应收账款金额（元）
          prop: 'factoringMoney',
          align: 'right',
          headerAlign: 'center',
          showOverflowTooltip: true,
          width: '171px',
          label: this.$i18n.messages[this.$i18n.locale].bankPrice.accountsReceivableTotal,
          format: (row) => {
            return format.thousandFilter(row.factoringMoney)
          }
        }
      ],
      pageSize: 10 // 页码
    }
  },
  computed: {
    // 创建新资产包
    api () {
      return bankPrice.detail
    },
    params () {
      return {
        pageSize: this.queryParas.pageSize,
        pageIndex: this.queryParas.pageIndex,
        assetPackageCode: this.assetPackageCode
      }
    }
  },
  methods: {
    // 提交录入
    handleSubmit (e) {
      let that = this
      let assetPackageStatus = that.forms.assetPackageStatus
      e.assetPackageCode = that.assetPackageCode
      let params = JSON.parse(JSON.stringify(e))
      if (assetPackageStatus !== '4') {
        params.preLoanDateBank = new Date(params.preLoanDateBank).getTime().toString()
        params.preLoanDateFactoring = new Date(params.preLoanDateFactoring).getTime().toString()
      }
      // 费率转化为浮点数
      params.serviceMoney = parseFloat(params.serviceMoney).toString()
      params.manageMoney = parseFloat(params.manageMoney).toString()
      // 提交录入
      this.assetpkgmgrFullScreenLoading()
      bankPrice.bankPrice.confirm(params).then(res => {
        this.assetpkgmgrFullScreenLoading().close()
        if (res.success) {
          that.success(that.$t('bankPrice.importSuccess'))
          that.dialogVisible = false
          that.$parent.$refs.dataTable.loadTableData()
        }
      }).catch(res => {
        this.assetpkgmgrFullScreenLoading().close()
      })
    },
    handleFilter () {
      let $this = this
      // 请求详情
      $this.assetpkgmgrButtonLoading = true
      bankPrice.detail.getPage($this.params).then(res => {
        if (res.success) {
          let datas = res.data
          let componentListTwo = $this.componentListTwo // 银行录入表单
          let formRules = $this.formRules // 银行录入表单校验
          // 如果再报理银行为招商银行,则不显示合同编号输入框
          // console.log(bankId)
          if (datas.factorBankId === this.bankId) {
            componentListTwo[componentListTwo.length - 1].showFlag = true
          } else {
            componentListTwo[componentListTwo.length - 1].showFlag = false
          }
          // 资产包状态为【4:已放款登记】的时候，只有【银行服务费率】和【银行管理费率】可修改，其他项目不可修改
          let isRegister = datas.assetPackageStatus === '4'
          componentListTwo[2].disabled = isRegister
          componentListTwo[3].disabled = isRegister
          componentListTwo[4].disabled = isRegister
          formRules.preLoanDateBank[0].required = !isRegister
          formRules.preLoanDateFactoring[0].required = !isRegister
          $this.checkChange(datas.dueDate)
          // 初始化表单
          $this.forms = {
            factoringMoneyTotal: format.thousandFilter(datas.factoringMoneyTotal),
            initialOwnersName: datas.initialOwnersName,
            projectName: datas.projectName,
            factorBankName: datas.factorBankName,
            assetPackageStatus: datas.assetPackageStatus,
            dueDate: format.formatDateTpcModify(datas.dueDate)
          }
          // 银行管理费率存在时
          if (datas.manageMoney && datas.manageMoney !== '0.00') {
            $this.$set($this.form2, 'manageMoney', datas.manageMoney)
          }
          // 银行服务费率存在时
          if (datas.serviceMoney && datas.manageMoney !== '0.00') {
            $this.$set($this.form2, 'serviceMoney', datas.serviceMoney)
          }
          // 预计放款日期(保理商)存在时
          if (datas.expectPayDateBank > 0) {
            $this.$set($this.form2, 'preLoanDateBank', Number(datas.expectPayDateBank))
          }
          // 预计放款日期(供应商)存在时
          if (datas.expectPayDateSupply > 0) {
            $this.$set($this.form2, 'preLoanDateFactoring', Number(datas.expectPayDateSupply))
          }
          // 合同编号存在时
          if (datas.assetContractInfoId) {
            $this.$set($this.form2, 'assetContractInfoId', datas.assetContractInfoId)
          }
          $this.$refs.dataTable.buildTableData(datas.datas.datas, datas.datas.totalRow)
        }
        $this.assetpkgmgrButtonLoading = false
      }).catch(res => {
        $this.assetpkgmgrButtonLoading = false
      })
    },
    // 处理日期选择范围
    checkChange (e, t) {
      let dueDate = e
      // console.log(this.forms)
      // 使选择日期不能超过账款到期日
      if (dueDate) {
        this.componentListTwo[2].pickerOptions = {
          disabledDate: function (time) {
            return time.getTime() > dueDate
          }
        }
        this.componentListTwo[3].pickerOptions = {
          disabledDate: function (time) {
            return time.getTime() > dueDate
          }
        }
      } else {
        this.componentListTwo[2].pickerOptions = {
          disabledDate: function () {
            return true
          }
        }
        this.componentListTwo[3].pickerOptions = {
          disabledDate: function () {
            return true
          }
        }
      }
    }
  },
  watch: {
    async visible (val) {
      if (val) {
        let $this = this
        $this.form2 = {}
        $this.forms = {}
        $this.modifyData = []

        let args = {
          setupType: 'factor_bank',
          setupKey: ['factor_bank_zs']
        }
        // 获取招商银行id
        let bankId = await new Promise((resolve, reject) => {
          // 请求招商银行id
          external.bank.getBank(args).then(res => {
            if (res.success) {
              resolve(res.data.factor_bank_zs)
            }
          })
        })
        this.bankId = bankId
        this.handleFilter()
      }
    }
  }
}
</script>
