<template>
  <div>
    <dialog-edit width="95%" ref="dialogEdit" :visible.sync="dialogVisible" :form="queryParas" :formRules="formRules" :autoSave="autoSave"
      :editModel="editModel" :api="api" :appendToBody="appendToBody" :title="$t('sendLoanInfo.addTitle')"
      @onSaved="onSaved">
      <div class="assetpkgmgr-box">
        <!-- 查询信息 -->
        <dym-form :formValue.sync="queryParas" :componentList="componentList" @selectChanged="selectChanged"></dym-form>
        <div align="right">
          <auth-button icon="iconfont iconycchaxun" :size="'medium'" :label="$t('common.search')" @click="isSend = false;$refs.dialogEdit.save()"
            type="primary"></auth-button>
          <auth-button icon="iconfont iconyczhongzhi" :size="'medium'" :label="$t('common.reset')" @click="clearParam"
            type="primary"></auth-button>
        </div>
        <dividerTitle :title="$t('sendLoanInfo.payCodeList')"></dividerTitle>
        <!-- 可放款资产信息一览 -->
        <data-table ref="dataTable" :api="api" :operateBtnLayout="operateBtnLayout" v-bind="{maxheight:300}" selectable="false"
          :showSelection="true" :queryParas="queryParas" :sourceData="modifyData" :toolMenuFlag="toolMenuFlag" :columns="modifyColumns"
          :loadCount.sync="loadCount" :menuFlag="menuFlag" loadPage="getInfo" :headTitle="$t('sendLoanInfo.addTitle')"
          :loadingFlag="loadingFlag" :selectedRows.sync="selectedRows">
          <template slot="headButton">
            <div class="flex-spaceB" style="margin-bottom: 10px;">
              <el-form ref="submitForm" :rules="submitRules" :model="submitForms" style="width:65%">
                <dym-form :formValue.sync="submitForms" :componentList="submitForm" @selectChanged="bankChanged"></dym-form>
              </el-form>
              <div align="right">
                <auth-button :size="'medium'" icon="iconfont iconfasong" :label="$t('sendLoanInfo.setBtn')" @click="isSend = true;$refs.dialogEdit.save()" type="primary"></auth-button>
              </div>
            </div>
          </template>
        </data-table>
      </div>
    </dialog-edit>
    <!-- 发送放款指令弹窗 -->
    <sendLoanCmdEditPop :visible.sync="isSet" :editModel="editType" :form="submitForms" :selectedList="bankApplyCheckListDtoList" @onSaved="saveItem"></sendLoanCmdEditPop>
  </div>
</template>

<script>
import BaseEdit from '@/pages/baseEditPage'
import * as format from '@/filters/index.js'
import {
  DialogEdit,
  DataTable,
  authButton,
  amountInput,
  SelectProductName,
  dymForm
} from 'newepoch-components'
import SelectLoanBank from '@/components/element/assetpkgmgr/SelectLoanBank.vue' // 银行选择框
import dividerTitle from '@/components/element/assetpkgmgr/dividerTitle'
import sendLoanCmdEditPop from './sendLoanCmdEditPop' // 发送放款指令弹窗组件
import sendLoanInfo from '@/api/assetpkgmgr/sendLoanInfoApi.js'
import externalApi from '@/api/assetpkgmgr/externalApi.js'
export default {
  extends: new BaseEdit(),
  name: 'loanApplyPop',
  components: {
    DialogEdit,
    DataTable,
    authButton,
    amountInput,
    dividerTitle,
    sendLoanCmdEditPop,
    dymForm
  },
  props: {
    autoSave: {
      type: [Boolean],
      default: false
    }
  },
  data () {
    return {
      selectedRows: [], // 选中项
      chooseIndex: '', // 选中项索引值
      appendToBody: true,
      toolMenuFlag: true,
      isSet: false,
      isSend: false,
      loadCount: 0,
      submitForms: {},
      menuFlag: false,
      chooseRow: {},
      operateBtnLayout: '',
      loadingFlag: false, // 加载动画控件
      queryParas: {},
      modifyData: [], // 可放款资产列表
      contactData: [],
      editType: 'S',
      forms: {},
      // 基本信息表单验证
      formRules: {
        projectId: [{
          required: true,
          message: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect + this.$i18n.messages[this.$i18n.locale].packageOperation.projectName,
          trigger: 'blur'
        }],
        periods: [{
          required: false,
          message: this.$i18n.messages[this.$i18n.locale].common.pleaseInput + this.$i18n.messages[this.$i18n.locale].sendLoanInfo.periodsNum,
          trigger: 'blur'
        }]
      },
      submitRules: {
        depositBankAccountNotAppend: [{
          required: true,
          message: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect + this.$i18n.messages[this.$i18n.locale].sendLoanInfo.loanBankName,
          trigger: 'blur'
        }, {
          required: true,
          message: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect + this.$i18n.messages[this.$i18n.locale].sendLoanInfo.loanBankName,
          trigger: 'change'
        }],
        loanDate: [{
          required: true,
          message: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect + this.$i18n.messages[this.$i18n.locale].sendLoanInfo.loanDate,
          trigger: 'blur'
        }, {
          required: true,
          message: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect + this.$i18n.messages[this.$i18n.locale].sendLoanInfo.loanDate,
          trigger: 'change'
        }]
      },
      submitForm: [{
        // 划款银行
        label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.loanBankName,
        value: 'depositBankAccountNotAppend',
        prop: 'depositBankAccountNotAppend',
        placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect,
        labelWidth: '100px',
        cols: [11, 11, 11],
        clearable: true,
        name: 'transferBankFlag',
        componentName: SelectLoanBank
      },
      {
        // 划款日期
        label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.loanDate,
        value: 'loanDate',
        prop: 'loanDate',
        componentName: 'el-date-picker',
        labelWidth: '100px',
        clearable: true,
        pickerOptions: {
          disabledDate: function (time) {
            return time.getTime() < new Date().getTime() - 60 * 60 * 24 * 1000
          }
        },
        cols: [11, 11, 11]
      }
      ],
      // 搜索表单
      componentList: [{
        // 产品名称
        label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.projectName,
        value: 'projectId',
        prop: 'projectId',
        placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect,
        labelWidth: '110px',
        name: 'productName',
        cols: [12, 12, 12, 8],
        clearable: true,
        componentName: SelectProductName
      },
      {
        // 期数
        label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.periodsNum,
        value: 'periods',
        prop: 'periods',
        disabled: true,
        placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
        labelWidth: '110px',
        cols: [12, 12, 12, 8],
        clearable: true,
        componentName: amountInput
      },
      {
        // 资产包编号
        label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.assetPackageCode,
        value: 'assetPackageCode',
        prop: 'assetPackageCode',
        placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
        labelWidth: '110px',
        cols: [12, 12, 12, 8],
        clearable: true,
        componentName: 'el-input'
      },
      {
        // 付款确认书编号
        label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.payCode,
        value: 'assetCode',
        prop: 'assetCode',
        placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
        labelWidth: '110px',
        cols: [12, 12, 12, 8],
        clearable: true,
        componentName: 'el-input'
      }
      ],
      modifyColumns: [
        // 付款确认书编号
        {
          prop: 'assetCode',
          align: 'center',
          sortable: true,
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.payCode,
          width: '240px'
        },
        // 供应商名称
        {
          prop: 'recipientName',
          headerAlign: 'center',
          align: 'left',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.suppliersName,
          width: '230px'
        },
        // 应收账款金额（元）
        {
          prop: 'factoringMoneyTotal',
          headerAlign: 'center',
          align: 'right',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.totalPrice,
          width: '150px',
          format: (row) => {
            return format.thousandFilter(row.factoringMoneyTotal)
          }
        },
        // 收款人名称
        {
          prop: 'recipientAccountName',
          headerAlign: 'center',
          align: 'left',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.recipientAccountName,
          width: '170px'
        },
        // 收款人开户行
        {
          prop: 'recipientBankName',
          headerAlign: 'center',
          align: 'left',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.recipientBankName,
          width: '170px'
        },
        // 收款人银行账号
        {
          prop: 'recipientAccount',
          showOverflowTooltip: true,
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.recipientAccount,
          width: '200px'
        }
      ],
      menuKey: 1,
      bankApplyCheckListDtoList: [] // 发送列表
    }
  },
  computed: {
    // api
    api () {
      return sendLoanInfo.sendLoanInfo
    }
  },
  methods: {
    // 提交表单
    saveItem (e) {
      let $this = this
      $this.api['review'](e).then(res => {
        if (res.success) {
          $this.dialogVisible = false
          $this.success($this.$t('sendLoanInfo.setBtn'))
          $this.isSet = false // 关闭遮罩
          $this.$parent.$refs.dataTable.loadTableData()
          // 重置列表
        } else {
          $this.error(res.message)
        }
      })
    },
    // 选中产品名称回调
    selectChanged (a, b, c) {
      if (a.productNameInfo) {
        let params = {
          projectIdArray: [a.productNameInfo.keyId]
        }
        // 请求产品分类
        externalApi.productClassify.getList(params).then(res => {
          if (res.success) {
            // 产品是否为ABS
            let isABS = res.data[0].productType === '1'
            // 重置期数
            if (!isABS) {
              this.$set(this.queryParas, 'periods', '')
            }
            // 添加产品类型至表单
            if (!this.queryParas.productType) {
              this.$set(this.queryParas, 'productType', res.data[0].productType)
            } else {
              this.queryParas.productType = res.data[0].productType
            }
            // 更新期数规则校验必填状态
            this.formRules.periods[0].required = isABS
            // this.menuKey++
            // 更新期数编辑状态
            this.componentList[1].disabled = !isABS
            this.$refs.dialogEdit.$refs.editForm.clearValidate('periods')
          }
        })
        this.submitForms.projectId = a.productNameInfo.keyId
        this.submitForms.projectName = a.productNameInfo.projectName
      }
    },
    // 选中银行回调
    bankChanged (a, b, c) {
      if (a.transferBankFlagInfo) {
        this.submitForms.loanBankId = a.transferBankFlagInfo.bankId
        this.submitForms.loanBankName = a.transferBankFlagInfo.depositBankAccount
      }
    },
    // 查询或发送放款指令
    onSaved () {
      // 发送放款指令
      if (this.isSend) {
        this.sendDerective()
      // 查询
      } else {
        this.getList()
      }
    },
    // 请求表格数据
    getList () {
      let that = this
      // 参数
      let params = {
        pageIndex: 1,
        pageSize: 10,
        projectId: that.queryParas.projectId,
        productType: that.queryParas.productType,
        assetPackageCode: that.queryParas.assetPackageCode,
        periods: that.queryParas.periods,
        assetCode: that.queryParas.assetCode
      }
      // 加载
      that.loadingFlag = true
      // 请求
      that.api.getInfo(params).then(res => {
        // 加载结束
        that.loadingFlag = false
        // 请求成功
        if (res.success) {
          // that.modifyData = res.data.datas
          that.$refs.dataTable.buildTableData(res.data.datas, res.data.totalRow)
          // that.isJiangsu = res.data.bankStatus
        }
      }).catch(res => {
        // 加载结束
        that.loadingFlag = false
      })
    },
    // 发送放款指令
    sendDerective () {
      let that = this
      // 检验发送放款指令表单
      that.$refs['submitForm'].validate((valid) => {
        if (valid) {
          let selectedRows = that.selectedRows // 选中项
          let loanBankName = that.submitForms.loanBankId // 选中银行
          let projectId = that.submitForms.projectId // 选中产品
          // console.log(this.queryParas.periods)
          // if (this.queryParas.periods) {
          this.submitForms.periods = this.queryParas.periods
          // }
          this.bankApplyCheckListDtoList = []
          // 若有选中资产
          if (selectedRows.length > 0) {
            // 选中项是否属于该产品（防止查询过后重选产品）
            for (let index in selectedRows) {
              if (selectedRows[index].projectId !== projectId) {
                that.warning(that.$t('sendLoanInfo.noProject'))
                return
              }
            }
            let args = {
              projectId: [projectId],
              bankId: loanBankName,
              bankApplyCheckListDtoList: selectedRows.map(item => {
                item.loanTime = this.submitForms.loanDate.getTime().toString()
                return item
              })
            }
            // 根据选择的银行账号，产品以及银行ID，从【划款银行账号配置信息】表中，查询结果存在的时候，才能进行放款
            that.api.check(args).then(res => {
              if (res.success && res.data && res.data.length > 0) {
                this.bankApplyCheckListDtoList = res.data
                // 打开放款申请
                that.editType = 'S'
                that.isSet = true
              }
            })
          } else {
            that.editType = 'S'
            that.isSet = true
          }
        }
      })
    },
    // 重置
    clearParam () {
      this.queryParas = {
        pageIndex: 1,
        pageSize: 10
      }
      this.componentList[1].disabled = true
      this.formRules.periods[0].required = false
      this.$refs.dialogEdit.$refs.editForm.clearValidate()
      setTimeout(() => {
        this.$refs.submitForm.clearValidate()
      }, 500)
    }
  },
  watch: {
    visible (val) {
      if (!val) {
        // 初始化
        this.$nextTick(() => {
          this.modifyData = []
          this.submitForms = {}
          this.clearParam()
        })
      }
    },
    FormList () {
      this.formatForm()
    }
  }
}
</script>

<style scoped>
  @import "~@/styles/assetpkgmgr/common.scss";
</style>
