<template>
  <div>
    <div v-if="fileType !== 'img'" class="file_list flex">
      <div
        v-for="(item, index) in showFileList"
        :key="index"
        class="file_item relative text-center cursor-pointer"
        @click="handlePreview(item)"
      >
        <div
          v-if="fileType === 'video'"
          class="file_item_icon mt-3 iconfont icon-shipin1"
        ></div>
        <div v-else class="file_item_icon mt-3 iconfont icon-PDF1"></div>
        <div class="file_item_text">{{ `${$t("CLICK")}${$t("PREVIEW")}` }}</div>
        <div
          v-if="!disabled"
          class="file_item_cancel iconfont icon-quxiao1 absolute"
          @click.stop="handleDelete(index)"
        ></div>
      </div>
    </div>
    <a-upload
      v-show="showFileList.length === 0 || fileType === 'img'"
      ref="aUpload"
      key="upload1"
      :action="uploadUrl"
      :limit="limit"
      :accept="accept"
      list-type="picture-card"
      :before-upload="beforeUpload"
      :class="{ hide: hideUpload }"
      :default-file-list="fileList"
      :file-list="fileList"
      :remove="handleRemove"
      :disabled="disabled"
      @change="handleChange"
    >
      <div v-if="fileList.length == 0 || fileList.length != limit">
        <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") }}
        </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: "SingleUpload",
  components: {
    MegaDrawer,
  },
  props: {
    // 配合v-model 加载初始值
    value: {
      type: String,
      default: "",
    },
    // 最大值文件个数限制
    limit: {
      type: Number,
      default: 1,
    },
    accept: {
      type: String,
      default: "",
    },
    mutiple: {
      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`,
      dialogImageUrl: "",
      fileName: "",
      imageUrl: "",
      fileList: [],
      showFileList: [],
      dialogVisible: false,
      showUploadInfo: {
        showRemoveIcon: true,
      },
      fileType: "img",
    };
  },
  computed: {
    hideUpload() {
      return this.fileList.length >= this.limit;
    },
  },
  // 监听父组件值是否在变化
  watch: {
    // 有些页面初始初始src没有赋值
    value: {
      handler(newValue, oldValue) {
        this.fileList = [];
        if (!newValue) return;
        this.showFileList = [];
        this.showFileList.push(newValue);
        const i = newValue.lastIndexOf(".");
        const suffix = newValue.slice(i);
        this.checkFileType(suffix);
        this.fileList = 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.fileList = 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 = false;
          this.showFileList.push(item);
        }
      },
      immediate: true,
      deep: true,
    },
  },
  mounted() {
    if (this.value) {
      this.fileList =
        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: {
    // 预览
    handlePreview(item) {
      window.open(fetchFileUrl(item, this));
    },
    // 删除
    handleDelete(index) {
      this.showFileList.splice(index, 1);
      this.fileList.splice(index, 1);
      this.fileType = "img";
    },
    handleRemove(file) {
      // const list = this.fileList.filter(
      //   (item) => item.fileUrl !== file.fileUrl
      // );
      // const resultUrl = list.map((item) => item.fileUrl).join(",");
      this.$emit("input", "");
    },
    // 限制图片大小
    // eslint-disable-next-line
    beforeUpload(file) {
      const suffixs = [
        ".png",
        ".jpg",
        ".gif",
        ".jepg",
        ".jpeg",
        ".ico",
        ".svg",
        ".mp4",
        ".pdf",
        ".PDF",
      ];
      const i = file.name.lastIndexOf(".");
      const suffix = file.name.slice(i);
      this.checkFileType(suffix);
      if (!suffixs.includes(suffix)) {
        this.$message.error(this.$t("PICTURE_FORMAT_ERROR")); // 文件格式错误！
        return false;
      }
      let maxNum = 5;
      if ([".PDF", ".pdf", ".mp4"].includes(suffix)) {
        maxNum = 50;
      }
      const isLt5M = file.size / 1024 / 1024 < maxNum;
      if (!isLt5M) {
        this.$message.error(this.$t("FILESIZE_WARNING")); // 上传文件大小不能超过 5 / 50MB!
        return false;
      }
      return true;
    },
    checkFileType(suffix) {
      if (suffix === ".PDF" || suffix === ".pdf") {
        this.fileType = "pdf";
      } else if (suffix === ".mp4") {
        this.fileType = "video";
      } else {
        this.fileType = "img";
      }
    },
    handleChange(info) {
      this.fileList = 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 = [];
        this.showFileList = [];
        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>
.file_item {
  width: 106px;
  height: 106px;
  background: #f5f7fa;
  border: 1px solid #f2f3f3;
  border-radius: 4px;
  margin-right: 10px;
  .iconfont {
    font-size: 32px;
    color: rgba(0, 104, 150, 1);
  }
  .file_item_cancel {
    font-size: 20px;
    color: #999;
    top: -5px;
    right: 0;
  }
}
</style>
