<template>
  <div>
    <a-upload
      ref="aUpload"
      :key="time"
      :action="uploadUrl"
      :accept="accept"
      :limit="limit"
      list-type="picture-card"
      :before-upload="beforeUpload"
      :class="{ hide: hideUpload }"
      :default-file-list="fileList"
      :multiple="false"
      :remove="handleRemove"
      :show-upload-list="showUploadInfo"
      @change="handleChange"
      @preview="handlePreview"
    >
      <div
        v-if="
          (images.length == 0 || images.length != limit) &&
          isShowUploadButton === true
        "
      >
        <i
          v-if="!loading"
          slot="default"
          class="iconfont icon-ge_shangchuan"
          style="font-size: 18px; color: #0ea8d0"
        ></i>
        <a-icon v-else type="loading" />
        <div class="ant-upload-text" style="font-size: 12px; color: #666">
          {{ $t("UPLOAD") + $t("CORE_PICTURE") }}
        </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 } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import { fetchFileUrl } from "@/utils/file";

export default {
  name: "MultipleUpload",
  components: {
    MegaDrawer,
  },
  props: {
    // 配合v-model 加载初始值
    value: {
      type: Array,
      default() {
        return [];
      },
    },
    accept: {
      type: String,
      default: ".png, .jpg, .jepg, .jpeg, .gif",
    },
    // 最大值文件个数限制
    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,
      },
      time: 1,
      curCount: 0,
      tipFlag: false,
      // 图片上传
      uploadImg: {
        showImages: [], // 相关图片
        previewVisible: false,
        previewImage: "",
      },
    };
  },
  computed: {
    hideUpload() {
      return this.images.length >= this.limit;
    },
  },
  // 监听父组件值是否在变化
  watch: {
    // 有些页面初始初始src没有赋值
    value: {
      handler(newVal, oldValue) {
        this.images = [];
        if (!newVal) return;
        this.images = newVal.map((item) => {
          const obj = {};
          obj.url = fetchFileUrl(item.fileUrl, this);
          obj.fileUrl = item.fileUrl;
          obj.fileCode = item.fileCode;
          obj.name = item.fileUrl;
          obj.status = "done";
          obj.type = "image/png";
          obj.uid = item.fileCode || item.fileUrl;
          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.fileUrl || item.url, this);
            obj.fileUrl = item.fileUrl || item.url;
            obj.fileCode = item.fileCode || item.fileId;
            obj.name = item.fileUrl || item.url;
            obj.status = "done";
            obj.type = "image/png";
            obj.uid = item.fileCode || item.fileUrl || item.fileId || item.url;
            return obj;
          });
          this.showUploadInfo.showRemoveIcon = this.isShowUploadButton;
          this.curCount = this.fileList.length;
        } else {
          this.fileList = [];
        }
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    handleRemove(file) {
      this.curCount -= 1;
      let list = [];
      if (file.response) {
        list = this.images.filter(
          (item) => item.fileUrl !== file.response.data.fileUrl
        );
      } else {
        list = this.images.filter((item) => item.fileUrl !== file.fileUrl);
      }
      const resultUrl = list.map((item) => item.fileUrl).join(",");
      this.$emit("input", resultUrl, list);
    },
    // 限制图片大小
    // 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 < 2;
      // 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,
            fileCode: item.fileCode
              ? item.fileCode
              : item?.response?.data?.fileCode,
            fileUrl: item.fileUrl
              ? item.fileUrl
              : item?.response?.data?.fileUrl,
          };
          list.push(data);
        });
        const resultUrl = list.map((item) => item.fileUrl).join(",");
        this.$emit("input", resultUrl, list);
      }
    },
    // 預覽圖片
    handlePreview(file) {
      window.open(
        fetchFileUrl(
          file.fileUrl ? file.fileUrl : file.response.data.fileUrl,
          this
        )
      );
    },
  },
};
</script>
<style lang="less">
.login-name {
  position: absolute;
  bottom: -25px;
}
</style>
