<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="true" :handleFlag.sync="handleFlag" :menuFlag="false"
          :queryParas="queryParas" :sourceData.sync="sourceData" :selectTable="selectTable" :loadCount.sync="loadCount" :columns="columns"
          :showSelection="true" :otherHeight="'240'" operateBtnLayout="" :IsRight="false" :pageAll="true" :operatWidth="'200'" :selectedRows.sync="selectedRows">
          <!-- 操作工具栏 -->
          <template slot="headButton">
            <div align="right">
              <!-- 新增 -->
              <auth-button class="iconfont iconxinzeng" :size="'medium'" :label="$t('common.create')" @click="isAdd = true"
                type="primary"></auth-button>
              <!-- 批量下载资料 -->
              <auth-button class="iconfont iconycpiliangxiazai" :size="'medium'" :label="$t('supplementInfo.batchDownload')" @click="batchDonwnload"
                type="primary"></auth-button>
            </div>
          </template>
          <!-- 补出账状态 -->
          <template #supplementStatus="scope">
            <!-- 若补出状态为“补出账确认完成，账户无修改”时，则显示不修改原因 -->
            <div v-if="scope.data.row.supplementStatus === '4' && scope.data.row.noModifyReason">
                <el-popover
                  placement="left-start"
                  :title="$t('supplementInfo.noModifyReason')"
                  width="200"
                  trigger="hover"
                  :content="scope.data.row.noModifyReason">
                  <div slot="reference">
                    {{scope.data.row.supplementStatus| formatDict('bk_pkg_supplement_status')}}
                  </div>
                </el-popover>
            </div>
            <div v-else>
              {{scope.data.row.supplementStatus === formatDict(scope.data.row.supplementStatus,'bk_pkg_supplement_status') ? '' : formatDict(scope.data.row.supplementStatus,'bk_pkg_supplement_status')}}
            </div>
          </template>
          <!-- 单行操作 -->
          <el-table-column align="center" min-width="200px" :label="$t('common.operate')" fixed="right">
            <template slot-scope="scope">
              <!-- 通知客服确认 -->
              <auth-button v-if="scope.row.supplementStatus === '1'" class="iconCircle" icon="iconfont iconkefu" :title="$t('supplementInfo.noticeConfirm')" @click="operateItem(scope.row,0)"></auth-button>
              <!-- 履历 -->
              <auth-button v-if="scope.row.isExistRecord === '1'" class="iconCircle" icon="iconfont iconlvli" :title="$t('supplementInfo.history')" @click="checkInfo(scope.row)"></auth-button>
              <!-- 删除 -->
              <auth-button v-if="scope.row.supplementStatus === '1'" class="iconCircle iconCircleDel" icon="iconfont iconycjian" :title="$t('common.delete')" @click="operateItem(scope.row,1)"></auth-button>
              <!-- 下载补出账资料 -->
              <auth-button class="iconCircle" icon="iconfont iconziliao2" v-if="scope.row.supplementStatus === '5' && scope.row.fileIds && scope.row.fileIds.length > 0" :title="$t('supplementInfo.downLoad')" @click="operateItem(scope.row,2)"></auth-button>
              <!-- 下载账户证明附件 -->
              <btn-download circleIcon="iconfont iconxiazaifujian" v-if="(scope.row.supplementStatus === '3' || scope.row.supplementStatus === '4' || scope.row.supplementStatus === '5') && scope.row.blzyFileId && scope.row.blzyFileId > 0" :fileID="scope.row.blzyFileId" :title="$t('supplementInfo.accountFile')"></btn-download>
            </template>
          </el-table-column>
        </data-table>
      </template>
    </up-down-layout>
    <!-- 新增 -->
    <supplement-add-pop :visible.sync="isAdd" editModel="C" :form="form" :autoSave="false" @onSaved="addItem"></supplement-add-pop>
    <!-- 履历 -->
    <supplement-his-pop :visible.sync="isView" editModel="V" :form="form" :currentRow="currentRow"></supplement-his-pop>
  </div>
</template>
<script>
import {
  upDownLayout,
  searchForm,
  DataTable,
  amountInput,
  btnDownload,
  SelectProductName,
  authButton
} from 'newepoch-components'
import supplementAddPop from './supplementAddPop' // 新增
import supplementHisPop from './supplementHisPop' // 履历
import fileApi from '@/api/fileApi.js'
import externalApi 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: 'supplementInfoIndex',
  components: {
    searchForm,
    upDownLayout,
    DataTable,
    amountInput,
    btnDownload,
    authButton,
    supplementAddPop,
    supplementHisPop
  },
  data () {
    return {
      handleFlag: true,
      loadCount: 0,
      editModel: 'V',
      currentRow: {},
      isAdd: false, // 添加补出帐
      isView: false, // 查看履历
      templateCode: 'zcrs006',
      queryData: {},
      form: {},
      componentList: [{
        // 产品名称
        label: this.$i18n.messages[this.$i18n.locale].supplementInfo.projectName,
        disabled: false,
        value: 'productId',
        placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect,
        labelWidth: '160px',
        clearable: true,
        componentName: SelectProductName
      },
      {
        // 期数
        label: this.$i18n.messages[this.$i18n.locale].supplementInfo.specialPlanPeriods,
        disabled: false,
        value: 'specialPlanPeriods',
        placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
        labelWidth: '160px',
        clearable: true,
        componentName: amountInput
      },
      {
        // 付款确认书编号
        label: this.$i18n.messages[this.$i18n.locale].supplementInfo.assetCode,
        disabled: false,
        value: 'assetCode',
        placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
        labelWidth: '160px',
        clearable: true,
        componentName: 'el-input'
      }
      ],
      columns: [
        {
        // 产品名称
          prop: 'projectName',
          align: 'left',
          headerAlign: 'center',
          showOverflowTooltip: true,
          width: '100px',
          label: this.$i18n.messages[this.$i18n.locale].supplementInfo.projectName
        },
        {
        // 付款确认书编号
          prop: 'assetCode',
          align: 'center',
          showOverflowTooltip: true,
          width: '240px',
          label: this.$i18n.messages[this.$i18n.locale].supplementInfo.assetCode
        },
        {
        // 核心企业
          prop: 'coreEnterpriseName',
          align: 'left',
          headerAlign: 'center',
          showOverflowTooltip: true,
          width: '230px',
          label: this.$i18n.messages[this.$i18n.locale].supplementInfo.coreEnterpriseName
        },
        {
        // 计划管理人/再保理银行
          prop: 'planOrBankName',
          align: 'left',
          showOverflowTooltip: true,
          headerAlign: 'center',
          width: '180px',
          label: this.$i18n.messages[this.$i18n.locale].supplementInfo.planOrBankName
        },
        {
        // 期数
          prop: 'specialPlanPeriods',
          align: 'right',
          headerAlign: 'center',
          width: '100px',
          label: this.$i18n.messages[this.$i18n.locale].supplementInfo.specialPlanPeriods
        },
        {
        // 保理金额
          prop: 'factoringMoney',
          headerAlign: 'center',
          showOverflowTooltip: true,
          align: 'right',
          width: '115px',
          label: this.$i18n.messages[this.$i18n.locale].supplementInfo.factoringMoney,
          format: (row) => {
            return format.thousandFilter(row.factoringMoney)
          }
        },
        {
        // 放款金额
          prop: 'loanAmountFactoring',
          headerAlign: 'center',
          showOverflowTooltip: true,
          align: 'right',
          width: '115px',
          label: this.$i18n.messages[this.$i18n.locale].supplementInfo.loanAmountFactoring,
          format: (row) => {
            return format.thousandFilter(row.loanAmountFactoring)
          }
        },
        {
        // 资产对应客服信息
          prop: 'customerAccountName',
          align: 'left',
          headerAlign: 'center',
          width: '150px',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].supplementInfo.customerAccountName
        },
        {
        // 补出账原因
          prop: 'supplementReason',
          headerAlign: 'center',
          align: 'left',
          width: '171px',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].supplementInfo.supplementReason
        },
        {
        // 保理专员备注
          prop: 'blzyMemo',
          headerAlign: 'center',
          align: 'left',
          width: '171px',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].supplementInfo.blzyMemo
        },
        {
        // 补出账状态
          prop: 'supplementStatus',
          align: 'center',
          width: '130px',
          slot: true,
          label: this.$i18n.messages[this.$i18n.locale].supplementInfo.supplementStatus
        }
      ],
      sourceData: []
    }
  },
  computed: {
    // api接口
    api () {
      return externalApi.supplement
    }
  },
  mounted () {
    // 触发loadCount去请求获得表格数据
    this.handleFilter()
  },
  methods: {
    ...format,
    // 复选框禁用
    selectTable (row) {
      // 补出账状态为【5:补出账确认完成】可选
      if (row.supplementStatus === '5') {
        return true
      } else {
        return false
      }
    },
    // 新增
    addItem (e) {
      let params = {
        existBlacklist: '1',
        accounts: e.map(item => {
          return item.receiverBankAccount
        })
      }
      let arg = e.map(item => {
        return {
          assetCode: item.assetCode,
          assetInfoId: item.assetInfoId,
          assetPoolId: item.assetPoolId,
          supplementReason: item.supplementReason
        }
      })
      this.assetpkgmgrFullScreenLoading()
      externalApi.accountinfo.updateBlackBatch(params).then(res => {
        if (res.success) {
          externalApi.external.add(arg).then(res => {
            this.assetpkgmgrFullScreenLoading().close()
            if (res.success) {
              this.success(this.$t('common.addSuccess'))
              this.isAdd = false // 关闭遮罩
              this.handleFilter() // 重置列表
            } else {
              this.error(res.message)
            }
          }).catch(res => {
            this.assetpkgmgrFullScreenLoading().close()
          })
        }
      }).catch(res => {
        this.assetpkgmgrFullScreenLoading().close()
      })
    },
    // 查看履历
    checkInfo (row) {
      this.editModel = 'V'
      this.currentRow = row
      this.isView = true
    },
    // 批量下载资料
    batchDonwnload (ids) {
      let that = this
      let selectedRows = that.selectedRows
      // 是否有选中项
      if (selectedRows.length > 0) {
        // 编辑目录结构
        let fileStructure = {} // 目录结构
        let fileList = [] // 文件列表
        selectedRows.forEach(item => {
          fileStructure[`${item.assetCode}/`] = item.fileIds
          fileList.push(item.fileIds)
        })
        if (fileList.length < 1) {
          that.warning(that.$t('supplementInfo.downPrompt'))
          return false
        }
        // 配置请求参数
        let args = {
          expireTime: 50000000,
          fileStructure: fileStructure,
          flag: false
        }
        // 保存目录结构
        that.assetpkgmgrFullScreenLoading()
        externalApi.fileInfo.saveFileinfo(args).then(res => {
          if (res.success) {
            let params = {
              encoding: 'utf-8',
              uuid: res.data.keyId
            }
            // 下载
            fileApi.file.downloadByUUID(params).then(res => {
              that.assetpkgmgrFullScreenLoading().close()
              that.downFile(res, this.$t('supplementInfo.supplementFile'))
            }).catch(res => {
              that.assetpkgmgrFullScreenLoading().close()
              that.error(res.message)
            })
          }
        }).catch(res => {
          that.assetpkgmgrFullScreenLoading().close()
        })
      } else {
        that.warning(that.$t('common.selectOperateTip'))
      }
    },
    // 操作栏
    // id:supplementId;type:0 通知客服确认;1 删除;3 下载;
    operateItem (row, type) {
      let that = this
      let apiName = [that.$t('supplementInfo.noticeConfirm'), that.$t('common.delete'), that.$t('common.downLoad')]
      that.$confirm(`${that.$t('common.confirm') + apiName[type]}？`, that.$t('common.tip'), {
        type: 'warning'
      }).then(() => {
        that.assetpkgmgrFullScreenLoading()
        if (type === 2) {
          // 下载
          fileApi.file.batchDownload({ keyIds: row.fileIds }).then(res => {
            that.assetpkgmgrFullScreenLoading().close()
            that.downFile(res, `${row.assetCode}.zip`)
          }).catch(res => {
            that.assetpkgmgrFullScreenLoading().close()
            that.error(res.message)
          })
        } else {
        // 配置请求参数
        // 删除操作
          if (type === 1) {
            let params = {
              supplementIds: [row.supplementId]
            }
            let arg = {
              accountNumber: row.receiverBankAccount,
              existBlacklist: 0
            }
            // 删除黑名单
            externalApi.accountinfo.updateBlack(arg).then(res => {
              if (res.success) {
              // 删除补出帐
                externalApi.external['deleteItem'](params).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(res => {
              that.assetpkgmgrFullScreenLoading().close()
            })
          // 通知客服确认
          } else {
            let params = {
              keyId: row.supplementId,
              assetCode: row.assetCode,
              supplementStatus: '2'
            }
            // 请求操作
            externalApi.external['update'](params).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) => {
        // console.log(e)
      })
    },
    // 具名下载
    downFile (res, filename) {
      if ('msSaveOrOpenBlob' in navigator) {
        // edge和ie的下载方法
        window.navigator.msSaveOrOpenBlob(new Blob([res.data]), filename)
      } else {
        let url = window.URL.createObjectURL(new Blob([res.data]))
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', filename)
        document.body.appendChild(link)
        link.click()
        URL.revokeObjectURL(link.href)
        document.body.removeChild(link)
      }
    },
    // 提交回调
    handleSubmit (res, callback) {
      if (res.success) {
        // 回调函数
        callback && callback()
      }
    }
  }
}
</script>
