<template>
  <MegaModal
    id="uploadModal"
    :visible.sync="visible"
    :title="$t(title)"
    width="400px"
    @cancel="closeDialog"
  >
    <a-upload
      ref="upload"
      class="upload-demo"
      :data="data"
      :action="url"
      :file-list="fileList"
      :headers="headers"
      :accept="accept"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <a-button size="small" type="primary">
        {{ $t("SELECT_FILE") }} {{ `(${accept})` }}
      </a-button>
      <div v-if="showTip" class="el-upload__tip">
        {{ $t("UPLOAD_ONLY") }}{{ fileSize }}M
      </div>
    </a-upload>
    <span slot="footer" class="dialog-footer">
      <a-button @click="visible = false">{{ $t("CANCEL") }}</a-button>
      <a-button type="primary" :loading="loading" @click="handleSubmit">{{
        $t("UPLOAD")
      }}</a-button>
    </span>
  </MegaModal>
</template>

<script>
import { Modal as MegaModal } from "@mega-design/ui-vue";
import axios from "axios";
import { getToken } from "@/utils/auth";

export default {
  name: "IUploadModal",
  components: {
    MegaModal,
  },
  props: {
    url: {
      type: String,
      default: "",
    },
    showTip: {
      type: Boolean,
      default: true,
    },
    title: {
      type: String,
      default: "IMPORT",
    },
    accept: {
      type: String,
      default: ".xls,.xlsx",
    },
    fileSize: {
      type: Number,
      default() {
        return 2;
      },
    },
    limit: {
      type: Number,
      default: 1000,
    },
    data: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      visible: false,
      fileList: [],
      loading: false,
      headers: {
        Authorization: `Bearer ${getToken()}`,
      },
    };
  },
  computed: {
    // 判断是否已选择文件，false:未选取,true:已选取
    fileFlag() {
      return this.fileList.length > 0;
    },
  },
  methods: {
    init() {
      this.visible = true;
    },
    handleSubmit() {
      const { fileFlag, url, headers, fileList, uploadFiles } = this;
      if (!fileFlag) {
        this.$message.error(`${`${this.$t("PLEASE_SELECT_FILE_FIRST")}!`}`);
        return;
      }
      this.loading = true;
      fileList.forEach((file) => {
        uploadFiles(url, headers, "file", file);
      });
    },
    uploadFiles(url, headers, fileName, file) {
      const formData = new FormData();
      formData.append(fileName, file);
      const request = axios.create({
        headers,
      });
      return request
        .post(url, formData)
        .then((response) => {
          this.$message.success(this.$t("TIPS:COMMON:IMPORT_SUCCESS"));
          return Promise.resolve(response.data);
        })
        .catch((error) => {
          this.$message.error(this.$t(error.message));
          return Promise.reject(error);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        this.$t("UPLOAD_FILE_CANNOT_EXCEED") + this.limit + this.$t("PCS")
      );
    },
    beforeAvatarUpload(file) {
      const { fileList, fileSize, handleExceed, limit } = this;
      const isLt2M = file.size / 1024 / 1024 < fileSize;
      if (!isLt2M) {
        this.$message.error(
          `${this.$t("UPLOAD_FILE_CANNOT_EXCEED") + fileSize}MB!`
        );
      }
      if (fileList.length + 1 > limit) {
        handleExceed();
      } else {
        this.fileList = [...fileList, file];
      }
      // return isLt2M;
      return false;
    },
    handleAvatarSuccess(res, file) {
      this.loading = false;
      if (res.code === 200) {
        this.$message.success(this.$t("TIPS:COMMON:IMPORT_SUCCESS"));
        this.fileList = [];
        this.visible = false;
        this.fileList = [];
        this.$nextTick(() => {
          this.$emit("fetchList");
        });
        this.$emit("handleData", res, file);
      } else {
        this.fileList = [];
        this.$message.error(this.$t(res.msg));
      }
    },
    // 文件状态改变
    handleAvatarChange({ file, fileList }) {
      this.fileList = fileList;
      // // 当多余一个的时候替换文件
      // if (fileList.length > 1) {
      //   fileList.splice(0, 1)
      // }
    },
    // 关闭弹框
    closeDialog() {
      this.visible = false;
      this.fileList = [];
    },
  },
};
</script>

<style lang="less">
@import (optional, once) "../theme/index";

.upload-demo {
  padding: 20px;
}
#uploadModal {
  .ant-modal-header {
    border: none;
    .ant-modal-title {
      line-height: 24px;
      font-size: 18px;
      color: @primary-color;
    }
  }
}
</style>
