<template>
  <div class="index_view">
    <up-down-layout :headerVisible="false" :handleFlag.sync="handleFlag" >
      <Filters slot="query" @handleFilter="handleFilter" ref="Filters" @clearParam="clearParam"  :formValue.sync="queryParas" />
      <data-table
        :api="api"
        slot="table"
        :menuFlag="true"
        :headTitle="$t('chargeback.refundviewTitle')"
        operateBtnLayout
        :columns="columns"
        :loadCount.sync="loadCount"
        :queryParas="queryParas"
        :showSelection="true"
        :selectedRows.sync="selectedRows"
        :selectTable="selectTable"
        v-bind="elHeightObj"
        @sort-change="sortChange"
      >
        <template slot="index">
          <el-table-column type="expand" fixed="left">
            <template slot-scope="scope">
              <child-table :formItem="scope" />
            </template>
          </el-table-column>
        </template>
        <!-- 表格内容的自定义显示处理 -->
        <template slot="assetCode" slot-scope="scope">
          <span class="pointer_item" @click="showPayment(scope)">{{scope.data.row.assetCode}}</span>
        </template>
        <template slot="headButton">
          <div class="btngroup_right">
            <auth-button
              size="medium"
              type="primary"
              :label="$t('chargeback.bulk_operation')"
              @click="bulkOperation"
              :menuCode="menuId"
              :icon="'iconfont iconpiliangbanli'"
              :store="$store"
              :openPerms="false"
              perms="bulk_operation"
            ></auth-button>
            <!--btnDownload-->
<!--            <btn-download-->
<!--              :xhr="$xhr"-->
<!--              size="medium"-->
<!--              type="primary"-->
<!--              :fileID="downloadCode"-->
<!--              :store="$store"-->
<!--              :openPerms="false"-->
<!--              :classType="true"-->
<!--              :downloadButtonMsg="$t('chargeback.return_template')"-->
<!--              :menuCode="menuId"-->
<!--              perms="return_template"-->
<!--            ></btn-download>-->
            <auth-button size="medium" type="primary"
                         :label="$t('projectCompany.downloadmeun')"
                         :icon="'iconfont iconycxiazai'"
                         :loading="downloadFileByTemplateCodeLoading"
                         @click="downloadFileByTemplateCode"></auth-button>
            <btn-upload :store="$store"
                        btnSize="medium"
                        :icon="'iconfont icontuidan'"
                        :btnDisplay="true"
                        :menuCode="menuId"
                        :openPerms="false"
                        perms="import_refunds"
                        :uploadName="$t('chargeback.import_refunds')"
                        :uploadApi="uploadApi1"
                        @uploadSuccess="uploadSuccess"
                        type="primary"
                        class="marginleft10">
            </btn-upload >
            <!-- <btn-import
              :xhr="$xhr"
              style="margin-left: 10px"
              :store="$store"
              btnSize="small"
              :btnDisplay="true"
              :openPerms="true"
              :menuCode="menuId"
              perms="import_refunds"
              :uploadName="$t('chargeback.import_refunds')"
              :uploadApi="uploadApi"
              @importSuccess="importSuccess"
              type="primary"
            ></btn-import> -->
            <auth-button
              size="medium"
              type="primary"
              :label="$t('common.create')"
              :icon="'iconfont iconxinzeng'"
              @click="showCreateRefund()"
              :openPerms="false"
              :menuFlag="true"

              :store="$store"
              :menuCode="menuId"
              perms="create"
            ></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="200px" class="edit-group">
          <template slot-scope="scope">
            <auth-button
              class="iconCircle"
              :title="$t('chargeback.remove')"
              @click="actionsPre(scope.row, '4')"
              :icon="'iconfont iconchexiao'"
              v-if="!!scope.row.batchOperationFlag"
            ></auth-button>
            <auth-button
              class="iconCircle"
              v-if="!!scope.row.postponeFlag && scope.row.productType === 1"
              :icon="'iconfont iconshunyan'"
              :title="$t('chargeback.postpone')"
              @click="actionsPre(scope.row, '3')"
            ></auth-button>
            <auth-button
              class="iconCircle"
              v-if="!!scope.row.proposedChargeBack"
              :icon="'iconfont iconnituidan'"
              :title="$t('chargeback.quasi_refund')"
              @click="actionsPre(scope.row, '1')"
            ></auth-button>
            <auth-button
              class="iconCircle"
              :icon="'iconfont iconwanchengdingdan'"
              v-if="!!scope.row.batchOperationFlag"
              :title="$t('chargeback.completion_refund')"
              @click="actionsPre(scope.row, '2')"
            ></auth-button>
            <auth-button
              class="iconCircle"
              v-if="!!scope.row.auditResultFlag"
              :title="$t('chargeback.receive_refund_information')"
              @click="receivingInformation(scope.row)"
              :icon="'iconfont iconjieshou'"
            ></auth-button>
          </template>
        </el-table-column>
      </data-table>
    </up-down-layout>
    <!-- 付款确认书 -->
    <payment-confirmation :visible.sync="paymentVisible" :form="paymentItem" :api="api" editModel="'V'"></payment-confirmation>
    <!-- 退单暂停库一览 -->
    <refundSuspension :visible.sync="refundVisible" :form="refundItem" :api="pauseApi" :editModel="'V'"></refundSuspension>
    <!-- 接受退单资料 -->
    <receiving-refund-information :visible.sync="receivingVisible" :form="receivingItem"
                                  @editSuccess="refundSuccess" editModel="'V'"
                                  :api="dataApi"></receiving-refund-information>
    <!-- 顺延 撤销 完成退单 -->
    <pre-refund-view
      :visible.sync="preRefundVisible"
      :form="preRefundItem"
      :resume_list="resume_list"
      :api="pauseApi"
      @success="refundSuccess"
      :preType="preType"
      editModel="'V'"
    ></pre-refund-view>
    <import-result :visible.sync="importVisable"
                   :dialogTitle="$t('chargeback.import_result')"
                   editModel="'V'"
                   :form="importItem"></import-result>
  </div>
</template>
<script>
import BasePage from '@/pages/basePage'
import { upDownLayout, DataTable, authButton, btnDownload, btnImport, btnExport, btnUpload } from 'newepoch-components'
import Filters from './components/Filter'
import chargebackApi from '@/api/chargeback'
import importResult from './components/importResult'
import paymentConfirmation from './paymentConfirmation'
import refundSuspension from './refundSuspension'
import receivingRefundInformation from './receivingRefundInformation'
import preRefundView from './preRefundView'
import childTable from './components/childTable'
import * as format from '@/filters'
import { UPLOAD_API, IMPRT_SERVER_ADDRESS } from '@/constant'
import exportApi from '@/api/sysApi.js'
import { downFile } from '@/utils/devUtils'
import fileApi from '@/api/fileApi'
import mixin from '@/pages/mixin'
import { regExp } from '@/validator/index'
export default {
  name: 'factoringRefund',
  mixins: [mixin],
  extends: new BasePage(),
  components: {
    upDownLayout,
    Filters,
    btnImport,
    btnExport,
    btnUpload,
    childTable,
    preRefundView,
    importResult,
    btnDownload,
    DataTable,
    paymentConfirmation,
    authButton,
    refundSuspension,
    receivingRefundInformation
  },
  computed: {
    api () {
      return chargebackApi.initAPI
    },
    pauseApi () {
      return chargebackApi.pauseApi
    },
    dataApi () {
      return chargebackApi.dataApi
    },
    queryParams () { // 导出数据处理
      let newObj = JSON.parse(JSON.stringify(this.queryParas))
      const { factoring_application_date: date, chargebackDate } = newObj
      // 处理时间格式
      if (date && date.length) {
        const [one, two] = date
        let towAdd = two + 60 * 60 * 24 * 1000
        newObj.factoringApplyStartTime = format.formatDateNull(one)
        newObj.factoringApplyEndTime = format.formatDateNull(towAdd)
        delete newObj.factoring_application_date
      }
      if (chargebackDate) {
        newObj.chargebackDate = format.formatDateNull(chargebackDate)
      }
      if (this.UtilJs.isEmpty(this.sortWay)) {
        delete newObj.sortName
        delete newObj.sortIndex
      }
      delete newObj.pageIndex
      delete newObj.pageSize
      delete newObj.pageNumber
      this.$set(newObj, 'tenantId', this.$store.getters.tenantId)
      return newObj
    }
  },
  mounted () {
    this.downloadCode = format.formatDict('chargeback', 'L0008')
    this.$refs.Filters.handleFilter()
  },
  data () {
    return {
      downloadFileByTemplateCodeLoading: false,
      sortWay: {},
      fileId: '',
      uploadApi: IMPRT_SERVER_ADDRESS,
      uploadApi1: UPLOAD_API,
      timer: null,
      downloadCode: null,
      resume_list: [],
      importVisable: false,
      importItem: {},
      handleFlag: true,
      preRefundVisible: false,
      preRefundItem: {},
      paymentVisible: false,
      refundVisible: false,
      selectedRows: [],
      refundItem: {},
      paymentItem: {
        keyId: '1'
      },
      receivingVisible: false,
      receivingItem: {},
      queryParas: {
        sortName: '',
        sortIndex: ''
        // coreEnterpriseId: '',
        // planningManagerId: ''
      },
      preType: '',
      searchList: [],
      columns: [
        {
          // 退单状态
          prop: 'chargebackReviewStatus',
          align: 'center',
          width: '140px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.chargeback_status,
          format: row => format.formatDict(row.chargebackReviewStatus + '', 'L0003')
        },
        {
          // 退单类型
          prop: 'chargebackType',
          align: 'center',
          width: '100px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.refundStyles,
          format: row => format.formatDict(row.chargebackType + '', 'L0005')
        },
        {
          // 付款确认书编号
          prop: 'assetCode',
          align: 'left',
          width: '240px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.pay_code,
          slot: true
        },
        {
          // 核心企业
          prop: 'coreEnterpriseName',
          align: 'left',
          width: '140px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.core_enterprise,
          sortable: true
        },
        {
          // 计划管理人/再保理银行
          prop: 'planOrBankName',
          align: 'left',
          width: '170px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.planning_manager
        },
        {
          // 原始权益人
          prop: 'initialOwnersName',
          align: 'left',
          width: '130px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.initial_equity_owner
        },
        {
          // 项目公司名称
          prop: 'debtor',
          align: 'left',
          width: '240px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.project_company
        },
        {
          // 供应商名称
          prop: 'creditor',
          align: 'left',
          width: '240px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.creditor
        },
        {
          // 应收账款金额(元)
          prop: 'factoringMoney',
          align: 'right',
          width: '150px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .account_receivable_je,
          format: row => format.thousandFilter(row.factoringMoney, 2)
        },
        {
          // 账款到期日
          prop: 'dueDate',
          align: 'center',
          width: '140px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.account_maturity_date,
          format: row => format.formatDateNull(row.dueDate)
        },
        {
          // 期数
          prop: 'specialPlanPeriods',
          align: 'right',
          width: '70px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.periods
        },
        {
          // 退单人
          prop: 'chargebackPerson',
          align: 'left',
          width: '100px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.chargeback_person
        },
        {
          // 退单日期
          prop: 'chargebackDate',
          align: 'center',
          width: '170px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.chargeback_date,
          format: row => format.formatDatetime(row.chargebackDate)
        },
        {
          // 退单原因
          prop: 'chargebackReason',
          align: 'left',
          width: '200px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .chargeback_reason
        },
        {
          // 区域编号
          prop: 'regionCode',
          align: 'left',
          width: '130px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.area_number
        },
        {
          // 保理专员
          prop: 'factoringCommissioner',
          align: 'left',
          width: '100px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.factoring_commissioner
        },
        {
          // 区域专员
          prop: 'coreAreaAttacheName',
          align: 'left',
          width: '100px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.regional_commissioner
        },
        {
          // 业务人员
          prop: 'businessPersonnel',
          align: 'left',
          width: '100px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.operational_personne
        }
      ]
    }
  },
  methods: {
    downloadFileByTemplateCode () {
      this.downloadFileByTemplateCodeLoading = true
      fileApi.file.downloadFileByTemplateCode({ templateCode: 'chargeback' }).then(res => {
        downFile(res)
      }).finally(res => {
        this.downloadFileByTemplateCodeLoading = false
      })
    },
    exportFile () {
      let newObj = JSON.parse(JSON.stringify(this.queryParas))
      const { factoring_application_date: date, chargebackDate } = newObj
      // 处理时间格式
      if (date && date.length) {
        const [one, two] = date
        let towAdd = two + 60 * 60 * 24 * 1000
        newObj.factoringApplyStartTime = format.formatDateNull(one)
        newObj.factoringApplyEndTime = format.formatDateNull(towAdd)
        delete newObj.factoring_application_date
      }
      if (chargebackDate) {
        newObj.chargebackDate = format.formatDateNull(chargebackDate)
      }
      if (this.UtilJs.isEmpty(this.sortWay)) {
        delete newObj.sortName
        delete newObj.sortIndex
      }
      delete newObj.pageIndex
      delete newObj.pageSize
      delete newObj.pageNumber
      this.$set(newObj, 'tenantId', this.$store.getters.tenantId)
      this.api.exportInfo(newObj).then(exRes => {
        if (exRes && exRes.data) {
          let obj = {
            map: {
              api: {}
            },
            fileName: '保理退单一览' + format.formatDatetime(new Date(), 'yyyy年MM月dd日hh时mm分ss秒')
          }
          this.$set(obj.map.api, 'tdlcq001', exRes.data)
          exportApi.exportFileTemplate.createTemplate(obj, 'CREATE', 'tdlcq001').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)
        }
      })
    },
    selectTable (row) {
      const { batchOperationFlag } = row
      return !!batchOperationFlag
    },
    refundSuccess () {
      // this.loadCount++
      this.handleFilter()
    },
    bulkOperation () { // 批量操作
      if (!this.selectedRows.length) return this.warning('暂无操作数据')
      this.resume_list = this.selectedRows
      this.resume_list.forEach(item => {
        item.chargebackType = '1'
      })
      this.preRefundVisible = true
    },
    // 排序回调
    sortChange (column, prop, order) {
      this.sortWay = column
      this.queryParas.pageIndex = 1
      this.handleFilter()
    },
    handleFilter () { // 查询
      if (!regExp.number.test(this.queryParas.specialPlanPeriods) && this.queryParas.specialPlanPeriods !== '' && this.queryParas.specialPlanPeriods !== undefined) {
        this.warning('期数应为数字，请重新输入')
        this.queryParas.specialPlanPeriods = ''
        return
      }
      const { factoring_application_date: date } = this.queryParas
      // 处理时间格式
      if (date && date.length) {
        const [one, two] = date
        this.queryParas.factoringApplyStartTime = one
        this.queryParas.factoringApplyEndTime = two
      } else { // 不删除就会一直都在
        delete this.queryParas.factoringApplyEndTime
        delete this.queryParas.factoringApplyStartTime
      }
      // 处理排序
      if (this.sortWay.order !== null && this.sortWay.order !== undefined) {
        this.queryParas.sortName = this.sortWay.prop.replace(/([A-Z])/g, '_$1').toLowerCase()
        this.queryParas.sortIndex = this.sortWay.order.replace('ending', '')
      } else {
        delete this.queryParas.sortName
        delete this.queryParas.sortIndex
      }
      this.loadCount++
    },
    importSuccess (data) { // 导入成功的回调
      // eslint-disable-next-line no-unused-vars
      const [first, second, third, fourth, fifth, sixth, ...rest] = data
      if (!data.length) {
        return this.warning('请确认导入模板是否正确')
      }
      if ((!sixth && sixth.length !== 4) || !sixth.includes('付款确认书编号') || !sixth.includes('退单原因') || !sixth.includes('退单类型') || !sixth.includes('顺延期数（选填）') || !fifth || !fifth.length || !fifth.includes('退单导入模板')) {
        return this.warning('请确认导入模板是否正确')
      }
      // if (!sixth.includes('顺延期数（选填）')) {
      //   return this.warning('请确认导入模板是否正确')
      // }
      if (!rest || !rest.length) {
        return this.warning('数据为空')
      }
      let postList = []
      rest.forEach(item => {
        const [assetCode, chargebackReason, chargebackType, afterPeriods] = item
        let obj = {
          assetCode,
          chargebackReason,
          chargebackType,
          afterPeriods
        }
        obj.fileId = this.fileId
        postList.push(obj)
      })
      this.importSearch(postList)
    },
    importSearch (list) { // 上传成功后导入查询 判断成功获取文件ID
      let $this = this
      this.api.batchApply(list)
        .then(res => {
          $this.importVisable = true
          $this.importItem = res && res.data
        })
        .catch(e => {
          console.log(e)
        })
    },
    showPayment (item) {
      const {
        data: { row }
      } = item
      this.paymentItem = row
      this.paymentVisible = true
    },
    showCreateRefund () {
      this.refundVisible = true
    },
    receivingInformation (item) {
      this.receivingVisible = true
      this.receivingItem = item
    },
    actionsPre (item, chargebackType) {
      // 顺延 撤销 完成退单
      // this.preType = chargebackType
      this.resume_list = []
      this.resume_list[0] = Object.assign({ chargebackReason: '' }, item)
      // this.resume_list[0].chargebackType = chargebackType
      this.preRefundVisible = true
    },
    // 文件上传成功回调
    uploadSuccess (returnData, rowData, fileList) {
      let $this = this
      $this.fileId = returnData.fileID
      let index = fileList.length - 1
      let fm = new FormData()
      fm.append('file', fileList[index].raw)
      fileApi.file.importFile(fm).then(res => {
        if (res.success) {
          this.importSuccess(res.data)
        } else {
          $this.error('解析文件失败')
        }
      })
    }
  },
  destroyed () {
    this.timer = null
  }
}
</script>
