<template>
  <!-- 自有资产放款信息登记 -->
  <div>
    <up-down-layout :handleFlag.sync="handleFlag">
      <search-form :formValue.sync="queryParas" searchPerms="search" @handleFilter="handleFilter" @clearParam="clearParam"
        slot="query" resetPerms="reset" :componentList="componentList"></search-form>
      <template slot="table">
        <data-table ref="dataTable" :api="api" v-bind="elHeightObj" :deleteApi="api" selectable="false" :handleFlag.sync="handleFlag" :menuFlag="false"
          :queryParas="queryParas" :sourceData.sync="sourceData" :loadCount.sync="loadCount" loadPage="search" :columns="columns"
          :showSelection="false" :otherHeight="'240'" operateBtnLayout="" :IsRight="false" :pageAll="true" :operatWidth="'200'" @getTableData="getTableData">
          <!-- 新增 -->
          <template slot="headButton">
            <div align="right">
              <auth-button class="iconfont iconxinzeng" :size="'medium'" :label="$t('common.create')" @click="dialogVisible = true;editModel = 'C'"
                type="primary"></auth-button>
            </div>
          </template>
          <!-- 放款自垫文件操作栏 -->
          <el-table-column align="center" min-width="150px" :label="$t('selfPayLoan.selfPayFileName')" fixed="right">
            <!-- 当再保理银行为浦发和邮储以外的时候，【重新生成】和【下载】按钮不显示 -->
            <template v-if="scope.row.factorBankId === ycbank || scope.row.factorBankId === pfbank" slot-scope="scope">
              <!-- 重新生成 -->
              <auth-button class="iconCircle" icon="iconfont iconzhongxinshengcheng" :title="$t('common.remake')" @click="operateItem(scope.row,0)"></auth-button>
              <!-- 下载 -->
              <!-- <btn-batch-download v-if="scope.row.fileList && scope.row.fileList.length > 0 && computeFile(scope.row.fileList)" :fileID="scope.row.fileList" :title="$t('common.downLoad')"></btn-batch-download> -->
              <auth-button class="iconCircle" icon="iconfont iconxiazai" :title="$t('common.downLoad')" @click="operateItem(scope.row,1)" :disabled="!(scope.row.fileList && scope.row.fileList.length > 0 && computeFile(scope.row.fileList))"></auth-button>
            </template>
          </el-table-column>
          <!-- 单行操作栏 -->
          <el-table-column align="center" min-width="150px" :label="$t('common.operate')" fixed="right">
            <template slot-scope="scope">
              <!-- 若已开票则不显示openInvoiceStatus:21 已开部分电子票;22 已开电子票;23 已开纸质票 -->
              <div v-if="scope.row.openInvoiceStatus !== '21' && scope.row.openInvoiceStatus !== '22' && scope.row.openInvoiceStatus !== '23'">
                <!-- 编辑 -->
                <auth-button class="iconCircle" icon="iconfont iconbianji" :title="$t('common.edit')" @click="checkInfo(scope.row)"></auth-button>
                <!-- 删除 -->
                <auth-button class="iconCircle iconCircleDel" icon="iconfont iconycjian" :title="$t('common.delete')" @click="operateItem(scope.row,2)"></auth-button>
              </div>
            </template>
          </el-table-column>
        </data-table>
      </template>
    </up-down-layout>
    <selfPayAddModPop :visible.sync="dialogVisible" :editModel="editModel" :form="form" :autoSave="false" @onSaved="saveItem" :currentRow="currentRow"></selfPayAddModPop>
  </div>
</template>
<script>
import {
  upDownLayout,
  searchForm,
  DataTable,
  authButton,
  SelectFinancialInstitutions
} from 'newepoch-components'
import selfPayAddModPop from './selfPayAddModPop' // 自有资金放款登记新增编辑页面
import fileApi from '@/api/fileApi.js'
import {
  downFile
} from '@/utils/devUtils'
import selfPayLoan from '@/api/assetpkgmgr/selfPayLoanApi.js'
import external from '@/api/assetpkgmgr/externalApi.js'
import * as format from '@/filters/index'
import BasePage from '@/pages/basePage'
import mixin from '@/pages/mixin'

export default {
  extends: new BasePage(),
  mixins: [mixin],
  name: 'selfPayLoanIndex',
  components: {
    searchForm,
    upDownLayout,
    DataTable,
    // btnDownload,
    authButton,
    selfPayAddModPop
  },
  data () {
    return {
      handleFlag: true,
      loadCount: 0,
      editModel: '',
      currentRow: {},
      dialogVisible: false, // 添加和编辑自有资产放款信息控件
      queryData: {},
      form: {},
      componentList: [
        {
        // 再保理银行
          label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.planOrBankName,
          disabled: false,
          value: 'planOrBankId',
          labelWidth: '160px',
          clearable: true,
          componentName: SelectFinancialInstitutions
        },
        {
        // 付款确认书编号
          label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.payCode,
          disabled: false,
          value: 'assetCode',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
          labelWidth: '160px',
          clearable: true,
          componentName: 'el-input'
        },
        {
        // 账款到期日
          label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.dueDate,
          value: 'dueDate',
          componentName: 'el-date-picker',
          clearable: true,
          labelWidth: '160px',
          format: 'timestamp'
        }
      ],
      columns: [{
        // 付款确认书编号
        prop: 'assetCode',
        align: 'center',
        sortable: true,
        width: '240px',
        label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.payCode
      },
      {
        // 供应商名称
        prop: 'supplierName',
        headerAlign: 'center',
        showOverflowTooltip: true,
        align: 'left',
        width: '230px',
        sortable: true,
        label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.creditor
      },
      {
        // 计划管理人/再保理银行
        prop: 'factorBankName',
        headerAlign: 'center',
        showOverflowTooltip: true,
        align: 'left',
        width: '200px',
        sortable: true,
        label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.planOrBankName
      },
      {
        // 应收账款金额（元）
        prop: 'factoringMoneyTotal',
        headerAlign: 'center',
        showOverflowTooltip: true,
        align: 'right',
        width: '171px',
        sortable: true,
        label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.factoringMoney,
        format: (row) => {
          return format.thousandFilter(row.factoringMoneyTotal)
        }
      },
      {
        // 账款到期日
        prop: 'dueDate',
        align: 'center',
        width: '115px',
        sortable: true,
        label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.dueDate,
        format: (row) => {
          return format.formatDateTpcModify(row.dueDate)
        }
      },
      {
        // 放款量
        prop: 'loanTotal',
        headerAlign: 'right',
        showOverflowTooltip: true,
        align: 'center',
        sortable: true,
        width: '150px',
        label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.loanAmountFactoring,
        format: (row) => {
          return format.thousandFilter(row.loanTotal)
        }
      },
      {
        // 放款时间
        prop: 'loanDate',
        align: 'center',
        width: '171px',
        sortable: true,
        label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.loanDateFactoring,
        format: (row) => {
          return format.formatDateTpcModify(row.loanDate)
        }
      },
      {
        // 手续费
        prop: 'feeTotal',
        headerAlign: 'center',
        showOverflowTooltip: true,
        align: 'right',
        width: '171px',
        sortable: true,
        label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.fee,
        format: (row) => {
          return format.thousandFilter(row.feeTotal)
        }
      },
      {
        // 资金来源
        prop: 'fundsProvide',
        showOverflowTooltip: true,
        align: 'center',
        width: '230px',
        label: this.$i18n.messages[this.$i18n.locale].selfPayLoan.ownerName,
        format: (row) => {
          return row.fundsProvide.join('，')
        }
      }
      ],
      sourceData: [],
      ycbank: '', // 邮储银行
      pfbank: '' // 浦发银行
    }
  },
  computed: {
    // api接口
    api () {
      return selfPayLoan.selfPayLoan
    }
  },
  async mounted () {
    // 配置请求银行参数
    let args = {
      setupType: 'factor_bank',
      setupKey: ['factor_bank_yc', 'factor_bank_pf']
    }
    // 获取浦发银行和有邮储银行id
    let bankInfo = await new Promise((resolve, reject) => {
      external.bank.getBank(args).then(res => {
        if (res.success) {
          resolve(res.data)
        }
      })
    })
    // 邮储银行
    this.ycbank = bankInfo.factor_bank_yc
    // 浦发银行
    this.pfbank = bankInfo.factor_bank_pf
    // 触发loadCount去请求获得表格数据
    this.handleFilter()
  },
  methods: {
    getTableData (data) {
      data = data.map(item => {
        item.factoringMoneyTotal = Number(item.factoringMoneyTotal)
        item.loanTotal = Number(item.loanTotal)
        item.feeTotal = Number(item.feeTotal)
        return item
      })
    },
    // 文件列表判空
    computeFile (e) {
      for (let index in e) {
        let item = e[index]
        if (item < 1) {
          return false
        }
      }
      return true
    },
    // 新增
    saveItem (e) {
      let $this = this
      let url = $this.editModel === 'E' ? 'modItem' : 'addItem'
      $this.assetpkgmgrFullScreenLoading()
      $this.api[url](e).then(res => {
        $this.assetpkgmgrFullScreenLoading().close()
        if (res.success) {
          this.dialogVisible = false
          $this.success(($this.editModel === 'E' ? '编辑' : '新增') + '成功！')
          $this.isAdd = false // 关闭遮罩
          $this.handleFilter() // 重置列表
        } else {
          $this.error(res.message)
        }
      }).catch(res => {
        $this.assetpkgmgrFullScreenLoading().close()
      })
    },
    // 查看和编辑
    checkInfo (row) {
      this.editModel = 'E'
      this.currentRow = row
      this.dialogVisible = true
    },
    // 操作栏
    operateItem (row, type) { // id:keyId;type:0 重新生成;1 下载;2 删除;
      let that = this
      let apiName = [that.$t('common.remake'), that.$t('common.downLoad'), that.$t('common.delete')]
      let api = ['recreate', 'download', 'deleteItem']
      that.$confirm(that.$t('common.confirm') + apiName[type] + '？', that.$t('common.tip'), {
        type: 'warning'
      }).then(() => {
        that.assetpkgmgrFullScreenLoading()
        // 下载
        if (type === 1) {
          fileApi.file.batchDownload({
            keyIds: row.fileList
          }).then(res => {
            that.assetpkgmgrFullScreenLoading().close()
            downFile(res, row.assetCode + '.zip')
          }).catch(res => {
            that.assetpkgmgrFullScreenLoading().close()
            that.error(res.message)
          })
        } else {
          let args = {
            keyId: row.keyId
          }
          if (type === 2) {
            args.coreEnterpriseId = row.coreEnterpriseId
            args.productType = row.productType
          } else {
            args.selfPayFileName = row.selfPayFileName
          }
          // 重新生成或删除
          that.api[api[type]](args).then(function (res) {
            that.assetpkgmgrFullScreenLoading().close()
            that.handleSubmit(res, function () {
              // 回调提示
              that.success(apiName[type] + that.$t('common.successfully'))
              // 重置表格
              that.$refs.dataTable.loadTableData()
            })
          }).catch(res => {
            that.assetpkgmgrFullScreenLoading().close()
          })
        }
      }).catch((e) => {})
    },
    // 提交回调
    handleSubmit (res, callback) {
      let that = this
      if (res.success) {
        // 回调函数
        callback && callback()
      } else {
        that.error(res.message)
      }
    }
  },
  watch: {
    editVisible (value) {
      if (!value) {
        this.handleFilter()
      }
    }
  }
}
</script>
