<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'">
          <template slot="headButton">
            <div align="right">
              <auth-button :size="'medium'" class="iconfont iconfangkuan1" :label="$t('sendLoanInfo.applybtn')" @click="dialogVisibleOne = true;editModel = 'V'"
                type="primary"></auth-button>
            </div>
          </template>
          <el-table-column align="center" min-width="200px" :label="$t('common.operate')" fixed="right">
            <template slot-scope="scope">
              <!-- 查看 -->
              <auth-button class="iconCircle" icon="iconfont iconview" :title="$t('common.view')" @click="checkInfo(0,scope.row)"></auth-button>
              <!-- 编辑 -->
              <auth-button v-if="scope.row.loanApplyStatus === '1' || scope.row.loanApplyStatus === '3' || scope.row.loanApplyStatus === '5' || scope.row.loanApplyStatus === '7' || scope.row.loanApplyStatus === '8'" class="iconCircle" icon="iconfont iconbianji" :title="$t('common.edit')" @click="checkInfo(1,scope.row)"></auth-button>
              <!-- 删除 -->
              <auth-button v-if="scope.row.loanApplyStatus === '1' || scope.row.loanApplyStatus === '3' || scope.row.loanApplyStatus === '5' || scope.row.loanApplyStatus === '7' || scope.row.loanApplyStatus === '8'" class="iconCircle iconCircleDel" icon="iconfont iconycjian" :title="$t('common.delete')" @click="operateItem(scope.row)"></auth-button>
              <!-- 提交复审 -->
              <auth-button v-if="scope.row.loanApplyStatus === '1' || scope.row.loanApplyStatus === '3' || scope.row.loanApplyStatus === '5' || scope.row.loanApplyStatus === '7' || scope.row.loanApplyStatus === '8'" class="iconCircle" icon="iconfont iconzhongxinshenhe" :title="$t('sendLoanInfo.submitReview')" @click="checkInfo(2,scope.row)"></auth-button>
            </template>
          </el-table-column>
        </data-table>
      </template>
    </up-down-layout>
    <!-- 放款申请组件弹窗 -->
    <loan-apply-pop ref="loanApplyPop" :visible.sync="dialogVisibleOne" :editModel="editModel" :form="form" :autoSave="false" @onSaved="saveItem"></loan-apply-pop>
    <!-- 发送放款指令弹窗 -->
    <send-loan-cmd-edit-pop :visible.sync="isSet" :editModel="editModel" :form="form" :currentRow="currentRow" @onSaved="saveItem"></send-loan-cmd-edit-pop>
    <!-- 审批系统弹窗 -->
    <approval-task-Modal :visible.sync="approvalVisible" editModel="V" :form="item"></approval-task-Modal>
  </div>
</template>
<script>
import {
  upDownLayout,
  searchForm,
  DataTable,
  SelectDictionary,
  authButton,
  amountInput
  // btnDownload
} from 'newepoch-components'
import loanApplyPop from './loanApplyPop' // 放款申请组件
import sendLoanCmdEditPop from './sendLoanCmdEditPop' // 发送放款指令
import approvalTaskModal from '@/pages/assetpkgmgr/approval/approvalTaskModal' // 审批系统
import SelectLoanBank from '@/components/element/assetpkgmgr/SelectLoanBank' // 划款银行
import sendLoanInfo from '@/api/assetpkgmgr/sendLoanInfoApi.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: 'sendLoanInfoIndex',
  components: {
    searchForm,
    upDownLayout,
    DataTable,
    authButton,
    loanApplyPop,
    sendLoanCmdEditPop,
    approvalTaskModal
  },
  data () {
    return {
      handleFlag: true,
      loadCount: 0,
      editModel: '',
      currentRow: {},
      item: {},
      needComplete: false,
      isSet: false, // 发送放款指令控件
      approvalVisible: false, // 审批弹窗控件
      dialogVisibleOne: false, // 放款申请弹窗控件
      queryData: {},
      form: {},
      componentList: [
        {
        // 划款银行
          label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.loanBankName,
          value: 'loanBankName',
          disabled: false,
          labelWidth: '110px',
          clearable: true,
          name: 'transferBankFlag',
          componentName: SelectLoanBank
        },
        {
        // 划款日期
          label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.loanDate,
          value: 'loanDate',
          disabled: false,
          componentName: 'el-date-picker',
          labelWidth: '110px',
          clearable: true,
          type: 'daterange',
          format: 'timestamp'
        },
        {
        // 放款总金额(元)
          label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.loanTotals,
          value: 'loanTotal',
          disabled: false,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
          componentName: amountInput,
          clearable: true,
          labelWidth: '110px'
        },
        {
        // 放款申请状态
          label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.loanApplyStatus,
          value: 'loanApplyStatus',
          disabled: false,
          dictTypeCode: 'bk_pkg_loan_apply_status',
          componentName: SelectDictionary,
          clearable: true,
          labelWidth: '110px'
        }
      ],
      columns: [
        {
        // 划款银行名称
          prop: 'loanBankName',
          headerAlign: 'center',
          align: 'left',
          showOverflowTooltip: true,
          width: '220px',
          label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.loanBankName
        },
        {
        // 划款账号
          prop: 'loanBankAcctId',
          align: 'center',
          width: '230px',
          label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.epositBankAccount
        },
        {
        // 划款日期
          prop: 'loanDate',
          align: 'center',
          width: '115px',
          label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.loanDate
        },
        {
        // 放款笔数
          prop: 'loanAssetCount',
          align: 'right',
          headerAlign: 'center',
          width: '100px',
          label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.loanAssetCount
        },
        {
        // 放款总金额(元)
          prop: 'loanTotal',
          headerAlign: 'center',
          align: 'right',
          showOverflowTooltip: true,
          width: '120px',
          label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.loanTotals,
          format: (row) => {
            return format.thousandFilter(row.loanTotal)
          }
        },
        {
        // 应收账款总金额(元)
          prop: 'factoringMoneyTotal',
          headerAlign: 'center',
          align: 'right',
          showOverflowTooltip: true,
          width: '150px',
          label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.factoringMoneyTotal,
          format: (row) => {
            return format.thousandFilter(row.factoringMoneyTotal)
          }
        },
        {
        // 放款申请时间
          prop: 'loanApplyDate',
          align: 'center',
          width: '171px',
          label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.loanApplyDate
        },
        {
        // 放款申请状态
          prop: 'loanApplyStatus',
          align: 'center',
          width: '150px',
          label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.loanApplyStatus,
          format: (row) => {
            return format.formatDict(row.loanApplyStatus, 'bk_pkg_loan_apply_status')
          }
        }
      ],
      sourceData: []
    }
  },
  computed: {
    // api接口
    api () {
      return sendLoanInfo.sendLoanInfo
    },
    // 设置提交表单api地址
    apiUrl () {
      let $this = this
      let url = ''
      switch ($this.editModel) {
        case 'S':
          url = 'review'
          break
        case 'E':
          url = 'update'
          break
        case 'C':
          url = 'reCheck'
          break
        default:
          break
      }
      return url
    },
    // 设置返回信息提示
    toast () {
      let $this = this
      let toast = ''
      switch ($this.editModel) {
        case 'S':
          toast = $this.$t('common.saveBtnSuccessfully')
          break
        case 'E':
          toast = $this.$t('common.updateSuccess')
          break
        case 'C':
          toast = $this.$t('common.review') + $this.$t('common.successfully')
          break
        default:
          break
      }
      return toast
    }
  },
  mounted () {
    this.handleFilter()
  },
  methods: {
    // 提交表单
    saveItem (e) {
      let $this = this
      $this.assetpkgmgrFullScreenLoading()
      $this.api[$this.apiUrl](e).then(res => {
        $this.assetpkgmgrFullScreenLoading().close()
        if (res.success) {
          $this.success($this.toast)
          $this.isSet = false // 关闭遮罩
          // 重置列表
          $this.$refs.dataTable.loadTableData()
        } else {
          $this.error(res.message)
        }
      }).catch(res => {
        $this.assetpkgmgrFullScreenLoading().close()
      })
    },
    // 查看和编辑
    checkInfo (type, row) {
      let types = ['V', 'E', 'C']
      this.editModel = types[type]
      if (type === 2) {
        this.$confirm(this.$t('sendLoanInfo.submitReviewPropmt'), this.$t('common.tip'), {
          type: 'warning'
        }).then(() => {
          this.assetpkgmgrFullScreenLoading()
          // 调用复审接口
          sendLoanInfo.sendLoanInfo.reCheck({
            keyId: row.keyId
          }).then(res => {
            this.assetpkgmgrFullScreenLoading().close()
            if (res.success) {
              this.success(this.$t('common.updateSuccess'))
              // 重置列表
              this.$refs.dataTable.loadTableData()
            } else {
              this.error(res.message)
            }
          }).catch(res => {
            this.assetpkgmgrFullScreenLoading().close()
          })
        }).catch((e) => {})
      } else {
        this.currentRow = row
        if (type === 0 && row.loanApplyStatus !== '1') {
          let processInstanceId = row.processInstanceId
          // 根据keyId去取流程列表
          this.assetpkgmgrFullScreenLoading()
          externalApi.todotask.getProcessInfoWithApprovalResult({
            bizId: [row.keyId]
          }).then(res => {
            this.assetpkgmgrFullScreenLoading().close()
            if (res.success) {
              // 流程列表
              let datas = res.data[0].instances
              if (datas.length > 0) {
                // 获取当前流程
                let instances = datas.filter(item => {
                  return item.instanceId === processInstanceId
                })[0].data
                // 审批意见
                let audit = []
                // 待办理
                let waiting = instances.filter(item => {
                  return item.taskStatus === '2'
                })
                // 待领取
                let draw = instances.filter(item => {
                  return item.taskStatus === '1'
                })
                // 办理完成
                let finish = instances.filter(item => {
                  return item.taskStatus === '3'
                })
                // 判断目前处于的审批节点，优先级为：待办理 > 待领取 > 办理完成（同状态取审核时间reviewTime最近的）
                if (waiting.length > 0) { // 审核任务待办理
                // 对比审核时间取最近
                  let reviewTimes = waiting.reduce((prev, current) => {
                    return new Date(prev.reviewTime).getTime() > new Date(current.reviewTime).getTime() ? prev : current
                  })
                  audit = reviewTimes
                } else if (draw.length > 0) { // 审核任务待领取
                  audit = draw[0]
                } else if (finish.length > 0) { // 审核任务办理完成
                // 对比审核时间取最近
                  let reviewTimes = finish.reduce((prev, current) => {
                    return new Date(prev.reviewTime).getTime() > new Date(current.reviewTime).getTime() ? prev : current
                  })
                  audit = reviewTimes
                } else { // 审核任务未领取
                  this.warning(this.$t('sendLoanInfo.waitingTip'))
                  return false
                }
                // console.log(audit)
                this.item = Object.assign({}, audit, row)
                this.item.instanceid = processInstanceId
                this.approvalVisible = true
              } else {
                this.warning(this.$t('sendLoanInfo.waitingTip'))
              }
            }
          }).catch(res => {
            this.assetpkgmgrFullScreenLoading().close()
          })
        } else {
          // 打开发送指令
          this.isSet = true
        }
      }
    },
    // 单行操作栏
    operateItem (row) {
      let that = this
      that.$confirm(that.$t('common.delTip'), that.$t('common.tip'), {
        type: 'warning'
      }).then(() => {
        // 调用删除接口
        that.assetpkgmgrFullScreenLoading()
        that.api.deleteItem({
          keyId: row.keyId,
          productType: row.productType
        }).then(function (res) {
          that.assetpkgmgrFullScreenLoading().close()
          if (res.success) {
            that.success(that.$t('common.delSuccess'))
            // 重置表格
            that.$refs.dataTable.loadTableData()
          }
        }).catch(res => {
          this.assetpkgmgrFullScreenLoading().close()
        })
      }).catch((e) => {})
    }
  },
  watch: {
    editVisible (value) {
      if (!value) {
        this.handleFilter()
      }
    }
  }
}
</script>
