<template>
  <div :class="prefixCls">
    <el-dialog
      class="modify-data"
      :visible.sync="modalIsShow"
      :title="title"
      top="10vh"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      @open="visibleChange"
    >
      <div style="footer"></div>
      <div :class="[`${prefixCls}-body`]">
        <el-upload
          drag
          :action="uploadUrl"
          :headers="headers"
          :max-size="maxSize"
          :format="format"
          :accept="accept"
          :data="uploadData"
          :before-upload="handleBeforeUpload"
          :on-error="handleError"
          :on-success="handleSuccess"
          :on-remove="handleRemove"
          ref="UploadComp"
        >
          <i class="el-icon-upload"></i><br />
          <em class="el-upload__text">将文件拖到此处，或<em>点击上传</em></em>
          <p
            slot="tip"
            :class="[
              `${prefixCls}-tips`,
              {
                'cc-tips-success': res.success,
                'cc-tips-error': !res.success,
              },
            ]"
            v-if="res.msg"
          >
            {{ res.msg }}
          </p>
        </el-upload>
      </div>
      <div :class="[`${prefixCls}-footer`]" v-if="downloadUrl">
        文件下载：
        <a :href="downloadUrl" :download="dfilename">{{ dfilename }}</a>
      </div>
    </el-dialog>
  </div>
</template>

<script>
const prefixCls = "cc-import-file";

export default {
  name: "import-file",
  props: {
    title: {
      type: String,
      default: "文件上传",
    },
    downloadUrl: {
      type: String,
      default: "",
    },
    downloadFilename: String,
    format: {
      type: Array,
      default() {
        return ["jpg", "jpeg", "png"];
      },
    },
    uploadUrl: {
      type: String,
      required: true,
    },
    uploadData: {
      type: Object,
      default() {
        return {};
      },
    },
    headers: {
      type: Object,
      default() {
        return {};
      },
    },
    maxSize: {
      type: Number,
      default: 20 * 1024 * 1024,
    },
    addFilenameParam: {
      type: String,
      default: "fileName",
    },
  },
  data() {
    return {
      prefixCls,
      modalIsShow: false,
      res: {
        success: true,
        msg: "",
      },
    };
  },
  computed: {
    dfilename() {
      return this.downloadFilename || this.downloadUrl.split("/").pop();
    },
    accept() {
      return this.format.map((el) => `.${el}`).join();
    },
  },
  methods: {
    visibleChange() {
      this.res = {
        success: true,
        msg: "",
      };
    },
    checkFileFormat(fileType) {
      const _file_format = fileType.split("/").pop().toLocaleLowerCase();
      return this.format.some(
        (item) => item.toLocaleLowerCase() === _file_format
      );
    },
    handleBeforeUpload(file) {
      if (this.addFilenameParam)
        this.uploadData[this.addFilenameParam] = file.name;

      if (file.size > this.maxSize) {
        this.handleExceededSize();
        return Promise.reject();
      }

      if (!this.checkFileFormat(file.type)) {
        this.handleFormatError();
        return Promise.reject();
      }

      return true;
    },
    handleError(error) {
      this.res = {
        success: false,
        msg: error.message,
      };
      this.$emit("upload-error", error);
    },
    handleSuccess(response) {
      this.res = {
        success: true,
        msg: "导入成功！",
      };
      this.$emit("upload-success", response);
    },
    handleFormatError() {
      this.res = {
        success: false,
        msg: "只支持文件格式为" + this.format.join("/"),
      };
      this.$refs.UploadComp.clearFiles();
    },
    handleExceededSize() {
      this.res = {
        success: false,
        msg: "文件大小不能超过" + Math.floor(this.maxSize / 1024) + "M",
      };
      this.$refs.UploadComp.clearFiles();
    },
    handleRemove() {
      this.$refs.UploadComp.abort();
      this.$refs.UploadComp.clearFiles();
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
  },
};
</script>
