<template>
    <div>
        <dialog-edit
                :visible.sync="dialogVisible"
                :title="$t('common.ExpeditedOrder')"
                center="center"
                :width="'90%'"
                :appendToBody="true"
                editModel="E"
                :form="{}"
                :footerBtnShow="false"
                :before-close="closeDialog">

            <!--上传文件-->
            <el-col class="uploadFileRow">
              <span size="3">{{$t('common.selectedUploadFile')}}</span>
              <span class="paddingLeft20">
                    {{uploadFileName}}
                    <!--上传按钮-->
                    <btn-upload class="uploadBnt" type="primary" :uploadApi="uploadApi" fileType=".xls,.xlsx"
                                @uploadSuccess="uploadSuccess"></btn-upload>
              </span>
            </el-col>

            <!--错误消息-->
            <el-col v-if="errorMsgFileName!==''">
                <div>
                    <span class="fontRed">{{$t('common.uploadFileErrorMsg')}}
                        <a v-if="code === '0'" :title="$t('traceMgr.errorFile')" class="errorFile" @click="downLoadErrorMsgFile()">{{errorMsgFileName}}({{$t('traceMgr.clickLook')}})</a>
                        <sapn v-if="code === '-1'" :title="$t('traceMgr.errorMessage1')">{{errorMsgFileName}}</sapn>
                    </span>
                </div>
            </el-col>

            <!--表格数据-->
            <el-col class="tableRow">
                <el-tabs>
                    <el-tab-pane :label="$t('common.importExpeditedOrder')"></el-tab-pane>
                </el-tabs>

                <urgentOrderList :data.sync="sourceData" :dialogVisible="dialogVisible"></urgentOrderList>

            </el-col>

            <!--表单-->
            <el-col v-if="dialogVisible">
                <el-form :model="form" :rules="rules" ref="form">
                    <el-form-item :label="$t('common.ExpeditedProcess')" label-width="80px" prop="expeditedProcess">
                        <el-select class="form-item-class" v-model="form.expeditedProcess" style="width: 15%" @change="orderUrgentConfigChange()"
                                   :placeholder="$t('common.point')">
                            <el-option
                                    v-for="kv in options"
                                    :key="kv.k"
                                    :label="kv.v"
                                    :value="kv.k">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </el-col>

          <div slot="footer" class="dialog-footer">
            <auth-button type="primary" size="medium" :label="$t('common.complete')" @click="importUrgentOrderDialog_conmit()"></auth-button>
            <el-button size="medium" @click="dialogVisible=false">{{$t('common.close')}}</el-button>
          </div>

        </dialog-edit>
    </div>
</template>

<script>

import { DialogEdit, authButton, btnUpload } from 'newepoch-components'

import tracemgrApi from '@/api/tracemgrApi.js'

import urgentOrderList from './urgentOrderList'
import fileApi from '@/api/fileApi.js'
import { downFile } from '@/utils/devUtils'

export default {
  props: {
    visible: {
      type: Boolean
    }
  },

  computed: {
    dialogVisible: {
      get: function () {
        return this.visible
      },
      set: function (val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    dialogVisible: {
      deep: true,
      handler: function () {
        if (this.dialogVisible) { // 初始化页面
          tracemgrApi['importUrgentOrderDialogApi'].getDictTypeCode().then(res => {
            this.options = res.data
          })
        } else { // 关闭页面
          this.uploadFileName = ''
          this.form = {}
          this.errorMsgFileName = ''
        }
      }
    }
  },
  name: 'importUrgentOrderDialog',
  components: {
    urgentOrderList,
    DialogEdit,
    authButton,
    btnUpload
  },
  data () {
    return {
      fileId: '',
      sourceData: [],
      /* 加急流程下拉框数据 */
      options: [],
      /* 文件上传地址 */
      uploadApi: tracemgrApi['importUrgentOrderDialogApi'].UPLOAD_API,
      /* 文件名 */
      uploadFileName: '',
      /* 反馈文件名 */
      errorMsgFileName: '',
      /* 反馈文件目录 */
      errorMsgFileDir: '',
      /* 文件处理Code */
      code: '',
      /* 列表数据 */
      form: {},
      /* 表单校验规则 */
      rules: { expeditedProcess: [{ required: true, message: this.$i18n.messages[this.$i18n.locale].common.expeditedProcessNotEmpty, trigger: 'change' }] }
    }
  },
  methods: {
    closeDialog () {
      this.dialogVisible = false
    },
    orderUrgentConfigChange () {
      let list = this.form.data
      if (list === undefined || list.length === 0) {
        return
      }

      let orderUrgentConfig = this.form.expeditedProcess
      for (let i = 0; i < list.length; i++) {
        this.form.data[i].orderUrgentConfigId = orderUrgentConfig
      }
    },

    /**
     * 反馈文件下载
     */
    downLoadErrorMsgFile () {
      let $this = this
      $this.showLoading = true
      fileApi.file.download({ keyId: $this.fileId }).then(res => {
        downFile(res)
        $this.showLoading = false
      }).catch(() => {
        $this.showLoading = false
      })
      // tracemgrApi['importUrgentOrderDialogApi'].downLoadErrorMsgFile({ filePath: this.errorMsgFileDir, fileName: this.errorMsgFileName }, this.errorMsgFileName)
    },

    /**
     * 提交按钮
     */
    importUrgentOrderDialog_conmit () {
      this.$refs['form'].validate(result => {
        if (result) { // 验证通过，提交方法
          let data = this.form.data
          if (data === undefined || data.length === 0) {
            this.$message.error(this.$i18n.messages[this.$i18n.locale].baoLiWorkbenchOrderTrack.noDataSubmit)
            return
          }

          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 requestData = { listJson: JSON.stringify(data) }

          // 执行保存
          tracemgrApi['importUrgentOrderDialogApi'].orderUrgentSave(requestData).then(res => {
            loading.close()
            clearTimeout(timeout)
            if (res.code !== '0') { // 请求失败
              this.$message.error(this.$i18n.messages[this.$i18n.locale].baoLiWorkbenchOrderTrack.serverBusy)
            } else {
              if (res.data.code === -1) {
                this.$message.error(this.$i18n.messages[this.$i18n.locale].common.saveError)
              } else {
                this.$message.success(this.$i18n.messages[this.$i18n.locale].common.saveSuccess)
                this.closeDialog()
              }
            }
          })
        }
      })
    },

    /**
       * 文件上传成功提示
       * @param returnData
       */
    uploadSuccess (returnData) {
      let data = JSON.parse(returnData.fileID)
      let code = data.code

      if (code === '1') { // 文件类容正确，加载列表数据
        if (data.data.length === 0) this.$message.warning(this.$i18n.messages[this.$i18n.locale].baoLiWorkbenchOrderTrack.noDataFound)
        this.form.data = data.data
        this.sourceData = data.data
        this.errorMsgFileName = ''
      } 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// 文件名
    }
  }
}
</script>

<style scoped>
    @import '~@/styles/tracemgr/factoringCommissioner/workbench/orderTrack/importUrgentOrderDialog.scss'
</style>
