<template>
  <!--预分配订单导入页面-->
  <dialog-edit :visible.sync="dialogVisible"
               :title="$t('traceMgr.preAllocationOrderImport')"
               :editModel="''"
               :form="queryParas"
               width="90%"
               @onSaved="submit"
               :autoSave="false"
               :autoClose="true"
               @close="dialogClose"
               :loading="saveLoading"
               :appendToBody="true">
    <el-form  :model="queryParas" :rules="rules" ref="form" style="margin-bottom: 30px"  >
      <el-row>
        <!--产品-->
        <el-col :span="4">
          <el-form-item :label="$t('traceMgr.product')"  prop="productId" :label-width="'80px'">
            <select-dictionary :dictTypeCode="'ZD0087'" @selectChanged="selectChangedName" v-model="queryParas.productId"></select-dictionary>
          </el-form-item>
        </el-col>
        <!--核心企业-->
        <el-col :span="4">
          <el-form-item :label="$t('traceMgr.coreEnterprise')" prop="coreEnterpriseId" :label-width="'80px'">
            <select-core-enterprise v-model="queryParas.coreEnterpriseId"
                                    @selectChanged="selectChanged"></select-core-enterprise>
          </el-form-item>
        </el-col>
        <!--计划管理人/再保理银行-->
        <el-col :span="6">
          <el-form-item :label="$t('traceMgr.financialInstitutions')" prop="planOrBankId" :label-width="'180px'">
            <select-financial-institutions v-model="queryParas.planOrBankId"
                                           @selectChanged="selectChangedPlan"></select-financial-institutions>
          </el-form-item>
        </el-col>
        <!--期数-->
        <el-col :span="4">
          <el-form-item :label="$t('traceMgr.periodsCascade')"  prop="specialPlanPeriods"  :label-width="'80px'">
            <!--                        <select-periods-cascade v-model="periodsCascadeId"></select-periods-cascade>-->
            <select-flag :options="options" :disabled="disabled" v-model="queryParas.specialPlanPeriods"></select-flag>
          </el-form-item>
        </el-col>
        <!--提单日期-->
        <el-col :span="4">
          <el-form-item :label="$t('traceMgr.billOfLadingDate')" prop="factoringApplyTime" :label-width="'80px'">
            <div class="block">
              <el-date-picker
                v-model="queryParas.factoringApplyTime"
                type="date"
                value-format="yyyy-MM-dd"
                :placeholder="$t('common.point')"
                :picker-options="pickerOptions">
              </el-date-picker>
            </div>
          </el-form-item>
        </el-col>
        &nbsp;&nbsp;
        <el-col :span="1">
          <el-button type="primary" class="btn-upload" size="small"   @click="checkParams('form')"><i class="iconfont iconycshangchuan" ></i>&nbsp;&nbsp;{{$t('common.upload')}}</el-button>
          <btn-upload type="primary" :uploadApi="uploadApi" ref="upload" :beforeUpload="beforeUpload" style="margin-left: 10px;margin-top: 4px;display: none " :belongCode="params()" @uploadSuccess="uploadSuccess"
                      @uploadFailed="uploadFailed" class="btn-upload"></btn-upload>
        </el-col>
      </el-row>
      <el-row>
        <!-- :http-request="handleUploadForm"-->
        <!--错误消息-->
        <el-col v-if="errorMsgFileName!==''">
          <div class="margin-left24" v-if="errorMsgFileName!==''">
                                <span class="fontRed">{{$t('common.uploadFileErrorMsg')}}
                                    <a v-if="code === '0'" :title="$t('traceMgr.errorFile')" class="errorFile" :loading="showLoading"
                                       @click="downLoadErrorFile()">{{errorMsgFileName}}({{$t('traceMgr.clickLook')}})</a>
                                    <sapn v-if="code === '-1'" :title="$t('traceMgr.errorMessage1')">{{errorMsgFileName}}</sapn>
                                </span>
          </div>
        </el-col>
      </el-row>
      <data-table :sourceData.sync="sourceData" :columns="columns" :api="tableApi" operateBtnLayout="" :border="true"
                  :stripe="true" :showPage="false">
      </data-table>
    </el-form>
    <business-data-statistics-dialog :importQueryParas="queryParas" :orderType="orderType" @closeParent="closeDialogVisible"
                                     :visible.sync="businessDataStatisticsDialog"></business-data-statistics-dialog>
  </dialog-edit>
</template>
<script>
import BaseEditPage from '@/pages/baseEditPage'
// import { UPLOAD_API } from '@/constant.js'
import {
  DialogEdit,
  SelectProductName,
  SelectCoreEnterprise,
  SelectFinancialInstitutions,
  SelectPeriodsCascade,
  btnUpload,
  DataTable,
  SelectDictionary
} from 'newepoch-components'
import SelectFlag from '@/components/tracemgr/common/SelectFlag'
import tracemgrApi from '@/api/tracemgrApi'
import businessDataStatisticsDialog from './businessDataStatisticsDialog'
import * as format from '@/filters/index'
import fileApi from '@/api/fileApi.js'
import { downFile } from '@/utils/devUtils'

export default {
  name: 'importPreDistributionOrderDialog',
  extends: new BaseEditPage(''),
  props: {
    editModel: {
      type: String
    },
    form: {
      type: Object
    }
  },
  components: {
    DataTable,
    DialogEdit,
    SelectProductName,
    SelectCoreEnterprise,
    SelectFinancialInstitutions,
    SelectPeriodsCascade,
    btnUpload,
    SelectDictionary,
    SelectFlag,
    tracemgrApi,
    businessDataStatisticsDialog,
    format
  },
  computed: {
    dialogVisible: {
      get: function () {
        return this.visible
      },
      set: function (value) {
        this.$emit('update:visible', value)
      }
    }
  },
  data () {
    return {
      businessDataStatisticsDialog: false,
      saveLoading: false,
      fileId: '',
      uploadApi: tracemgrApi['importPreDistributionOrderDialog'].UPLOAD_API,
      orderType: '2',
      disabled: false,
      queryParas: {
        productId: '',
        coreEnterpriseId: '',
        coreEnterpriseName: '',
        planOrBankId: '',
        planOrBankName: '',
        specialPlanPeriods: '',
        factoringApplyTime: '',
        orderType: '2',
        // 这里只做导入区分
        productName: '1'
      },
      rules: {
        productId: [
          { required: true, message: this.$i18n.messages[this.$i18n.locale].traceMgr.pleaseSelectTheProduct, trigger: 'change' }
        ],
        coreEnterpriseId: [
          { required: true, message: this.$i18n.messages[this.$i18n.locale].traceMgr.pleaseSelectTheCoreEnterpriseId, trigger: 'change' }
        ],
        planOrBankId: [
          { required: true, message: this.$i18n.messages[this.$i18n.locale].traceMgr.pleaseSelectThePlanOrBankId, trigger: 'change' }
        ],
        specialPlanPeriods: [
          { required: true, message: this.$i18n.messages[this.$i18n.locale].traceMgr.pleaseSelectTheSpecialPlanPeriods, trigger: 'change' }
        ],
        factoringApplyTime: [
          { required: true, message: this.$i18n.messages[this.$i18n.locale].traceMgr.pleaseSelectTheFactoringApplyTime, trigger: 'change' }
        ]
      },
      showLoading: false,
      /* 反馈文件名 */
      errorMsgFileName: '',
      /* 反馈文件目录 */
      errorMsgFileDir: '',
      // productId: '',
      options: [{ label: 1, value: 1 }, { label: 2, value: 2 }, { label: 3, value: 3 }, {
        label: 4,
        value: 4
      }, { label: 5, value: 5 }, { label: 6, value: 6 },
      { label: 7, value: 7 }, { label: 8, value: 8 }, { label: 9, value: 9 }, { label: 10, value: 10 }, {
        label: 11,
        value: 11
      }, { label: 12, value: 12 },
      { label: 13, value: 13 }, { label: 14, value: 14 }, { label: 15, value: 15 }, {
        label: 16,
        value: 16
      }, { label: 17, value: 17 }, { label: 18, value: 18 },
      { label: 19, value: 19 }, { label: 20, value: 20 }, { label: 21, value: 21 }, {
        label: 22,
        value: 22
      }, { label: 23, value: 23 }, { label: 24, value: 24 },
      { label: 25, value: 25 }, { label: 26, value: 26 }, { label: 27, value: 27 }, {
        label: 28,
        value: 28
      }, { label: 29, value: 29 }, { label: 30, value: 30 },
      { label: 31, value: 31 }, { label: 32, value: 32 }, { label: 33, value: 33 }, {
        label: 34,
        value: 34
      }, { label: 35, value: 35 }, { label: 36, value: 36 },
      { label: 37, value: 37 }, { label: 38, value: 38 }, { label: 39, value: 39 }, {
        label: 40,
        value: 40
      }, { label: 41, value: 41 }, { label: 42, value: 42 },
      { label: 43, value: 43 }, { label: 44, value: 44 }, { label: 45, value: 45 }, {
        label: 46,
        value: 46
      }, { label: 47, value: 47 }, { label: 48, value: 48 },
      { label: 49, value: 49 }, { label: 50, value: 50 }],
      // coreEnterpriseId: '',
      // financialInstitutionsId: '',
      // periodsCascadeId: '',
      // billOfLadingDate: '',
      // enterpriseName: '',
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now() - 8.64e6
        }
      },
      tableApi: {},
      sourceData: [],
      columns: [
        // 付款确认书编号
        {
          prop: 'assetCode',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.paymentConfirmationNo
        },
        // 应收账款金额
        {
          prop: 'factoringMoney',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.amountOfReceivables
        },
        // 到期日
        {
          prop: 'dueDate',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.dueDate,
          format: (row) => {
            return format.formatDateNull(row.dueDate)
          }
        },
        // 供应商名称
        {
          prop: 'creditor',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.supplierName

        },
        // 项目公司名称
        {
          prop: 'projectName',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.projectCompanyName
        }
      ]
    }
  },
  watch: {
    visible (value) {
      if (value) {
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
          this.errorMsgFileName = ''
          for (let key in this.queryParas) {
            this.queryParas[key] = ''
          }
        })
      }
    }
  },
  methods: {
    selectChangedName (v, a, b) {
      if (v !== null && v !== '') {
        this.queryParas.name = b.dictName
        this.queryParas.nameId = v
      }
      if (v === '1') {
        this.rules.factoringApplyTime[0].required = false
        this.queryParas.factoringApplyTime = ''
        this.rules.specialPlanPeriods[0].required = true
        this.disabled = false
      }
      if (v === '2') {
        this.rules.factoringApplyTime[0].required = true
        this.rules.specialPlanPeriods[0].required = false
        this.queryParas.specialPlanPeriods = ''
        this.disabled = true
      }
    },
    // selectqiye (v, a, b) {
    //   this.queryParas.qiye = b.enterpriseName
    //   this.queryParas.qiyeId = v
    // },
    params () {
      return JSON.stringify(this.queryParas)
    },
    beforeUpload (file) {

    },
    uploadSuccess (returnData) {
      let data = JSON.parse(returnData.fileID)
      let code = data.code
      if (code === '1') { // 文件类容正确，加载列表数据
        this.success(this.$i18n.messages[this.$i18n.locale].bankPrice.importSuccess)
        this.sourceData = data.orderData
        this.errorMsgFileName = ''
        this.errorMsgFileDir = ''
      } else { // 错误
        if (code === '0') { // 文件错误
          this.errorMsgFileName = data.feedbackFileName // 反馈文件名
          this.fileId = data.feedbackFileName
          // this.errorMsgFileDir = data.dir // 反馈文件目录
        } else if (code === '-1') { // 文件格式错误
          this.errorMsgFileName = data.errorMsg
        }
        this.$message.error(data.errorMsg)
      }

      this.code = code
      this.uploadFileName = data.fileName// 文件名
      // tracemgrApi['importPreDistributionOrderDialog'].importData(this.queryParas)
    },
    /**
       * 反馈文件下载
       */
    downLoadErrorFile () {
      let $this = this
      $this.showLoading = true
      fileApi.file.download({ keyId: $this.fileId }).then(res => {
        downFile(res)
        $this.showLoading = false
      }).catch(() => {
        $this.showLoading = false
      })
      // tracemgrApi['importPreDistributionOrderDialog'].downLoadErrorFile({
      //   filePath: this.errorMsgFileDir,
      //   fileName: this.errorMsgFileName
      // }, this.errorMsgFileName)
      // this.showLoading = false
    },
    uploadFailed: function (a, b, c) {
      this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.fileEorro)
    },
    resetQuery () {
      this.productId = ''
      this.coreEnterpriseId = ''
      this.financialInstitutionsId = ''
      this.periodsCascadeId = ''
      this.billOfLadingDate = ''
    },
    closeDialogVisible () {
      this.productId = ''
      this.coreEnterpriseId = ''
      this.financialInstitutionsId = ''
      this.periodsCascadeId = ''
      this.billOfLadingDate = ''
      this.dialogVisible = false
      this.sourceData = []
      this.disabled = false
    },
    selectChanged (v, a, b) {
      if (v !== null && v !== '') {
        this.queryParas.coreEnterpriseName = b.enterpriseName
        this.queryParas.qiye = b.enterpriseName
        this.queryParas.qiyeId = v
      }
    },
    selectChangedPlan (v, a, b) {
      if (v !== null && v !== '') {
        this.queryParas.planOrBankName = b.enterpriseName
      }
    },
    submit () {
      let $this = this
      // let problemListData = {}
      if ($this.sourceData.length === 0) {
        this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.failedPleaseMakeSure)
        return
      }

      this.$confirm(this.$i18n.messages[this.$i18n.locale].traceMgr.saveOrNot, this.$i18n.messages[this.$i18n.locale].common.tip, {
        confirmButtonText: this.$i18n.messages[this.$i18n.locale].common.yes,
        cancelButtonText: this.$i18n.messages[this.$i18n.locale].common.no,
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: this.$i18n.messages[this.$i18n.locale].baoLiWorkbenchOrderTrack.pleaseWait,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        const timeout = setTimeout(() => {
          loading.close()
          this.$message.error(this.$i18n.messages[this.$i18n.locale].baoLiWorkbenchOrderTrack.serverBusy)
        }, 10000)

        let problemListData = $this.sourceData
        tracemgrApi['importPreDistributionOrderDialog'].save(problemListData).then(res => {
          loading.close()
          clearTimeout(timeout)

          if (res.data) {
            this.success(this.$i18n.messages[this.$i18n.locale].common.saveSuccess)
            this.$message({
              type: 'success',
              message: this.$i18n.messages[this.$i18n.locale].common.saveSuccess
            })
            this.queryParas.productName = '1'
            this.businessDataStatisticsDialog = true
          } else {
            // this.error(this.$i18n.messages[this.$i18n.locale].common.saveFailed)
          }
        }, res => {
          this.isLoading = false
        }).catch(
          // this.error(this.$i18n.messages[this.$i18n.locale].common.saveFailed)
        )
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$i18n.messages[this.$i18n.locale].traceMgr.canceled
        })
      })
    },
    dialogClose: function () {
      for (let key in this.queryParas) {
        this.queryParas[key] = ''
      }
      this.$refs['form'].resetFields()
      this.dialogVisible = false
      this.rules.factoringApplyTime[0].required = true
      this.rules.specialPlanPeriods[0].required = true
      this.sourceData = []
      this.disabled = false
    },
    checkParams (formName) {
      if (this.queryParas.productId === '1') {
        this.rules.factoringApplyTime[0].required = false
        this.queryParas.factoringApplyTime = ''
        this.rules.specialPlanPeriods[0].required = true
      }
      if (this.queryParas.productId === '2') {
        this.rules.factoringApplyTime[0].required = true
        this.rules.specialPlanPeriods[0].required = false
        this.queryParas.specialPlanPeriods = ''
      }
      this.queryParas.orderType = '2'
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$refs.upload.upload()
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
  @import '@/styles/tracemgr/coordinate/workbench/importPreDistributionOrderDialog.scss';
</style>
