<template>
  <div class="recevie_refund">
    <dialog-edit
      :visible.sync="dialogVisible"
      :title="$t('chargeback.receive_refund_information')"
      :editModel="editModel"
      :form="form"
      :api="api"
      width="80%"
      :footerVisible="true"
      :footerBtnShow="false"
    >
      <el-form :model="formData" ref="refundForm" :rules="rules">
        <dym-form
          :menuCode="menuId"
          :formValue.sync="formData.queryParas"
          :componentList="searchList"
        ></dym-form>
        <data-table
          :api="api"
          :headTitle="$t('chargeback.receive_refund_information_list')"
          operateBtnLayout
          :sourceData.sync="formData.sourceData"
          :columns="columns"
          :showPage="false"
        >
          <!-- 接受类型 -->
          <template slot-scope="scope" slot="dataTypehead">
            <select-dictionary
              class="table_head_dict"
              :store="$store"
              size="mini"
              name="dataType"
              v-model="dataType"
              @selectChanged="changByProp(scope.data.column.property)"
              :placeholder="scope.data.column.label"
              dictTypeCode="L0001"></select-dictionary>
          </template>
          <template slot="dataType" slot-scope="scope">
            <el-form-item :prop="'sourceData.' + scope.data.$index + '.dataType'" :rules="rules.dataType">
              <select-dictionary
                class="table_head_dict"
                :store="$store"
                size="mini"
                name="statusItem"
                v-model="scope.data.row.dataType"
                :placeholder="scope.data.column.label"
                @selectChanged="changDataType"
                dictTypeCode="L0001"></select-dictionary>
            </el-form-item>
          </template>
          <!-- 来源 -->
          <template slot-scope="scope" slot="sourcehead">
            <select-dictionary
              class="table_head_dict"
              :store="$store"
              size="mini"
              name="source"
              v-model="source"
              @selectChanged="changByProp(scope.data.column.property)"
              :placeholder="scope.data.column.label"
              :exclude="exclude(dataType)"
              :reload="sourceHeadReload"
              dictTypeCode="L0006"></select-dictionary
              >
          </template>
          <template slot="source" slot-scope="scope">
            <el-form-item :prop="'sourceData.' + scope.data.$index + '.source'" :rules="rules.selectNull">
              <select-dictionary
                class="table_head_dict"
                :store="$store"
                size="mini"
                name="sourceItem"
                v-model="scope.data.row.source"
                :placeholder="scope.data.column.label"
                :exclude="exclude(scope.data.row.dataType)"
                :reload="sourceHeadReload"
                dictTypeCode="L0006"></select-dictionary>
            </el-form-item>
          </template>
          <!-- 来源人 -->
          <template slot="sourceUserId" slot-scope="scope">
            <el-form-item :prop="'sourceData.' + scope.data.$index + '.sourceUserId'" :rules="scope.data.row.source === '3' || scope.data.row.source === '5' ? rules.selectUserNull : []">
              <source-user v-model="scope.data.row.sourceUserId" class="table_head_dict"
                           :currentCode="scope.data.row.source"
                           :disabled="sourceDisabled(scope.data.row.source)"
                           @set-null="setNull(scope.data.$index)"
                           :placeholder="scope.data.column.label"></source-user>
            </el-form-item>
          </template>
          <!-- 本份分数 -->
          <template slot="validNum" slot-scope="scope">
            <el-form-item :prop="'sourceData.' + scope.data.$index + '.validNum'" :rules="rules.validNum"
            >
              <el-input
                v-model="scope.data.row.validNum"
                :placeholder="scope.data.column.label"
                size="small"
              ></el-input>
            </el-form-item>
          </template>
          <!-- 备注 -->
          <template slot="memo" slot-scope="scope">
            <el-form-item :prop="'sourceData.' + scope.data.$index + '.memo'">
              <el-input
                v-model="scope.data.row.memo"
                :placeholder="scope.data.column.label"
                size="small"
                maxlength="200"
              ></el-input>
            </el-form-item>
          </template>
          <template slot="headButton">
            <div style="display: flex;margin-top: 10px">
              <el-form-item prop="expressCompany" :label="$t('chargeback.courier_company')"  :rules="rules.pickRules" style="display: flex" >
                <select-dictionary
                  :store="$store"
                  name="company"
                  v-model="formData.expressCompany"
                  dictTypeCode="L0007"></select-dictionary>
              </el-form-item>
              <el-form-item prop="expressNumber" :label="$t('chargeback.courier_number')" :rules="rules.inputRules" style="display: flex; margin-left: 24px">
                <el-input
                  :store="$store"
                  :maxlength="50"
                  v-model="formData.expressNumber"
                ></el-input>
              </el-form-item>
            </div>
          </template>
          <el-table-column fixed="right" align="center" label="操作" width="100px" class="edit-group">
            <template slot-scope="scope">
              <auth-button
                :title="$t('chargeback.details')"
                class="iconCircle"
                icon="iconfont iconmore"
                @click="refundDetails(scope.row)"
                :menuCode="menuId"
                perms="details"
              ></auth-button>
            </template>
          </el-table-column>
        </data-table>
      </el-form>
      <div slot="footer">
        <auth-button
          type="primary"
          size="medium"
          :label="$t('chargeback.resave')"
          @click="submit"
        ></auth-button>
        <auth-button
          size="medium"
          :label="$t('common.close')"
          @click="close()"
        ></auth-button>
      </div>
    </dialog-edit>
    <refund-details :visible.sync="detailVisible" :form="detailItem" :api="api" editModel="V"></refund-details>
  </div>
</template>

<script>
import BaseEditPage from '@/pages/baseEditPage'
import refundDetails from './refundDetails'
import SourceUser from '@/components/element/tuidan/SourceUser/index'
import { regExp } from '@/validator/index'
import chargebackApi from '@/api/chargeback'
import {
  SelectDictionary,
  DialogEdit,
  dymForm,
  DataTable,
  authButton
} from 'newepoch-components'

const cols = [24, 12, 12, 8]
const SOURCE_TYPES = ['3', '4', '5'] // 显示可以选择的来源人
export default {
  extends: new BaseEditPage(''),
  components: {
    DialogEdit,
    SourceUser,
    dymForm,
    SelectDictionary,
    refundDetails,
    DataTable,
    authButton
  },
  data () {
    let validatePick = (rule, value, callback) => { // 校验select
      if (this.isquired && !value) {
        callback(new Error('请选择'))
      } else {
        callback()
      }
    }
    let validateInput = (rule, value, callback) => { // 校验input
      if (this.isquired && !value) {
        callback(new Error('请输入'))
      } else {
        callback()
      }
    }
    let validateNum = (rule, value, callback) => {
      let strArray = rule.field.split('.')
      let currentIndex = strArray[1] // 当前的数值
      const { sourceData } = this.formData
      let indexType = sourceData[Number(currentIndex)].dataType // 判断是否选择了类型
      let remainNumber = sourceData[Number(currentIndex)].remainingData // 剩余份数
      if (!indexType || indexType === '0') { // 接受不做校验
        if (value <= 0) {
          callback(new Error('请输入大于0的整数'))
        } else if (value > 127) {
          callback(new Error('输入值应小于等于127份'))
        } else {
          callback()
        }
      } else {
        if (!value) {
          callback(new Error('请输入'))
        } else if (value <= 0) {
          callback(new Error('请输入大于0的整数'))
        } else if (value > 127) {
          callback(new Error('输入值应小于等于127份'))
        } else if (value - remainNumber > 0) {
          callback(new Error('输入值应小于剩余份数'))
        } else {
          callback()
        }
      }
    }
    let validateNull = (rule, value, callback) => {
      let strArray = rule.field.split('.')
      let currentIndex = strArray[1] // 当前的数值
      const { sourceData } = this.formData
      let indexType = sourceData[Number(currentIndex)].dataType // 判断是否选择了类型
      if (!indexType) {
        callback()
      } else {
        if (!value) {
          callback(new Error('请选择'))
        } else {
          callback()
        }
      }
    }
    let validateUserNull = (rule, value, callback) => {
      console.log(this.formData)
      let strArray = rule.field.split('.')
      let currentIndex = strArray[1] // 当前的数值
      const { sourceData } = this.formData
      let indexType = sourceData[Number(currentIndex)].dataType // 判断是否选择了类型
      let indexSource = sourceData[Number(currentIndex)].source // 判断来源类型使用
      if (!indexType) {
        callback()
      } else {
        if (!value && SOURCE_TYPES.indexOf(indexSource) !== -1) {
          callback(new Error('请选择'))
        } else {
          callback()
        }
      }
    }
    return {
      type: '', // 接收类型
      detailVisible: false,
      sourceHeadReload: false,
      rules: {
        dataType: [{ required: true, message: '必填', trigger: 'change' }],
        pickRules: [
          { required: true, message: '必填', trigger: 'blur' },
          { validator: validatePick, trigger: 'change' }
        ],
        inputRules: [
          { validator: validateInput, trigger: 'change' }
        ],
        validNum: [
          { required: true, message: '必填', trigger: 'blur' },
          { validator: validateNum, trigger: 'change' }
        ],
        selectNull: [
          // { required: true, message: '必填', trigger: 'blur' },
          { validator: validateNull, trigger: 'change' }
        ],
        selectUserNull: [
          { validator: validateUserNull, trigger: 'change' }
        ]
      },
      detailItem: {},
      sourceUserId: '',
      source: '',
      dataType: '',
      formData: {
        expressCompany: null,
        expressNumber: null,
        sourceData: [],
        queryParas: {}
      },
      searchList: [
        {
          // 供应商名称
          label: this.$i18n.messages[this.$i18n.locale].chargeback.creditor,
          value: 'creditor',
          disabled: true,
          placeholder: '请输入',
          componentName: 'el-input',
          cols,
          labelWidth: '85px'
        },
        {
          // 项目公司名称
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .project_company,
          disabled: true,
          value: 'debtor',
          placeholder: '请输入',
          componentName: 'el-input',
          cols,
          labelWidth: '160px'
        },
        {
          // 付款确认书编号
          label: this.$i18n.messages[this.$i18n.locale].chargeback.pay_code,
          value: 'assetCode',
          disabled: true,
          placeholder: '请输入',
          componentName: 'el-input',
          cols,
          labelWidth: '110px'
        },
        {
          // 核心企业
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .core_enterprise,
          disabled: true,
          value: 'coreEnterpriseName',
          placeholder: '请输入',
          componentName: 'el-input',
          cols,
          labelWidth: '85px'
        },
        {
          // 计划管理人/再保理银行
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .planning_manager,
          disabled: true,
          value: 'planOrBankName',
          placeholder: '请输入',
          componentName: 'el-input',
          cols,
          labelWidth: '160px'
        },
        {
          // 原始权益人
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .initial_equity_owner,
          disabled: true,
          value: 'initialOwnersName',
          placeholder: '请输入',
          componentName: 'el-input',
          cols,
          labelWidth: '110px'
        },
        {
          // 账款到期日
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .account_maturity_date,
          disabled: true,
          value: 'dueDate',
          placeholder: '请输入',
          componentName: 'el-date-picker',
          cols,
          labelWidth: '85px'
        },
        {
          // 退单人
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .chargeback_person,
          value: 'chargebackPerson',
          disabled: true,
          placeholder: '请输入',
          componentName: 'el-input',
          cols,
          labelWidth: '160px'
        },

        {
          // 退单日期
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .chargeback_date,
          value: 'chargebackDate',
          disabled: true,
          placeholder: '请输入',
          componentName: 'el-date-picker',
          cols,
          labelWidth: '110px'
        },
        {
          // 退单原因
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .chargeback_reason,
          value: 'chargebackReason',
          disabled: true,
          placeholder: '请输入',
          componentName: 'el-input',
          cols,
          labelWidth: '85px'
        }
      ],
      // searchList1: [
      //   {
      //     // 快递公司
      //     label: this.$i18n.messages[this.$i18n.locale].chargeback
      //       .courier_company,
      //     value: 'expressCompany',
      //     placeholder: '请输入',
      //     dictTypeCode: 'L0007',
      //     store: this.$store,
      //     componentName: 'SelectDictionary',
      //     cols: [10, 10, 10, 10],
      //     labelWidth: '160px'
      //   },
      //   {
      //     // 快递单号
      //     label: this.$i18n.messages[this.$i18n.locale].chargeback
      //       .courier_number,
      //     value: 'expressNumber',
      //     placeholder: '请输入',
      //     componentName: 'el-input',
      //     cols: [10, 10, 10, 10],
      //     labelWidth: '160px'
      //   }
      // ],
      columns: [
        {
          // 接收类型
          prop: 'dataType',
          align: 'left',
          headslot: true,
          width: '160px',
          slot: true,
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .receiving_type
        },
        {
          // 资料名称
          prop: 'fileName',
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.data_name
        },
        {
          // 需求份数
          prop: 'needNum',
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].chargeback
            .requirements_num
        },
        {
          // 本次份数
          prop: 'validNum',
          align: 'left',
          slot: true,
          label: this.$i18n.messages[this.$i18n.locale].chargeback.current_num,
          width: '100'
        },
        {
          // 归还份数
          prop: 'refundData',
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.refund_num
        },
        {
          // 剩余份数
          prop: 'remainingData',
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.rest_num
        },
        {
          // 来源
          prop: 'source',
          align: 'left',
          headslot: true,
          slot: true,
          width: '160px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.source
        },
        {
          // 来源人
          prop: 'sourceUserId',
          align: 'left',
          slot: true,
          width: '160px',
          label: this.$i18n.messages[this.$i18n.locale].chargeback.source_person
        },
        {
          // 备注
          prop: 'memo',
          align: 'left',
          slot: true,
          label: this.$i18n.messages[this.$i18n.locale].chargeback.remarks
        }
      ],
      loadCount: 0
    }
  },
  methods: {
    submit () {
      let $this = this
      this.$refs['refundForm'].validate((val) => {
        if (val) {
          $this.sendData()
        }
      })
    },
    sendData () {
      const { sourceData, expressCompany: company, expressNumber: number } = this.formData
      const { assetCode, assetInfoId, assetPoolId } = this.form
      let list = []
      sourceData.forEach(item => {
        const { source, sourceUserId } = item
        if (source === '1') {
          item.expressCompany = company
          item.expressNumber = number
        } else {
          delete item.expressCompany
          delete item.expressNumber
        }
        if (sourceUserId === '') {
          delete item.sourceUserId
        }
        item.assetCode = assetCode
        item.assetInfoId = assetInfoId
        item.assetPoolId = assetPoolId
        const { dataType } = item
        if (dataType !== '') {
          list.push(item)
        }
      })
      this.api.apply(list).then(res => {
        this.success('提交成功')
        this.$emit('editSuccess')
        this.close()
      }).catch(() => {
        this.error('提交失败')
      })
    },
    changByProp (propName) {
      let value = this[propName]
      const { sourceData } = this.formData
      let list = sourceData.map(item => {
        item[propName] = value
        return item
      })
      this.formData.sourceData = list
      this.sourceHeadReload = !this.sourceHeadReload
    },
    // 重新加载来源
    changDataType () {
      this.sourceHeadReload = !this.sourceHeadReload
    },
    sourceDisabled (type) {
      let index = SOURCE_TYPES.indexOf(type)
      return index === -1
    },
    setNull (index) { // 切换来源时清空来源人
      this.$set(this.formData.sourceData[index], 'sourceUserId', '')
    },
    close () {
      this.dialogVisible = false
    },
    refundDetails (item) {
      const { assetCode } = this.form
      this.detailVisible = true
      item.assetCode = assetCode
      this.detailItem = item
    },
    filterData (item) {
      const { dueDate, chargebackDate, ...rest } = item
      let newObject = {
        ...rest,
        dueDate: (Number(dueDate) === -2209017600000 || dueDate === '1900-01-01') ? '' : dueDate,
        chargebackDate: (Number(chargebackDate) === -2209017600000 || chargebackDate === '1900-01-01') ? '' : chargebackDate
      }
      return newObject
    },
    // 列表数据请求
    loadData () {
      const { assetCode, assetInfoId, assetPoolId } = this.form
      this.api.getList({ assetCode, assetInfoId, assetPoolId }).then(res => {
        this.setFormData(res.data)
      }).catch(err => {
        console.log(err)
      })
    },
    //  处理数据的绑定
    setFormData (data) {
      let list = []
      data.forEach(item => {
        const { source, dataType, sourceUserId, validNum, memo } = item
        item.validNum = validNum || ''
        item.source = source || ''
        item.dataType = dataType || ''
        item.sourceUserId = sourceUserId || ''
        item.memo = memo || ''
        list.push(item)
      })
      this.formData.sourceData = list
    }
  },
  watch: {
    visible (val) {
      if (val) {
        // 获取来源人的配置选项
        this.$store.dispatch('getSourceUser')
        this.formData.queryParas = this.filterData(this.form)
        this.$set(this.formData, 'expressCompany', '1')
        // this.formData.expressCompany = '1'
        this.loadData()
      } else {
        this.dataType = ''
        this.source = ''
        this.formData = {}
      }
    }
  },
  computed: {
    isquired () {
      const { sourceData } = this.formData
      let types = sourceData.map(i => i.source)
      let index = types.indexOf('1')
      return index !== -1
    },
    exclude (dataType) {
      return function (dataType) {
        return dataType === '1' ? [{ dictId: '2' }, { dictId: '4' }] : [{ dictId: '5' }]
      }
    },
    api () {
      return chargebackApi.dataApi
    }
  }
}
</script>
