<template>
  <div>
    <a-upload
      ref="aUpload"
      key="upload1"
      :action="uploadUrl"
      :accept="accept"
      :limit="limit"
      :list-type="isShowButton ? 'picture' : 'picture-card'"
      :before-upload="beforeUpload"
      :class="{ hide: hideUpload }"
      :default-file-list="images"
      :file-list="images"
      :remove="handleRemove"
      :show-upload-list="showUploadInfo"
      :disabled="disabled"
      @change="handleChange"
    >
      <div
        v-if="(images.length == 0 || images.length != limit) && !isShowButton"
      >
        <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-button
        v-if="(images.length == 0 || images.length != limit) && isShowButton"
        type="primary"
      >
        <a-icon type="upload" /> {{ $t("UPLOAD") + $t("CORE_PICTURE") }}
      </a-button>
    </a-upload>
  </div>
</template>
<script>
import ApiConstant from "@/api/ApiConstant";
import { fetchFileUrl } from "@/utils/file";

export default {
  name: "SingleUpload",
  props: {
    // 配合v-model 加载初始值
    value: {
      type: String,
      default: "",
    },
    accept: {
      type: String,
      default: ".png, .jpg, .jepg, .jpeg, .gif",
    },
    // 最大值文件个数限制
    limit: {
      type: Number,
      default: 1,
    },
    mutiple: {
      type: Boolean,
      default: false,
    },
    // 是否显示为按钮
    isShowButton: {
      type: Boolean,
      default: false,
    },
    imageUrlList: {
      type: Array,
      default() {
        return [];
      },
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false,
      uploadUrl: `${ApiConstant.PREFIX_CORE}/api/sys/file/upload`,
      fileName: "",
      imageUrl: "",
      images: [],
      showUploadInfo: {
        showRemoveIcon: true,
      },
    };
  },
  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.images = JSON.parse(JSON.stringify(newVal));
          this.images = 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 = false;
        }
      },
      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;
        }) || [];
    }
  },
  methods: {
    handleRemove(file) {
      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) {
      const suffixs = [
        ".png",
        ".jpg",
        ".gif",
        ".jepg",
        ".jpeg",
        ".ico",
        ".svg",
      ];
      const i = file.name.lastIndexOf(".");
      const suffix = file.name.slice(i);
      if (!suffixs.includes(suffix)) {
        this.$message.error(this.$t("PICTURE_FORMAT_ERROR")); // 文件格式错误！
        return false;
      }
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message.error(this.$t("FILESIZE_WARNING")); // 上传文件大小不能超过 5MB!
        return false;
      }
      return true;
    },
    handleChange(info) {
      if (info.file.status === "uploading") {
        this.images = info.fileList;
        // this.loading = true;
      }
      if (info.file.status === "done") {
        this.images = info.fileList;
        // 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>
/deep/ .ant-upload-list-picture {
  margin-top: -20px;
}
</style>
