<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 :api="api"
                    ref="dataTable"
                    selectable="false"
                    v-bind="elHeightObj"
                    :handleFlag.sync="handleFlag"
                    :menuFlag="false"
                    :queryParas="queryParas"
                    :sourceData.sync="sourceData"
                    :loadCount.sync="loadCount"
                    :columns="columns"
                    :showSelection="true"
                    :otherHeight="'240'"
                    operateBtnLayout=""
                    :IsRight="false"
                    :selectTable="selectTable"
                    :pageAll="true"
                    :operatWidth="'200'"
                    @selectRowChange="selectRowChange"
                    @getTableData="getTableData">
          <template slot="headButton">
            <div align="right">
              <!-- 导出 -->
              <!-- <btn-export ref="export" btnSize="medium" :xhr="$xhr" :store="$store" :openPerms="false" :reName="$t('financialReceived.fileName')" :queryParas="exportParas" :templateCode="templateCode" :beforeExport="beforeExport"></btn-export> -->
              <auth-button size="medium" class="iconfont icondaochu" type="primary" :label="$t('common.export')" @click="handleExport"></auth-button>
              <!-- 提交 -->
              <auth-button size="medium" class="iconfont icontijiao" type="primary" :label="$t('common.submit')" @click="handleSubmit"></auth-button>
            </div>
          </template>
          <template slot="paginationLeft">
            <!-- 应收账款合计 -->
            <div class="total_price">{{$t('financialReceived.factoringMoney') + '：' + totalPrice}}</div>
          </template>
        </data-table>
      </template>
    </up-down-layout>
  </div>
</template>
<script>
import { upDownLayout, searchForm, DataTable, authButton, btnExport, SelectDictionary, SelectReFactoringBank } from 'newepoch-components'
import SelectProductName from '@/components/element/assetpkgmgr/SelectProductName'
import externalApi from '@/api/assetpkgmgr/externalApi'
import packageOperationApi from '@/api/assetpkgmgr/packageOperationApi'
import * as format from '@/filters/index'
import fileApi from '@/api/fileApi.js'
import {
  downFile
} from '@/utils/devUtils'
import BasePage from '@/pages/basePage'
import mixin from '@/pages/mixin'

export default {
  extends: new BasePage(),
  mixins: [mixin],
  name: 'financialReceivedIndex',
  components: {
    searchForm,
    upDownLayout,
    DataTable,
    btnExport,
    authButton
  },
  data () {
    return {
      handleFlag: true,
      templateCode: 'assetCodeList', // 导出文件模板code
      // 搜索表单
      queryParas: {
        pageIndex: 1,
        pageSize: 10,
        // deleteFlag: 0, // 未删除
        // backStatus: 0, // 未退单
        businessProcessStatus: '3003'
      },
      componentList: [
        {
          // 产品名称
          label: this.$i18n.messages[this.$i18n.locale].financialReceived.projectName,
          disabled: false,
          value: 'projectId',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect,
          labelWidth: '120px',
          clearable: true,
          componentName: SelectProductName
        },
        {
          // 再保理银行
          label: this.$i18n.messages[this.$i18n.locale].financialReceived.planOrBankName,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect,
          disabled: false,
          value: 'planOrBankId',
          labelWidth: '120px',
          clearable: true,
          componentName: SelectReFactoringBank
        },
        {
          // 付款确认书编号
          label: this.$i18n.messages[this.$i18n.locale].financialReceived.assetCode,
          disabled: false,
          value: 'assetCode',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
          labelWidth: '120px',
          clearable: true,
          componentName: 'el-input'
        },
        {
          // 账款到期日
          label: this.$i18n.messages[this.$i18n.locale].financialReceived.dueDate,
          value: 'dueDate',
          componentName: 'el-date-picker',
          clearable: true,
          labelWidth: '120px',
          format: 'timestamp'
        },
        {
          // 再保理资产状态
          label: this.$i18n.messages[this.$i18n.locale].financialReceived.assetStatus,
          disabled: false,
          value: 'businessProcessStatus',
          labelWidth: '120px',
          clearable: false,
          dictTypeCode: 'bk_pkg_factor_asset_status',
          componentName: SelectDictionary
        }
      ],
      columns: [
        {
          // 产品名称
          prop: 'projectName',
          align: 'left',
          headerAlign: 'center',
          width: '160px',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].financialReceived.projectName
        },
        {
          // 付款确认书编号
          prop: 'assetCode',
          align: 'center',
          width: '250px',
          sortable: true,
          label: this.$i18n.messages[this.$i18n.locale].financialReceived.assetCode
        },
        {
          // 供应商名称
          prop: 'creditor',
          align: 'left',
          headerAlign: 'center',
          width: '230px',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].financialReceived.creditor
        },
        {
          // 再保理银行
          prop: 'planOrBankName',
          align: 'left',
          headerAlign: 'center',
          width: '230px',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].financialReceived.planOrBankName
        },
        {
          // 应收账款金额（元）
          prop: 'factoringMoney',
          align: 'right',
          headerAlign: 'center',
          width: '171px',
          sortable: true,
          label: this.$i18n.messages[this.$i18n.locale].financialReceived.factoringMoney,
          format: (row) => {
            return format.thousandFilter(row.factoringMoney)
          }
        },
        {
          // 放款金额（元）
          prop: 'loanAmountFactoring',
          align: 'right',
          headerAlign: 'center',
          width: '171px',
          sortable: true,
          label: this.$i18n.messages[this.$i18n.locale].financialReceived.loanAmountFactoring,
          format: (row) => {
            return format.thousandFilter(row.loanAmountFactoring)
          }
        },
        {
          // 账款到期日
          prop: 'dueDate',
          align: 'center',
          width: '115px',
          sortable: true,
          label: this.$i18n.messages[this.$i18n.locale].financialReceived.dueDate,
          format: (row) => {
            return format.formatDateTpcModify(row.dueDate)
          }
        },
        {
          // 再保理资产状态
          prop: 'businessProcessStatus',
          align: 'center',
          width: '150px',
          label: this.$i18n.messages[this.$i18n.locale].financialReceived.assetStatus,
          format: (row) => {
            return format.formatDict(row.businessProcessStatus, 'bk_pkg_factor_asset_status')
          }
        }
      ],
      sourceData: [],
      isExport: true,
      isGet: true,
      selectRows: [] // 选中行集合
    }
  },
  computed: {
    // 合同部接受确认的接口
    api () {
      return externalApi.assetpackage
    },
    // 应收账款合计
    totalPrice () {
      // 选中项
      let selectRows = this.selectRows
      // 选中项应收账款
      let selectPrice = selectRows.length > 0 ? format.thousandFilter(Array.from(selectRows, ({ factoringMoney }) => factoringMoney).reduce((x, y) => x + y)) : '0.00'
      return selectPrice
    },
    // 导出参数
    exportParas () {
      let exportParas = this.UtilJs.cloneDeep(this.queryParas)
      delete exportParas.pageIndex
      delete exportParas.pageSize
      delete exportParas.productType
      for (let index in exportParas) {
        let item = exportParas[index]
        if (this.UtilJs.isEmpty(item)) {
          delete exportParas[index]
        }
      }
      return exportParas
    }
  },
  mounted () {
  //   // this.$nextTick(() => {
  //   // 默认选中第一个
  //   let businessProcessStatus = await new Promise((resolve, reject) => {
  //     this.$store.dispatch('GetDictionarys').then(res => {
  //       if (res && res.length > 0) {
  //         let dict = res.filter(function (dict) {
  //           return dict.dictTypeCode === 'bk_pkg_factor_asset_status'
  //         })
  //         let dictName = ''
  //         if (dict.length > 0) {
  //           dictName = dict.sort((a, b) => {
  //             return a.dictId - b.dictId
  //           })[0].dictId
  //         }
  //         resolve(dictName)
  //         // console.log(dictName)
  //       }
  //     })
  //   })
  //   this.queryParas.businessProcessStatus = businessProcessStatus
    this.handleFilter()
  //   // })
  },
  methods: {
    // 获取列表回调
    getTableData (data) {
      data = data.map(item => {
        item.businessProcessStatus = this.queryParas.businessProcessStatus
        return item
      })
      // 是否是导出
      if (!this.isGet) {
        // 去导出
        this.handleExport()
      }
    },
    // 初始化表单
    clearParam () {
      this.queryParas = {
        pageIndex: 1,
        pageSize: 10,
        // deleteFlag: 0, // 未删除
        // backStatus: 0, // 未退单
        businessProcessStatus: '3003'
      }
    },
    // 复选框禁用
    selectTable (row) {
      // 只有assetStatus为1：待接收，才可选择
      if (row.businessProcessStatus === '3003') {
        return true
      } else {
        return false
      }
    },
    // 选中操作
    selectRowChange (selectRows) {
      this.selectRows = selectRows
    },
    // 导出
    handleExport () {
      if (this.isGet) {
        this.isGet = false
        this.handleFilter()
      } else {
        this.isGet = true
        // 如果搜索列表为空
        if (this.sourceData.length > 0) {
          if (this.isExport) {
            this.$confirm(this.$t('common.confirm') + this.$t('common.export') + '？', this.$t('common.tip'), {
              type: 'warning'
            }).then((e) => {
              this.assetpkgmgrFullScreenLoading()
              packageOperationApi.exports.getDefault(this.queryParas).then(res => {
                if (res.success && res.data) {
                  fileApi.file.download({
                    keyId: res.data
                  }).then(res => {
                    this.assetpkgmgrFullScreenLoading().close()
                    downFile(res, this.$t('financialReceived.fileName'))
                  }).catch(res => {
                    this.assetpkgmgrFullScreenLoading().close()
                    this.error(res.message)
                  })
                } else {
                  this.warning(this.$t('common.nodownData'))
                }
              }).catch(res => {
                this.assetpkgmgrFullScreenLoading().close()
              })
            }).catch((e) => {})
          } else {
            this.isExport = true
          }
        } else {
          this.isExport = true
          this.warning(this.$t('common.nodownData'))
        }
      }
    },
    // 提交表单
    handleSubmit () {
      if (this.selectRows.length === 0) {
        this.warning(this.$t('common.selectOperateTip'))
        return
      }
      // 确认提示框
      this.$confirm(this.$t('common.confirm') + this.$t('financialReceived.submit') + '？', this.$t('common.tip'), {
        type: 'warning'
      }).then(() => {
        this.assetpkgmgrFullScreenLoading()
        let args = [...this.selectRows.map(item => {
          return {
            assetCode: item.assetCode,
            // keyId: item.keyId,
            bizProcessStatusCode: 3003,
            dealStatus: 2
          }
        }), ...this.selectRows.map(item => {
          return {
            assetCode: item.assetCode,
            // keyId: item.keyId,
            bizProcessStatusCode: 3004,
            dealStatus: 1
          }
        })]
        externalApi.bpm.putData(args).then(res => {
          if (res.success && res.data) {
            let params = this.selectRows.map(item => {
              return {
                'assetCode': item.assetCode,
                'assetStatus': 30,
                'hgReciverId': this.$store.getters.userId,
                'hgReciverName': this.$store.getters.user.userName,
                'hgReciveTime': new Date()
              }
            })
            externalApi.external.updateAssetpackage(params).then(res => {
              this.assetpkgmgrFullScreenLoading().close()
              if (res.success && res.data) {
                this.success(this.$t('common.updateSuccess'))
                // 刷新当前页
                this.$refs.dataTable.loadTableData()
              } else {
                this.error(this.$t('financialReceived.updateErrorTwo'))
              }
            }).catch(res => {
              this.assetpkgmgrFullScreenLoading().close()
            })
          } else {
            this.error(this.$t('financialReceived.updateError'))
          }
        }).catch(res => {
          this.assetpkgmgrFullScreenLoading().close()
        })
      }).catch((e) => {})
    }
  },
  watch: {
    editVisible (value) {
      if (!value) {
        this.handleFilter()
      }
    }
  }
}
</script>
<style scoped>
    @import '~@/styles/assetpkgmgr/packageOperation/packageOperationIndex.scss';
</style>
