<template>
  <div>
    <a-upload
      ref="upload"
      class="upload"
      :action="uploadUrl"
      accept="*"
      list-type="picture-card"
      :data="fileData"
      :file-list="fileList"
      :headers="headers"
      :on-exceed="handleExceed"
      :on-remove="handleRemove"
      :on-success="uploadSuccess"
      :before-upload="beforeUpload"
      :on-preview="handlePictureCardPreview"
      :class="{ hide: hideUpload }"
    >
      <a-icon type="plus" />
    </a-upload>
    <MegaDrawer :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </MegaDrawer>
  </div>
</template>
<script>
import { Drawer as MegaDrawer } from "@mega-design/ui-vue";
import { getToken } from "@/utils/auth";
import { fetchFileUrl } from "@/utils/file";

export default {
  name: "StaticUpload",
  components: {
    MegaDrawer,
  },
  props: {
    // 配合v-model 加载初始值
    value: {
      type: String,
      default: "",
    },
    // 最大值文件个数限制
    limit: {
      type: Number,
      default: 1,
    },
    mutiple: {
      type: Boolean,
      default: false,
    },
    // 上传路径
    uploadUrl: {
      type: String,
      default: () => {
        return "";
      },
    },
    fileData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      dialogImageUrl: "",
      fileName: "",
      imageUrl: "",
      dialogVisible: false,
      headers: {
        Authorization: getToken(),
      },
      fileList: [], // 文件列表
    };
  },
  computed: {
    hideUpload() {
      return this.fileList.length >= this.limit;
    },
  },
  // 监听父组件值是否在变化
  watch: {
    // 有些页面初始初始src没有赋值
    value: {
      handler(newValue, oldValue) {
        if (!newValue) return;
        this.fileList = [];
        if (this.mutiple) {
          this.fileList = newValue.split(",").map((item) => {
            const obj = {};
            obj.url = fetchFileUrl(item, this);
            return obj;
          });
        } else {
          this.fileList.push({
            url: `${fetchFileUrl(newValue, this)}?${new Date().getTime()}`,
          });
        }
      },
      immediate: false,
    },
  },
  mounted() {
    this.fileList = [];
    if (this.value) {
      this.fileList.push({ url: fetchFileUrl(this.value, this) });
    }
  },
  methods: {
    // 文件上传
    uploadSuccess(response, file, fileList) {
      this.fileList = [];
      // this.fileList.push(file)
      if (response.code === 200 && response.data !== null) {
        // 将文件放入表单
        // this.ruleForm.LOGIN_BACKGROUND = response.data.fileUrl
        const obj = {};
        obj.url = fetchFileUrl(response.data.fileUrl, this);
        this.fileList.push(obj);
        this.$emit("input", response.data.fileUrl);
        this.$set(this, "fileList", this.fileList);
        this.$forceUpdate();
        this.$message.success(this.$t("UPLOAD_SUCCESS"));
      } else {
        this.$refs.upload.clearFiles();
        this.$message.error(this.$t(response.msg));
      }
    },
    // 上传文件之前校验
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 100; // 判断文件大小是否小于100M
      if (!isLt2M) {
        this.$message.error(`${this.$t("UPLOAD_FILE_CANNOT_EXCEED") + 100}MB!`);
        return false;
      }
      return true;
    },
    // 清空文件
    handleRemove(file, fileList) {
      this.fileList = [];
      this.$emit("input", "");
    },
    // 文件超出个数限制时的钩子
    handleExceed(files, fileList) {
      this.$message.warning(
        this.$t("UPLOAD_FILE_CANNOT_EXCEED") + files.length + this.$t("PCS")
      );
    },
    // 预览图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
  },
};
</script>
<style lang="less">
.login-name {
  position: absolute;
  bottom: -25px;
}
</style>
