<template>
  <dialog-edit
    :visible.sync="dialogVisible"
    :title="$t('chargeback.pre_refund_view')"
    editModel="V"
    :form="form"
    :api="api"
    width="1480px"
    :footerVisible="true"
    :footerBtnShow="false"
    class="pre_refund"
  >
    <el-form :model="formData" :rules="rules" ref="refundForm">
      <data-table
        :api="api"
        :headTitle="$t('chargeback.pre_refund_title')"
        operateBtnLayout
        :sourceData.sync="formData.sourceData"
        :columns="columns"
        :showPage="false"
        :showSelection="true"
        :selectedRows.sync="selectedRows"
      >
      <!-- 删除按钮 -->
      <template slot="headButton">
        <!-- <div style="height:40px;line-height:40px"> -->
          <el-row type="flex" align="bottom">
          <el-col><span>已选择的退单信息如下：共{{checkNums}}笔，应收账款金额合计{{totalPrice}}元</span></el-col>
          <el-col>
            <auth-button
            style="float: right"
            size="medium"
            type="danger"
            :label="$t('common.dels')"
            @click="delConfirm"
            icon="iconfont iconshanchu"
          ></auth-button>
          </el-col>
        </el-row>
        <!-- </div> -->
      </template>
      <!-- 子表格-->
      <template slot="index">
        <el-table-column type="expand">
          <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-scope="scope" slot="chargebackTypehead">
          <select-dictionary
            class="table_head_dict"
            :store="$store"
            size="mini"
            :exclude="exclude()"
            name="chargebackType"
            v-model="chargebackType"
            @selectChanged="changByProp(scope.data.column.property)"
            :placeholder="scope.data.column.label"
            dictTypeCode="L0005" ></select-dictionary>
        </template>
        <template slot="chargebackType" slot-scope="scope">
          <el-form-item :prop="'sourceData.' + scope.data.$index + '.chargebackType'" :rules="rules.status">
            <select-dictionary
              class="table_head_dict"
              :store="$store"
              size="mini"
              :exclude="exclude()"
              name="statusItem"
              @selectChanged="itemChange(arguments, scope.data.$index)"
              v-model="scope.data.row.chargebackType"
              :placeholder="scope.data.column.label"
              dictTypeCode="L0005" ></select-dictionary>
          </el-form-item>
        </template>
        <!-- 退单原因 -->
        <template slot-scope="scope" slot="chargebackReasonhead">
          <create-dictionary
            class="table_head_dict"
            :store="$store"
            :allowCreate="true"
            size="mini"
            name="chargebackReason"
            v-model.trim="chargebackReason"
            @selectChanged="changByProp(scope.data.column.property)"
            :placeholder="scope.data.column.label"
            dictTypeCode="L0004" ></create-dictionary>
        </template>
        <template slot="chargebackReason" slot-scope="scope">
          <el-form-item :prop="'sourceData.' + scope.data.$index + '.chargebackReason'" :rules="rules.reason">
            <create-dictionary
              class="table_head_dict"
              :store="$store"
              :allowCreate="true"
              size="mini"
              v-model.trim="scope.data.row.chargebackReason"
              :placeholder="scope.data.column.label"
              dictTypeCode="L0004" ></create-dictionary>
          </el-form-item>
        </template>
        <!-- 顺延期数 -->
        <template slot="afterPeriodshead" slot-scope="scope">
            <el-input v-model="afterPeriods"
                      class="table_head_dict"
                      @change="changByProp(scope.data.column.property)"
                      :placeholder="scope.data.column.label"
                      size="small"></el-input>
        </template>
         <template slot="afterPeriods" slot-scope="scope">
          <el-form-item :prop="'sourceData.' + scope.data.$index + '.afterPeriods'">
            <el-input v-model="scope.data.row.afterPeriods"
                      class="table_head_dict"
                      :disabled="disabledAfter(scope.data.row)"
              :placeholder="scope.data.column.label"
              size="small"></el-input>
          </el-form-item>
        </template>
      </data-table>
    </el-form>
    <div slot="footer">
      <auth-button
        type="primary"
        :label="$t('chargeback.ensure_initiating_refund')"
        :menuCode="menuId"
        :disabled="disable"
        @click="validateForm"
        size="medium"
      ></auth-button>
      <auth-button
        :label="$t('common.close')"
        :menuCode="menuId"
        @click="close()"
        size="medium"
      ></auth-button>
    </div>
    <!-- 付款确认书 -->
    <payment-confirmation :visible.sync="paymentVisible" :form="paymentItem" :api="initApi" editModel="V"></payment-confirmation>
  </dialog-edit>
</template>

<script>
import BaseEditPage from '@/pages/baseEditPage'
import { DialogEdit, dymForm, DataTable, authButton, SelectDictionary } from 'newepoch-components'
import * as format from '@/filters'
import childTable from './components/childTable'
import CreateDictionary from '@/components/element/tuidan/CreateDictionary/index'
import chargebackApi from '@/api/chargeback'
import paymentConfirmation from './paymentConfirmation'
export default {
  extends: new BaseEditPage(''),
  components: {
    DialogEdit,
    dymForm,
    childTable,
    SelectDictionary,
    CreateDictionary,
    DataTable,
    authButton,
    paymentConfirmation
  },
  props: {
    preType: {
      type: String,
      default: ''
    },
    resume_list: {
      type: [Array],
      default: () => []
    }
  },
  data () {
    return {
      paymentItem: {
        keyId: '1'
      },
      paymentVisible: false,
      rules: {
        reason: [
          { required: true, validator: this.reasonCheck, trigger: ['blur', 'change'] }
        ],
        status: [
          { validator: this.statusCheck, trigger: 'change' }
        ]
      },
      formData: {
        sourceData: []
      },
      selectedRows: [],
      chargebackReason: '',
      afterPeriods: '',
      chargebackType: '',
      columns: [
        {
          // 产品名称
          prop: 'projectName',
          align: 'left',
          width: '160px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.product_name
        },
        {
          // 退单类型
          prop: 'chargebackType',
          align: 'left',
          width: '160px',
          headslot: true,
          slot: true,
          label: this.$i18n.messages[this.$i18n.locale].chargeback.refundStyles
        },
        {
          // 核心企业
          prop: 'coreEnterpriseName',
          align: 'left',
          width: '160px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .core_enterprise,
          sortable: true
        },
        {
          // 计划管理人/再保理银行
          prop: 'planOrBankName',
          align: 'left',
          width: '180px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.planning_manager
        },
        {
          // 期数
          prop: 'specialPlanPeriods',
          align: 'right',
          width: '100px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.periods
        },
        {
          // 区域编号
          prop: 'regionCode',
          align: 'left',
          width: '160px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.area_number
        },
        {
          // 付款确认书编号
          prop: 'assetCode',
          align: 'left',
          width: '240px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.pay_code,
          sortable: true,
          slot: true
        },
        {
          // 项目公司名称
          prop: 'debtor',
          align: 'left',
          width: '210px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .project_company,
          sortable: true
        },
        {
          // 供应商名称
          prop: 'creditor',
          align: 'left',
          width: '210px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.creditor,
          sortable: true
        },
        {
          // 应收账款金额
          prop: 'factoringMoney',
          align: 'right',
          width: '160px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .account_receivable,
          format: row => format.thousandFilter(row.factoringMoney, 2)
        },
        {
          // 费率
          prop: 'factoringRate',
          align: 'right',
          width: '120px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.factoringRate,
          format: row => format.thousandFilter(row.factoringRate * 100, 2) + '%'
        },
        {
          // 账款到期日
          prop: 'dueDate',
          align: 'center',
          width: '150px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .amountMaturity,
          format: row => format.formatDateNull(row.dueDate)
        },
        {
          // 顺延后期数
          prop: 'afterPeriods',
          align: 'left',
          headslot: true,
          width: '120px',
          slot: true,
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .progressive_num
        },
        {
          // 退单原因
          prop: 'chargebackReason',
          align: 'left',
          width: '160px',
          fixed: 'right',
          headslot: true,
          slot: true,
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .chargeback_reason
        }
      ],
      loadCount: 0
    }
  },
  computed: {
    disable () {
      return this.formData.sourceData.length === 0
    },
    exclude () { // 筛选退单类型
      return function () {
        // return this.preType === 'Pause' ? [{ dictId: '4' }] : []
      }
    },
    checkNums () {
      return this.formData.sourceData.length
    },
    totalPrice () {
      let price = 0
      if (this.formData.sourceData.length) {
        this.formData.sourceData.forEach(item => {
          const { factoringMoney } = item
          price += Number(factoringMoney)
        })
      }
      return format.thousandFilter(price, 2)
    },
    api () {
      return chargebackApi.pauseApi
    },
    initApi () {
      return chargebackApi.initAPI
    }
  },
  methods: {
    itemChange (args, index, row) { // 处理退单类型不为顺延时 清空顺延周期得操作
      const val = args[0]
      if (val !== '3') {
        this.setNull(index, 'afterPeriods')
      }
    },
    setNull (index, proName) {
      this.$set(this.formData.sourceData[index], proName, '')
    },
    disabledAfter (row) {
      const { chargebackType: status } = row
      return !(status === '3')
    },
    validateForm () {
      this.$refs.refundForm.validate((valid) => {
        if (!valid) return
        this.ensure_refund()
      })
    },
    delConfirm () { // 删除操作
      let $this = this
      if (!this.selectedRows.length) {
        return this.warning('请选择')
      }
      $this.$confirm('确认删除所选中行的数据？', '提示', {
        type: 'warning'
      }).then(() => {
        $this.delItems()
      }).catch(() => {
        console.log('取消操作')
      })
    },
    delItems () { // 数据处理
      const ids = this.selectedRows.map(it => it.assetCode)
      let newArray = this.formData.sourceData.filter(item => !ids.includes(item.assetCode))
      this.formData.sourceData = newArray
    },
    changByProp (propName) { // 表头选择处理列表数据
      let value = this[propName]
      if (!value) return
      const { sourceData } = this.formData
      let list = []
      sourceData.forEach((item, index) => {
        item[propName] = value
        if (this.disabledAfter(item)) {
          item.afterPeriods = ''
        }
        list.push(item)
      })
      this.formData.sourceData = list
    },
    filterKeyId (list) {
      let newArray = []
      list.forEach(item => {
        const { keyId, ...rest } = item
        newArray.push((rest))
      })
      return newArray
    },
    // 发起退单
    ensure_refund () {
      let $this = this
      // 这个需要判断 处理数据格式
      const { sourceData: chargebackAssetInfoList } = this.formData
      let isFilterId = this.preType === 'Pause' // 暂停库的需要删除keyId
      let postList = []
      if (isFilterId) {
        postList = this.filterKeyId(chargebackAssetInfoList)
      } else {
        postList = chargebackAssetInfoList
      }
      this.api.apply(postList).then(() => {
        this.success('操作成功')
        setTimeout(() => {
          this.$emit('success')
          $this.close()
        }, 600)
      }).catch(() => {
      })
    },
    close () {
      this.dialogVisible = false
    },
    // 退单类型验证
    statusCheck (rule, value, callback) {
      if (value === '' || value === undefined) {
        callback(new Error('请选择退单类型'))
      } else if (value === null) {
        callback(new Error('仅ABS资产有顺延退单类型'))
      } else {
        callback()
      }
    },
    reasonCheck (rule, value, callback) {
      if (this.UtilJs.isEmpty(value)) {
        callback(new Error('请输入或选择退单原因'))
      } else {
        callback()
      }
    },
    showPayment (item) {
      const {
        data: { row }
      } = item
      this.paymentItem = row
      this.paymentVisible = true
    }
  },
  watch: {
    visible (val) {
      if (val) {
        let list = []
        let cosyList = JSON.parse(JSON.stringify(this.resume_list))
        cosyList.forEach(item => {
          const { afterPeriods } = item
          this.$set(item, 'chargebackType', '')
          this.$set(item, 'chargebackReason', '')
          this.$set(item, 'afterPeriods', afterPeriods || '')
          list.push(item)
        })
        this.formData.sourceData = list
      } else {
        this.$set(this.formData, 'sourceData', [])
        // 退单类型
        this.chargebackType = ''
        // 顺延期数
        this.afterPeriods = ''
        // 退单原因
        this.chargebackReason = ''
      }
    },
    formData: {
      handler (now) {
        now.sourceData.forEach(item => {
          if (item.postponeFlag === 0 && item.chargebackType === '3') {
            this.$set(this.rules.status[0], 'required', false)
            item.chargebackType = null
            this.$set(this.rules.status[0], 'required', true)
          }
        })
      },
      deep: true
    }
  }
}
</script>
