<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" />
      <el-form :model="formData" :rules="rules" ref="examineForm" slot="table">
        <data-table
          :api="api"
          :headTitle="$t('chargeback.audit_list')"
          operateBtnLayout
          :columns="columns"
          :menuFlag="true"
          :loadCount.sync="loadCount"
          :sourceData.sync="formData.sourceData"
          :queryParas="queryParas"
          :showSelection="true"
          :selectedRows.sync="selectedRows"
          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="reviewOpinion" slot-scope="scope">
            <el-form-item :prop="'sourceData.' + scope.data.$index + '.reviewOpinion'" :rules="rules.reviewOpinion">
              <el-input v-model.trim="scope.data.row.reviewOpinion"
                        class="table_head_dict"
                        :placeholder="scope.data.column.label"
                        :maxlength="200"
                        size="small"></el-input>
            </el-form-item>
          </template>
          <template slot="headButton">
            <div class="btngroup_right">
              <auth-button
                size="medium"
                type="primary"
                :label="$t('chargeback.batch_pass')"
                @click="batchPass('1')"
                :menuCode="menuId"
                :icon="'iconfont icontongguo'"
                perms="batch_pass"
              ></auth-button>
              <auth-button
                size="medium"
                style="margin-left: 10px"
                type="primary"
                :label="$t('chargeback.batch_no_pass')"
                :icon="'iconfont iconbutongguo'"
                @click="batchPass('2')"
                :menuCode="menuId"
                perms="batch_no_pass"
              ></auth-button>
            </div>
          </template>
          <el-table-column fixed="right" align="center" label="操作" width="120px" class="edit-group">
            <template slot-scope="scope">
              <auth-button
                size="small"
                class="iconCircle"
                :title="$t('chargeback.pass')"
                @click="batchPassItem(null,scope.row, '1')"
                :menuCode="menuId"
                :icon="'iconfont icontongguo1'"
                perms="pass"
              ></auth-button>
              <auth-button
                size="small"
                class="iconCircle"
                @click="batchPassItem(scope.$index ,scope.row, '2')"
                :title="$t('chargeback.no_pass')"
                :menuCode="menuId"
                :icon="'iconfont iconno_pass'"
                perms="no_pass"
              ></auth-button>
            </template>
          </el-table-column>
        </data-table>
      </el-form>
    </up-down-layout>
    <!-- 付款确认书 -->
    <payment-confirmation :visible.sync="paymentVisible" :form="paymentItem" :api="api" editModel="V"></payment-confirmation>
    <audit-opinion :visible.sync="auditVisible" :form="auditItems" :api="api" :auditCode="auditCode" @successAudit="successAudit" editModel="V"></audit-opinion>
  </div>
</template>
<script>
import BasePage from '@/pages/basePage'
import { upDownLayout, DataTable, authButton, btnDownload, btnImport, btnExport } from 'newepoch-components'
import Filters from './components/Filter'
import chargebackApi from '@/api/chargeback'
import * as format from '@/filters'
import childTable from '../factoring-refund/components/childTable'
import auditOpinion from './auditOpinion'
import paymentConfirmation from '../factoring-refund/paymentConfirmation'
import mixin from '@/pages/mixin'
import { regExp } from '@/validator/index'
export default {
  name: 'examineRefund',
  mixins: [mixin],
  extends: new BasePage(),
  components: {
    upDownLayout,
    Filters,
    auditOpinion,
    btnImport,
    btnExport,
    childTable,
    btnDownload,
    DataTable,
    authButton,
    paymentConfirmation
  },
  computed: {
    api () {
      return chargebackApi.auditApi
    }
  },
  data () {
    let validatePass = (rule, value, callback) => {
      let strArray = rule.field.split('.')
      let currentIndex = strArray[1]
      if (Number(currentIndex) === this.passIndex && !value) {
        callback(new Error('请输入审核意见'))
      } else {
        callback()
      }
    }
    return {
      sortWay: {},
      paymentItem: {},
      paymentVisible: false,
      handleFlag: true,
      auditItems: {},
      auditVisible: false,
      auditCode: null,
      passIndex: null,
      rules: {
        reviewOpinion: [
          { validator: validatePass, trigger: 'change' }
        ]
      },
      formData: {
        sourceData: []
      },
      selectedRows: [],
      queryParas: {
      },
      columns: [
        {
        // 产品名称
          prop: 'projectName',
          align: 'left',
          width: '150px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.product_name
        }, {
        // 核心企业
          prop: 'coreEnterpriseName',
          align: 'left',
          width: '130px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .core_enterprise,
          sortable: 'custom'
        }, {
        // 计划管理人/再保理银行
          prop: 'planOrBankName',
          align: 'left',
          width: '170px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .planning_manager
        }, {
        // 付款确认书编号
          prop: 'assetCode',
          align: 'left',
          width: '240px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.pay_code,
          slot: true,
          sortable: 'custom'
        }, {
        // 项目公司名称
          prop: 'debtor',
          align: 'left',
          width: '240px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .project_company,
          sortable: 'custom'
        }, {
        // 供应商名称
          prop: 'creditor',
          align: 'left',
          width: '240px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.creditor,
          sortable: 'custom'
        }, {
        // 区域编号
          prop: 'regionCode',
          align: 'left',
          width: '130px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.area_number
        }, {
        // 应收账款金额(元)
          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: '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: 'chargebackDate',
          align: 'center',
          width: '140px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .chargeback_date,
          format: row => format.formatDateNull(row.chargebackDate)
        }, {
        // 保理申请日期
          prop: 'dueDate',
          align: 'center',
          width: '140px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .factoring_application_date,
          format: row => format.formatDateNull(row.dueDate)
        }, {
        // 原始期数
          prop: 'specialPlanPeriods',
          align: 'right',
          width: '80px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .primeval_periods
        }, {
        // 退单原因
          prop: 'chargebackReason',
          align: 'left',
          width: '200px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .chargeback_reason
        }, {
        // 退单类型
          prop: 'chargebackType',
          align: 'center',
          width: '100px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.refundStyles,
          format: row => format.formatDict(row.chargebackType, 'L0005'),
          sortable: true
        }, {
        // 退单人
          prop: 'chargebackPerson',
          align: 'left',
          width: '100px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .chargeback_person
        }, {
        // 审核意见
          prop: 'reviewOpinion',
          align: 'left',
          width: '180px',
          slot: true,
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .audit_opinion
        }]
    }
  },
  methods: {
    // 付款确认书
    showPayment (item) {
      const {
        data: { row }
      } = item
      this.paymentItem = row
      this.paymentVisible = true
    },
    loadData () {
      this.loadCount++
    },
    successAudit (reason) {
      let list = []
      this.selectedRows.forEach(item => {
        const { keyId: chargebackAssetId } = item
        item.chargebackAssetId = chargebackAssetId
        item.reviewStatus = this.auditCode
        item.reviewOpinion = reason
        list.push(item)
      })
      this.api.creates(list).then(res => {
        if (res.success) {
          this.success('操作成功')
          this.loadData()
        }
      }).catch(() => {
      })
    },
    batchPass (code) { // 批量操作
      if (!this.selectedRows.length) return this.warning('暂无操作数据')
      this.auditVisible = true
      this.auditCode = code
      // 1 通过
      // 2 不通过
    },
    auditItem (item, code) { // 单条数据处理
      const { keyId: chargebackAssetId } = item
      item.chargebackAssetId = chargebackAssetId
      item.reviewStatus = code
      // delete item.keyId
      this.api.creates([item]).then(res => {
        if (res.success) {
          this.success('操作成功')
          this.loadData()
        }
      }).catch(() => {
      })
    },
    batchPassItem (index, item, code) { // 单条审核
      this.passIndex = index
      if (index === null) { // 通过不校验
        this.auditItem(item, code)
      } else { // 不通过校验
        let $this = this
        this.$refs.examineForm.validate((val) => {
          if (val) {
            $this.auditItem(item, code)
          } else {
            $this.warning('请输入审核意见')
          }
        })
      }
    },
    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.chargebackStartDate = one
        this.queryParas.chargebackEndDate = two
      } else { // 不删除就会一直都在
        delete this.queryParas.chargebackEndDate
        delete this.queryParas.chargebackStartDate
      }
      // 处理排序
      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.loadData()
    },
    // 排序回调
    sortChange (column, prop, order) {
      this.sortWay = column
      this.queryParas.pageIndex = 1
      this.handleFilter()
    }
  }
}
</script>
