<template>
  <el-dialog :title="title" :visible.sync="show" width="400px" append-to-body>
    <el-upload
      ref="upload"
      :limit="1"
      accept=".xlsx, .xls"
      :headers="headers"
      :action="uploadUrl + '?updateSupport=' + updateSupport"
      :disabled="isUploading"
      :on-progress="handleFileUploadProgress"
      :on-success="handleFileSuccess"
      :auto-upload="false"
      drag
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip text-center" slot="tip">
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="updateSupport">更新已经存在的数据</el-checkbox>
        </div>
        <span>仅允许导入xls、xlsx格式文件。</span>
        <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
      </div>
    </el-upload>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitFileForm" :loading="isUploading">确 定</el-button>
      <el-button @click="show = false">取 消</el-button>
    </div>

  </el-dialog>
</template>

<script>
import { getToken } from '@/utils/auth'

export default {
  name: "ImportDialog",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '导入'
    },
    url: {
      type: String,
      default: null,
      required: true
    },
    templateUrl: {
      type: String,
      default: null,
      required: true
    },
    templateName: {
      type: String,
      default: "导入模板"
    }
  },
  data() {
    return {
      isUploading: false,
      updateSupport: false,
    }
  },
  computed: {
    show: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit('update:visible', val);
      }
    },
    headers() {
      return { Authorization: "Bearer " + getToken() }
    },
    uploadUrl() {
      console.log('process.env.VUE_APP_BASE_API + this.url',process.env.VUE_APP_BASE_API + this.url )
      return process.env.VUE_APP_BASE_API + this.url;
    }
  },
  methods: {
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.isUploading = false;
      this.$refs.upload.clearFiles();
      if (response.code === 200) {
        this.$message.success(`扫描到${response.data}条数据，正在导入中，可在导入日志中查看导入结果`);
        this.$emit('success');
      }
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(this.templateUrl, {
      }, `${this.templateName}_${new Date().getTime()}.xlsx`)
    },
  }

}
</script>
