<template>
  <div>
    <up-down-layout :handleFlag="true">
      <!-- 搜索栏 -->
      <search-form @clearParam="clearParam"
                   @handleFilter="handleFilter"
                   :menuCode="menuId"
                   searchPerms="search"
                   resetPerms="reset"
                   :formValue.sync="queryParas"
                   :componentList="componentList"
                   slot="query">
      </search-form>
      <!-- 表格栏 -->
      <template v-slot:table>
        <div class="table-item">
          <el-form :model="dataForm" ref="dataForm">
            <data-table :api="api"
                        ref="dataTable"
                        operateBtnLayout=""
                        :sourceData.sync="dataForm.sourceData"
                        :columns="columns"
                        :loadCount.sync="loadCount"
                        :queryParas="queryParas"
                        :showSelection="true"
                        :menuFlag="true"
                        v-bind="elHeightObj"
                        :selectedRows.sync="selectedRows"
                        @getTableData="getTableData">
              <!-- 表格头按钮 -->
              <template slot="headButton">
                <div class="btn-right">
                  <auth-button size="medium"
                               type="primary"
                               icon="iconfont icondaochu"
                               :label="$t('common.export')"
                               @click="exportFile">
                  </auth-button>
                </div>
              </template>
              <!-- 顺延后期数 -->
              <template slot="afterPeriodshead" slot-scope="scope">
                {{scope.data.column.label}}
                <el-input size="mini" v-model.number="number" :placeholder="$t('common.pleaseInput')"></el-input>
              </template>
              <template v-slot:afterPeriods="scope">
                <el-form-item v-if="scope.data.row.status" label-width="0"
                              :rules="{ required: true, trigger: 'blur', validator: specialPlanPeriodsCheck, row: scope.data.row }"
                              :prop="'sourceData.' + scope.data.$index + '.afterPeriods'">
                  <el-input v-model.number="scope.data.row.afterPeriods" :placeholder="$t('common.pleaseInput')"></el-input>
                </el-form-item>
                <span v-else>{{scope.data.row.afterPeriods}}</span>
              </template>
            </data-table>
          </el-form>
          <div align="center">
            <auth-button size="medium" type="primary" :label="$t('common.confirm')" @click="confirm"></auth-button>
          </div>
        </div>
      </template>
    </up-down-layout>
  </div>
</template>

<script>
import { authButton, upDownLayout, searchForm, DataTable, SelectProductName, SelectCoreEnterprise, SelectSmallArea,
  SelectFinancialInstitutions, btnExport } from 'newepoch-components'
import BasePage from '@/pages/basePage'
import { regExp } from '@/validator/index'
import factoringBusinessInfoApi from '@/api/factoringBusinessInfoApi'
import exportApi from '@/api/sysApi.js'
import fileApi from '@/api/fileApi.js'
import { downFile } from '@/utils/devUtils'
import mixin from '@/pages/mixin'
import * as format from '@/filters/index'
import cn from '@/i18n/langs/cn.js'

const { common, message } = cn
export default {
  extends: new BasePage(),
  mixins: [mixin],
  name: 'deferredAssetsList',
  components: {
    authButton,
    upDownLayout,
    searchForm,
    DataTable,
    btnExport
  },
  data () {
    const { factoringBusinessInfo } = this.$i18n.messages[this.$i18n.locale]
    const labelWidth = '160px'
    return {
      elOtherHeight: 95,
      templateCode: 'syzcqd001',
      selectedRows: [],
      dataForm: {
        sourceData: []
      },
      number: null,
      componentList: [
        // 产品名称
        {
          label: factoringBusinessInfo.product_name,
          value: 'projectId',
          componentName: SelectProductName,
          labelWidth: labelWidth
        },
        // 核心企业
        {
          label: factoringBusinessInfo.core_enterprise,
          value: 'coreEnterpriseId',
          componentName: SelectCoreEnterprise,
          labelWidth: labelWidth
        },
        // 计划管理人/再保理银行
        {
          label: factoringBusinessInfo.planning_manager,
          value: 'planOrBankId',
          componentName: SelectFinancialInstitutions,
          labelWidth: labelWidth
        },
        // 期数
        {
          label: factoringBusinessInfo.periods,
          value: 'specialPlanPeriods',
          placeholder: common.pleaseInput,
          componentName: 'el-input',
          labelWidth: labelWidth
        },
        // 付款确认书编号
        {
          label: factoringBusinessInfo.pay_code,
          value: 'assetCode',
          placeholder: common.pleaseInput,
          componentName: 'el-input',
          labelWidth: labelWidth
        },
        // 区域编号
        {
          label: factoringBusinessInfo.area_number,
          value: 'regionCode',
          placeholder: common.pleaseInput,
          componentName: 'el-input',
          labelWidth: labelWidth
        },
        // 区域
        {
          label: factoringBusinessInfo.area,
          value: 'coreArea',
          componentName: SelectSmallArea,
          labelWidth: labelWidth
        },
        // 项目公司名称
        {
          label: factoringBusinessInfo.project_company,
          value: 'debtor',
          placeholder: common.pleaseInput,
          componentName: 'el-input',
          labelWidth: labelWidth
        },
        // 供应商名称
        {
          label: factoringBusinessInfo.creditor,
          value: 'creditor',
          placeholder: common.pleaseInput,
          componentName: 'el-input',
          labelWidth: labelWidth
        },
        // 区域专员
        {
          label: factoringBusinessInfo.regional_commissioner,
          value: 'coreAreaAttacheName',
          placeholder: common.pleaseInput,
          componentName: 'el-input',
          labelWidth: labelWidth
        },
        // 保理专员
        {
          label: factoringBusinessInfo.factoring_commissioner,
          value: 'customerAccountName',
          placeholder: common.pleaseInput,
          componentName: 'el-input',
          labelWidth: labelWidth
        },
        // 业务人员
        {
          label: factoringBusinessInfo.operational_personne,
          value: 'businessPersonnel',
          placeholder: common.pleaseInput,
          componentName: 'el-input',
          labelWidth: labelWidth
        }
      ],
      columns: [
        // 产品名称
        {
          prop: 'projectName',
          align: 'left',
          width: '150px',
          label: factoringBusinessInfo.product_name
        },
        // 核心企业
        {
          prop: 'coreEnterpriseName',
          align: 'left',
          width: '140px',
          label: factoringBusinessInfo.core_enterprise
        },
        // 计划管理人/再保理银行
        {
          prop: 'planOrBankName',
          align: 'left',
          width: '170px',
          label: factoringBusinessInfo.planning_manager
        },
        // 期数
        {
          prop: 'specialPlanPeriods',
          align: 'right',
          width: '70px',
          label: factoringBusinessInfo.periods
        },
        // 付款确认书编号
        {
          prop: 'assetCode',
          align: 'left',
          width: '200px',
          label: factoringBusinessInfo.pay_code
        },
        // 区域编号
        {
          prop: 'regionCode',
          align: 'left',
          width: '130px',
          label: factoringBusinessInfo.area_number
        },
        // 区域
        {
          prop: 'coreAreaName',
          align: 'left',
          width: '150px',
          label: factoringBusinessInfo.area
        },
        // 项目公司名称
        {
          prop: 'debtor',
          align: 'left',
          width: '240px',
          label: factoringBusinessInfo.project_company
        },
        // 供应商名称
        {
          prop: 'creditor',
          align: 'left',
          width: '240px',
          label: factoringBusinessInfo.creditor
        },
        // 应收账款金额
        {
          prop: 'factoringMoney',
          align: 'right',
          width: '150px',
          label: factoringBusinessInfo.account_receivable,
          format: (row) => { return format.toThousandFilter(row.factoringMoney) }
        },
        // 区域专员
        {
          prop: 'coreAreaAttacheName',
          align: 'left',
          width: '100px',
          label: factoringBusinessInfo.regional_commissioner
        },
        // 保理专员
        {
          prop: 'customerAccountName',
          align: 'left',
          width: '100px',
          label: factoringBusinessInfo.factoring_commissioner
        },
        // 业务人员
        {
          prop: 'businessPersonnel',
          align: 'left',
          width: '100px',
          label: factoringBusinessInfo.operational_personne
        },
        // 顺延后期数
        {
          prop: 'afterPeriods',
          align: 'left',
          width: '180px',
          label: factoringBusinessInfo.progressive_num,
          headslot: true,
          slot: true
        },
        // 顺延原因
        {
          prop: 'chargebackReason',
          align: 'left',
          width: '200px',
          label: factoringBusinessInfo.progressive_info
        }
      ]
    }
  },
  computed: {
    api () {
      return factoringBusinessInfoApi.postponeApi
    }
  },
  methods: {
    confirm () {
      let _this = this
      if (_this.selectedRows.length === 0) {
        _this.warning(message.selectConfirmMsg)
      } else {
        let props = []
        _this.selectedRows.forEach((it, index) => {
          if (it.status) {
            props.push(`sourceData.${index}.afterPeriods`)
          }
        })
        let count = 0
        if (props.length > 0) {
          _this.$refs.dataForm.validateField(props, (valid) => {
            if (!_this.UtilJs.isEmpty(valid)) {
              count++
            }
          })
        }
        if (count === 0) {
          let arr = []
          _this.selectedRows.forEach(it => {
            arr.push({
              afterPeriods: it.afterPeriods,
              assetCode: it.assetCode,
              assetPoolId: it.assetPoolId
            })
          })
          _this.api.submit(arr).then(res => {
            if (res && res.data) {
              _this.success(message.confirmSuc)
              _this.handleFilter()
            } else {
              _this.error(message.confirmFail)
            }
          })
        } else {
          _this.warning('请完善标红处数据再提交确认！')
        }
      }
    },
    handleFilter () {
      this.$refs.dataTable.loadTableData()
      this.$refs.dataForm.clearValidate()
    },
    exportFile () {
      let _this = this
      let exportParams = {
        projectId: this.validateParams('projectId'),
        coreEnterpriseId: this.validateParams('coreEnterpriseId'),
        planOrBankId: this.validateParams('planOrBankId'),
        specialPlanPeriods: this.validateParams('specialPlanPeriods'),
        assetCode: this.validateParams('assetCode'),
        regionCode: this.validateParams('regionCode'),
        coreArea: this.validateParams('coreArea'),
        debtor: this.validateParams('debtor'),
        creditor: this.validateParams('creditor'),
        coreAreaAttacheName: this.validateParams('coreAreaAttacheName'),
        customerAccountName: this.validateParams('customerAccountName'),
        businessPersonnel: this.validateParams('businessPersonnel'),
        tenantId: this.$store.getters.tenantId
      }
      _this.api.exportList(exportParams).then(exRes => {
        if (exRes && exRes.data) {
          let obj = {
            map: {
              api: {}
            },
            fileName: format.formatDateNull(new Date(), 'yyyyMMdd') + '顺延资产清单'
          }
          _this.$set(obj.map.api, 'syzcqd001', exRes.data)
          exportApi.exportFileTemplate.createTemplate(obj, 'CREATE', 'syzcqd001').then(tepRes => {
            if (tepRes.success) {
              fileApi.file.download({ keyId: tepRes.data.keyId }).then(res => {
                downFile(res)
              })
            } else {
              _this.error(common.exportFail)
            }
          })
        } else {
          _this.error(common.exportFail)
        }
      })
    },
    validateParams (name) {
      return this.UtilJs.isNull(this.queryParas[name]) ? '' : this.queryParas[name]
    },
    specialPlanPeriodsCheck: function (rule, value, callback) {
      let row = rule.row
      if (!this.UtilJs.isEmpty(value)) {
        if (regExp.number.test(value) && value > row.specialPlanPeriods && value <= 127) {
          callback()
        } else {
          callback(new Error(message.afterPeriodsCompMsg))
        }
      } else {
        callback(new Error(message.afterPeriodsMsg))
      }
    },
    getTableData (returnData) {
      returnData.forEach(it => {
        if (this.UtilJs.isEmpty(it.afterPeriods)) {
          this.$set(it, 'status', true)
        } else {
          this.$set(it, 'status', false)
        }
      })
    }
  },
  watch: {
    'number' (n, o) {
      if (n !== o) {
        this.dataForm.sourceData.forEach(it => {
          if (it.status) {
            it.afterPeriods = this.number
          }
        })
        this.$refs.dataForm.validate()
      }
    }
  }
}
</script>

<style scoped lang="scss" src="@/styles/factoringBusinessInfo/index.scss">
</style>
