<template>
  <div>
    <up-down-layout :handleFlag="true">
      <!-- 搜索栏 -->
      <search-form @clearParam="clearParam"
                   @handleFilter="handleFilters"
                   :menuCode="menuId"
                   searchPerms="search"
                   resetPerms="reset"
                   :formValue.sync="queryParas"
                   :componentList="componentList"
                   slot="query">
      </search-form>
      <!-- 表格栏 -->
      <data-table :api="api"
                  slot="table"
                  operateBtnLayout=""
                  :columns="columns"
                  :loadCount.sync="loadCount"
                  :queryParas="queryParas"
                  :showSelection="true"
                  :menuFlag="true"
                  v-bind="elHeightObj"
                  :selectedRows.sync="selectedRows"
                  @selectRowChange="selectRowChange"
                  @sort-change="sortChange">
        <!-- 表头按钮 -->
        <template slot="headButton">
          <div class="head_button_right">
            <!-- 通知书下载 -->
            <auth-button size="medium"
                         type="primary"
                         :label="$t('factoringBusinessInfo.notice_download')"
                         @click="notice(1, $t('message.noticeMsg'))"
                         :menuCode="menuId"
                         perms="remove"
                         icon="iconfont iconxiazai1">
            </auth-button>
            <!-- 项目公司确权文件下载 -->
            <auth-button size="medium"
                         type="primary"
                         :label="$t('factoringBusinessInfo.project_company_auth_file_download')"
                         @click="notice(2, $t('message.projectconfirmMsg'))"
                         :menuCode="menuId"
                         perms="remove"
                         icon="iconfont iconxiazai1">
            </auth-button>
            <!-- 发票下载 -->
            <auth-button size="medium"
                         type="primary"
                         :label="$t('factoringBusinessInfo.invoice_download')"
                         @click="invoice(1, $t('message.invoiceMsg'))"
                         :menuCode="menuId"
                         perms="remove"
                         icon="iconfont iconxiazai1">
            </auth-button>
            <!-- 银行回单下载 -->
            <auth-button size="medium"
                         type="primary"
                         :label="$t('factoringBusinessInfo.bank_receipt_download')"
                         @click="invoice(2, $t('message.bankMsg'))"
                         :menuCode="menuId"
                         perms="remove"
                         icon="iconfont iconxiazai1">
            </auth-button>
            <!-- 导出 -->
            <auth-button size="medium"
                         type="primary"
                         icon="iconfont icondaochu"
                         :label="$t('common.export')"
                         @click="exportFile">
            </auth-button>
          </div>
        </template>
        <!-- 操作列 -->
        <el-table-column fixed="right" align="center" label="操作" width="120px">
          <template slot-scope="scope">
            <!-- 订单履历 -->
            <auth-button icon="iconfont iconlvli"
                          class="iconCircle"
                          :title="$t('factoringBusinessInfo.order_record')"
                          @click="showEdit(scope.row, '1')"
                          :menuCode="menuId"
                          perms="remove">
            </auth-button>
            <!-- 详情 -->
            <auth-button icon="iconfont iconmore"
                          class="iconCircle"
                          :title="$t('common.detail')"
                          @click="showEdit(scope.row, '2')"
                          :menuCode="menuId"
                          perms="detail">
            </auth-button>
          </template>
        </el-table-column>
      </data-table>
    </up-down-layout>
    <!-- 订单详情 -->
    <orderDetail :visible.sync="orderVisible" editModel="V" :form="orderForm" :api="api"></orderDetail>
    <!-- 保理信息详情 -->
    <factoringInfoDetail :visible.sync="factoringVisible" editModel="V" :form="factoringForm" :api="api"></factoringInfoDetail>
  </div>
</template>
<script>
import BasePage from '@/pages/basePage'
import { upDownLayout, searchForm, DataTable, authButton, btnDownload, btnExport, SelectFinancialInstitutions, SelectSmallArea, SelectCoreEnterprise } from 'newepoch-components'
import * as format from '@/filters/index'
import orderDetail from './orderDetail'
import factoringInfoDetail from './factoringInfoDetail'
import mixin from '@/pages/mixin'
import factoringBusinessInfoApi from '@/api/factoringBusinessInfoApi'
import exportApi from '@/api/sysApi.js'
import fileApi from '@/api/fileApi.js'
import { downFile } from '@/utils/devUtils'
import { regExp } from '@/validator/index'
export default {
  name: 'factoringSearch',
  mixins: [mixin],
  extends: new BasePage(),
  components: {
    upDownLayout,
    searchForm,
    DataTable,
    authButton,
    btnDownload,
    btnExport,
    orderDetail,
    factoringInfoDetail
  },
  mounted () {
    let date = new Date()
    let year = date.getFullYear() + '年'
    let month = date.getMonth() + 1 + '月'
    let day = date.getDate() + '日'
    this.reName = year + month + day + '保理业务信息.xlsx'
  },
  computed: {
    api () {
      return factoringBusinessInfoApi.searchApi
    }
  },
  data () {
    const { factoringBusinessInfo } = this.$i18n.messages[this.$i18n.locale]
    return {
      sortWay: {},
      orderVisible: false,
      orderForm: {},
      factoringVisible: false,
      factoringForm: {},
      fileID: '',
      reName: '',
      exportData: {
        keyId: []
      },
      componentList: [
        // 核心企业
        {
          label: factoringBusinessInfo.core_enterprise,
          value: 'coreEnterpriseId',
          componentName: SelectCoreEnterprise,
          labelWidth: '140px'
        },
        // 计划管理人/再保理银行
        {
          label: factoringBusinessInfo.planning_manager,
          value: 'planningManagerId',
          componentName: SelectFinancialInstitutions,
          labelWidth: '160px'
        },
        // 保理专员姓名
        {
          label: factoringBusinessInfo.factoring_commissioner_name,
          value: 'customerAccountName',
          placeholder: '请输入',
          componentName: 'el-input',
          labelWidth: '110px'
        },
        // 付款确认书编号
        {
          label: factoringBusinessInfo.pay_code,
          value: 'assetCode',
          placeholder: '请输入',
          componentName: 'el-input',
          labelWidth: '140px'
        },
        // 供应商名称
        {
          label: factoringBusinessInfo.creditor,
          value: 'creditor',
          placeholder: '请输入',
          componentName: 'el-input',
          labelWidth: '160px'
        },
        // 项目公司名称
        {
          label: factoringBusinessInfo.project_company,
          value: 'debtor',
          placeholder: '请输入',
          componentName: 'el-input',
          labelWidth: '110px'
        },
        // 合同名称
        {
          label: factoringBusinessInfo.contract_name,
          value: 'contractName',
          placeholder: '请输入',
          componentName: 'el-input',
          labelWidth: '140px'
        },
        // 保理金额
        {
          label: factoringBusinessInfo.factoring_amount,
          value: 'factoringMoney',
          placeholder: '请输入',
          componentName: 'el-input',
          labelWidth: '160px'
        },
        // 期数
        {
          label: factoringBusinessInfo.periods,
          value: 'specialPlanPeriods',
          placeholder: '请输入',
          componentName: 'el-input',
          labelWidth: '110px'
        },
        // 区域专员姓名
        {
          label: factoringBusinessInfo.regional_commissioner_name,
          value: 'coreAreaAttacheName',
          placeholder: '请输入',
          componentName: 'el-input',
          labelWidth: '140px'
        },
        // 区域编号
        {
          label: factoringBusinessInfo.area_number,
          value: 'regionCode',
          placeholder: '请输入',
          componentName: 'el-input',
          labelWidth: '160px'
        },
        // 区域
        {
          label: factoringBusinessInfo.area,
          value: 'coreArea',
          componentName: SelectSmallArea,
          labelWidth: '110px'
        },
        // 供应商是否下载发票
        {
          label: factoringBusinessInfo.creditor_download_invoice,
          value: 'downloadInvoiceFlag',
          componentName: 'SelectDictionary',
          dictTypeCode: 'yes_or_no_dangan',
          store: this.$store,
          labelWidth: '140px'
        }
      ],
      columns: [
        // 产品名称
        {
          prop: 'projectName',
          align: 'left',
          width: '150px',
          label: factoringBusinessInfo.product_name
        },
        // 核心企业
        {
          prop: 'coreEnterpriseName',
          align: 'left',
          width: '140px',
          label: factoringBusinessInfo.core_enterprise
        },
        // 计划管理人/再保理银行
        {
          prop: 'planOrBankName',
          align: 'left',
          width: '170px',
          label: factoringBusinessInfo.planning_manager
        },
        // 期数
        {
          prop: 'specialPlanPeriods',
          align: 'right',
          width: '70px',
          label: factoringBusinessInfo.periods
        },
        // 保理申请日期
        {
          prop: 'factoringApplyTime',
          align: 'center',
          width: '140px',
          label: factoringBusinessInfo.factoring_application_date,
          format: row => format.formatDateNull(row.factoringApplyTime)
        },
        // 区域
        {
          prop: 'coreAreaName',
          align: 'left',
          width: '150px',
          label: factoringBusinessInfo.area
        },
        // 区域编号
        {
          prop: 'regionCode',
          align: 'left',
          width: '130px',
          label: factoringBusinessInfo.area_number
        },
        // 付款确认书编号
        {
          prop: 'assetCode',
          align: 'left',
          width: '240px',
          label: factoringBusinessInfo.pay_code
        },
        // 供应商名称
        {
          prop: 'creditor',
          align: 'left',
          width: '240px',
          label: factoringBusinessInfo.creditor,
          sortable: 'custom'
        },
        // 项目公司名称
        {
          prop: 'debtor',
          align: 'left',
          width: '240px',
          label: factoringBusinessInfo.project_company,
          sortable: 'custom'
        },
        // 保理金额
        {
          prop: 'factoringMoney',
          align: 'right',
          width: '150px',
          label: factoringBusinessInfo.factoring_amount,
          format: row => format.thousandFilter(row.factoringMoney, 2),
          sortable: 'custom'
        },
        // 费率
        {
          prop: 'factoringRate',
          align: 'right',
          width: '80px',
          label: factoringBusinessInfo.factoring_rate,
          format: row => format.thousandFilter(row.factoringRate * 100, 2) + '%'
        },
        // 业务流程状态
        {
          prop: 'businessProcessStatus',
          align: 'center',
          width: '110px',
          label: factoringBusinessInfo.process_status,
          format: row => format.formatDict(this.eventDict(row.businessProcessStatus), 'ZD0085')
        },
        // 供应商盖章类型
        {
          prop: 'stampWay140',
          align: 'center',
          width: '120px',
          label: factoringBusinessInfo.creditor_seal_type,
          format: row => format.formatDict(row.stampWay140 + '', 'tracemgr_seal_type') // todo等待供应商盖章类型字典确定
        },
        // 放款日期
        {
          prop: 'loanDateFactoring',
          align: 'center',
          width: '140px',
          label: factoringBusinessInfo.lending_date,
          format: row => format.formatDateNull(row.loanDateFactoring),
          sortable: 'custom'
        },
        // 账款到期日
        {
          prop: 'dueDate',
          align: 'center',
          width: '140px',
          label: factoringBusinessInfo.amount_due_date,
          format: row => format.formatDateNull(row.dueDate)
        },
        // 保理天数
        {
          prop: 'factoringDays',
          align: 'right',
          width: '100px',
          label: factoringBusinessInfo.factoring_day
        },
        // 放款金额
        {
          prop: 'loanAmountFactoring',
          align: 'right',
          width: '150px',
          label: factoringBusinessInfo.lending_amount,
          format: row => format.thousandFilter(row.loanAmountFactoring, 2)
        },
        // 利息
        {
          prop: 'suppliersInterest',
          align: 'right',
          width: '80px',
          label: factoringBusinessInfo.interest,
          format: row => format.thousandFilter(row.suppliersInterest, 2)
        },
        // 合同名称
        {
          prop: 'basicContractName',
          align: 'left',
          width: '240px',
          label: factoringBusinessInfo.contract_name,
          sortable: 'custom'
        },
        // 合同编号
        {
          prop: 'basicContractCode',
          align: 'left',
          width: '180px',
          label: factoringBusinessInfo.contract_no
        },
        // 合同类型
        {
          prop: 'contractType',
          align: 'center',
          width: '120px',
          label: factoringBusinessInfo.contract_type,
          format: row => format.formatDict(row.contractType, 'ZD0107')
        },
        // 项目名称
        {
          prop: 'projectContractName',
          align: 'left',
          width: '240px',
          label: factoringBusinessInfo.project_name
        },
        // 发票号码
        {
          prop: 'invoiceNo',
          align: 'left',
          width: '200px',
          label: factoringBusinessInfo.invoice_number
        },
        // 收款人名称
        {
          prop: 'receiverName',
          align: 'left',
          width: '200px',
          label: factoringBusinessInfo.payee_name
        },
        // 收款人开户行
        {
          prop: 'receiverBank',
          align: 'left',
          width: '180px',
          label: factoringBusinessInfo.payee_bank
        },
        // 收款人账号
        {
          prop: 'receiverBankAccount',
          align: 'left',
          width: '280px',
          label: factoringBusinessInfo.payee_account
        },
        // 开票状态
        {
          prop: 'openInvoiceStatus',
          align: 'center',
          width: '120px',
          label: factoringBusinessInfo.invoice_status,
          format: row => format.formatDict(row.openInvoiceStatus + '', 'SCRS0111') // todo等待开票状态字典确定
        },
        // 供应商是否下载发票
        {
          prop: 'downloadInvoiceFlag',
          align: 'center',
          width: '150px',
          label: factoringBusinessInfo.creditor_download_invoice,
          format: row => format.formatDict(row.downloadInvoiceFlag + '', 'yes_or_no_dangan')
        },
        // 供应商是否补寄
        {
          prop: 'creditorSendBackFlag',
          align: 'center',
          width: '120px',
          label: factoringBusinessInfo.creditor_if_mail,
          format: row => format.formatDict(row.creditorSendBackFlag + '', 'yes_or_no_dangan')
        },
        // 项目公司是否补寄
        {
          prop: 'debtorSendBackFlag',
          align: 'center',
          width: '140px',
          label: factoringBusinessInfo.project_company_if_mail,
          format: row => format.formatDict(row.debtorSendBackFlag + '', 'yes_or_no_dangan')
        },
        // 保理专员
        {
          prop: 'customerAccountName',
          align: 'left',
          width: '100px',
          label: factoringBusinessInfo.factoring_commissioner
        },
        // 区域专员
        {
          prop: 'coreAreaAttacheName',
          align: 'left',
          width: '100px',
          label: factoringBusinessInfo.regional_commissioner
        },
        // 业务人员
        {
          prop: 'businessPersonnel',
          align: 'left',
          width: '100px',
          label: factoringBusinessInfo.operational_personne
        }
      ]
    }
  },
  methods: {
    // 排序回调
    sortChange (column, prop, order) {
      // 处理排序
      if (column.order !== null) {
        this.queryParas.sortName = column.prop.replace(/([A-Z])/g, '_$1').toLowerCase()
        this.queryParas.sortIndex = column.order.replace('ending', '')
      } else {
        delete this.queryParas.sortName
        delete this.queryParas.sortIndex
      }
      this.handleFilter()
    },
    // 查询
    handleFilters () {
      if (!regExp.number.test(this.queryParas.specialPlanPeriods) && this.queryParas.specialPlanPeriods !== '' && this.queryParas.specialPlanPeriods !== undefined) {
        this.warning('期数应为数字，请重新输入')
        this.queryParas.specialPlanPeriods = ''
        return
      }
      if (!regExp.number.test(this.queryParas.factoringMoney) && this.queryParas.factoringMoney !== '' && this.queryParas.factoringMoney !== undefined) {
        this.warning('保理金额应为数字，请重新输入')
        this.queryParas.factoringMoney = ''
        return
      }
      this.handleFilter()
    },
    // 弹窗
    showEdit (row, type) {
      if (type === '1') {
        // 订单履历
        this.orderForm = row
        this.orderForm.interestRate = this.orderForm.interestRate * 100
        this.orderForm.businessProcessStatus = this.orderForm.businessProcessStatus + ''
        if (this.orderForm.stampWay140) {
          this.orderForm.stampWay140 = this.orderForm.stampWay140 + ''
        } else {
          this.orderForm.stampWay140 = ''
        }
        this.orderForm.newFactoringRate = format.thousandFilter(this.orderForm.factoringRate * 100, 2) + '%'
        this.orderForm.factoringMoney = format.thousandFilter(this.orderForm.factoringMoney, 2)
        this.orderForm.contractType = this.orderForm.contractType.toString()
        this.orderForm.loanDateFactoring = format.formatDateNull(this.orderForm.loanDateFactoring)
        this.orderForm.dueDate = format.formatDateNull(this.orderForm.dueDate)
        this.orderVisible = true
      } else {
        // 保理信息详情
        this.factoringForm.keyId = row.keyId
        this.factoringForm.assetInfoId = row.assetInfoId
        this.factoringForm.assetPoolId = row.assetPoolId
        this.factoringForm.reMailAddressId = row.reMailAddressId
        this.factoringVisible = true
      }
    },
    // 文件下载
    notice (type, message) {
      // type资料文件分类:1:通知书,2:确权文件,
      if (this.selectedRows.length !== 0) {
        let arr = []
        let download = type === 1 ? 'notice' : 'projectconfirm'
        this.selectedRows.forEach(item => {
          arr.push(item.assetCode)
        })
        factoringBusinessInfoApi.searchApi[download](arr).then(res => {
          downFile(res)
        })
      } else {
        this.warning(message)
      }
    },
    // 票据下载
    invoice (type, message) {
      // type资料文件分类:1:费用发票,2:银行回单
      if (this.selectedRows.length !== 0) {
        let arr = []
        let download = type === 1 ? 'invoice' : 'bankreceipt'
        this.selectedRows.forEach(item => {
          arr.push(item.assetCode)
        })
        factoringBusinessInfoApi.searchApi[download](arr).then(res => {
          downFile(res)
        })
      } else {
        this.warning(message)
      }
    },
    selectRowChange (selection) {
      this.exportData.keyId = []
      selection.forEach(item => {
        this.exportData.keyId.push(item.assetInfoId)
      })
    },
    eventDict (val) {
      if (val === 0 || val === '0') {
        return ''
      } else {
        return val
      }
    },
    exportFile () {
      if (this.selectedRows.length === 0) {
        this.warning('请勾选需要导出的数据')
      } else {
        let assetInfoIds = this.selectedRows.map(it => {
          return it.assetInfoId
        })
        factoringBusinessInfoApi.searchApi.exportInfo({ assetInfoIds: assetInfoIds }).then(exRes => {
          if (exRes && exRes.data) {
            let obj = {
              map: {
                api: {}
              },
              fileName: format.formatDateNull(new Date(), 'yyyyMMdd') + '保理业务信息'
            }
            this.$set(obj.map.api, 'exportList', exRes.data)
            exportApi.exportFileTemplate.createTemplate(obj, 'CREATE', 'xiewei001').then(tepRes => {
              if (tepRes.success) {
                fileApi.file.download({ keyId: tepRes.data.keyId }).then(res => {
                  downFile(res)
                })
              } else {
                this.error(this.$i18n.messages[this.$i18n.locale].common.exportFail)
              }
            })
          } else {
            this.error(this.$i18n.messages[this.$i18n.locale].common.exportFail)
          }
        })
      }
    }
  },
  watch: {
    queryParas (val) {
      // if (val !== '' && val !== undefined) {
      //   console.log(Number(val))
      //   val = Number(val)
      // }
    }
  }
}
</script>
