<template>
  <div class="multiple-upload">
    <a-upload
      ref="aUpload"
      :key="time"
      :action="uploadUrl"
      :limit="limit"
      :headers="headers"
      list-type="picture-card"
      :before-upload="beforeUpload"
      :class="{ hide: hideUpload }"
      :default-file-list="fileList"
      :multiple="limit > 1"
      :remove="handleRemove"
      :show-upload-list="showUploadInfo"
      @change="handleChange"
    >
      <div
        v-if="
          (images.length == 0 || images.length != limit) &&
          isShowUploadButton === true
        "
      >
        <Icon
          v-if="!loading"
          slot="default"
          type="icon-cur-cloud-upload"
          :size="18"
          style="color: #0ea8d0"
        />
        <a-icon v-else type="loading" />
        <div class="ant-upload-text" style="font-size: 12px; color: #666">
          {{ $t("UPLOAD_IMG") }}
        </div>
      </div>
    </a-upload>
    <MegaDrawer :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="" />
    </MegaDrawer>
  </div>
</template>
<script>
import { Drawer as MegaDrawer, Icon } from "@mega-design/ui-vue";
import { fetchFileUrl } from "@/utils/file";
import ApiConstant from "@/api/ApiConstant";

export default {
  name: "MultipleUpload",
  components: {
    MegaDrawer,
    Icon,
  },
  props: {
    // 配合v-model 加载初始值
    value: {
      type: String,
      default: "",
    },
    // 最大值文件个数限制
    limit: {
      type: Number,
      default: 1,
    },
    mutiple: {
      type: Boolean,
      default: false,
    },
    imageUrlList: {
      type: Array,
      default() {
        return [];
      },
    },
    isShowUploadButton: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      loading: false,
      uploadUrl: `${ApiConstant.PREFIX_CORE}/api/sys/file/upload`,
      dialogImageUrl: "",
      fileName: "",
      fileList: [],
      imageUrl: "",
      images: [],
      dialogVisible: false,
      showUploadInfo: {
        showRemoveIcon: true,
      },
      headers: {
        tenantId:
          this.$store.state.app.systemConfig.TENANT_OPEN === "true"
            ? this.$store.state.account.tenantId
            : "",
      },
      time: 1,
      curCount: 0,
      tipFlag: false,
    };
  },
  computed: {
    hideUpload() {
      return this.images.length >= this.limit;
    },
  },
  // 监听父组件值是否在变化
  watch: {
    // 有些页面初始初始src没有赋值
    value: {
      handler(newValue, oldValue) {
        this.images = [];
        if (!newValue) return;
        this.images = newValue.split(",").map((item) => {
          const obj = {};
          obj.url = fetchFileUrl(item, this);
          obj.fileUrl = item;
          obj.name = item;
          obj.status = "done";
          obj.uid = item;
          return obj;
        });
      },
      immediate: false,
    },
    imageUrlList: {
      handler(newVal, oldVal) {
        if (newVal && newVal.length > 0) {
          this.time = new Date().getTime();
          // this.images = JSON.parse(JSON.stringify(newVal));
          this.fileList = newVal.map((item) => {
            const obj = {};
            obj.url = fetchFileUrl(item, this);
            obj.fileUrl = item;
            obj.name = item;
            obj.status = "done";
            obj.type = "image/png";
            obj.uid = item;
            return obj;
          });
          this.showUploadInfo.showRemoveIcon = this.isShowUploadButton;
        }
      },
      immediate: true,
      deep: true,
    },
  },
  mounted() {
    if (this.value) {
      this.images =
        this.value.split(",").map((item) => {
          const obj = {};
          obj.url = fetchFileUrl(item, this);
          obj.fileUrl = item;
          obj.name = item;
          obj.status = "done";
          obj.uid = item;
          return obj;
        }) || [];
      this.curCount = this.images.length;
    }
  },
  methods: {
    handleRemove(file) {
      this.curCount -= 1;
      const list = this.images.filter((item) => item.fileUrl !== file.fileUrl);
      const resultUrl = list.map((item) => item.fileUrl).join(",");
      this.$emit("input", resultUrl);
    },
    // 限制图片大小
    // eslint-disable-next-line
    beforeUpload(file, fileList) {
      const len = fileList.length + this.images.length;
      const suffixs = [
        ".png",
        ".jpg",
        ".gif",
        ".jepg",
        ".jpeg",
        ".ico",
        ".svg",
      ];
      const i = file.name.lastIndexOf(".");
      const suffix = file.name.slice(i);
      const isLt5M = file.size / 1024 / 1024 < 5;
      // this.tipFlag = !this.tipFlag ? len > this.limit : false;
      return new Promise((resolve, reject) => {
        if (!suffixs.includes(suffix)) {
          this.$message.error(this.$t("PICTURE_FORMAT_ERROR")); // 文件格式错误！
          reject(file);
        } else if (!isLt5M) {
          this.$message.error(this.$t("FILESIZE_WARNING")); // 上传文件大小不能超过 5MB!
          reject(file);
        } else if (this.curCount >= this.limit) {
          this.curCount = this.limit;
          if (!this.tipFlag) {
            this.tipFlag = true;
            this.$message.error(
              this.$t("UPLOAD_FILE_CANNOT_EXCEED") + this.limit + this.$t("PCS")
            );
          }
          // 文件数量超出限制数量！]
          reject(file);
        } else {
          this.curCount += 1;
          this.tipFlag = false;
          resolve(file);
        }
      });
    },
    handleChange(info) {
      this.tipFlag = false;
      this.images = info.fileList;
      if (info.file.status === "uploading") {
        // this.loading = true;
      }
      if (info.file.status === "done") {
        // Get this url from response in real world.
        // this.loading = false;
        const list = [];
        info.fileList.forEach((item) => {
          const data = {
            url: item.url ? item.url : item?.response?.data?.fileUrl,
            fileUrl: item.fileUrl
              ? item.fileUrl
              : item?.response?.data?.fileUrl,
          };
          list.push(data);
        });
        const resultUrl = list.map((item) => item.fileUrl).join(",");
        this.$emit("input", resultUrl);
      }
    },
  },
};
</script>
<style lang="less" scoped>
.multiple-upload {
  /deep/ .ant-upload-list-item {
    &-thumbnail img {
      object-fit: contain;
    }
    &-info > span {
      background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==);
    }
  }
}
</style>
