<template>
  <div>
    <div class="file_list_multiple flex">
      <div
        v-for="(item, index) in images"
        :key="index"
        class="file_item relative text-left cursor-pointer mb-5 pl-4"
        :class="{
          'not-disabled': !disabled,
          'not-finish': fileList.length && fileList[index].percent !== 100,
        }"
        @click="handlePreview(item)"
      >
        <div
          v-if="isVideo(item.name)"
          class="file_item_icon iconfont icon-shipin1"
        />
        <div v-else class="file_item_icon iconfont icon-PDF1" />
        <!-- <div class="file_item_text">{{ `${$t("CLICK")}${$t("PREVIEW")}` }}</div> -->
        <div class="file_item_text ml-3" :title="item.name">
          {{ item.name }}
        </div>
        <a-progress
          v-show="fileList.length && fileList[index].percent !== 100"
          :stroke-color="{
            '0%': '#108ee9',
            '100%': '#87d068',
          }"
          :percent="
            Number(fileList.length && fileList[index].percent.toFixed(2))
          "
          class="progress-line"
        />
        <div
          v-if="!disabled && !loading"
          class="file_item_cancel iconfont icon-quxiao1 absolute"
          @click.stop="handleDelete(item, index)"
        />
      </div>
      <i></i><i></i><i></i><i></i><i></i>
    </div>
    <a-upload
      v-if="!disabled"
      ref="aUpload"
      :key="time"
      :action="uploadUrl"
      :accept="accept"
      list-type="picture-card"
      :before-upload="beforeUpload"
      :default-file-list="fileList"
      :multiple="true"
      :show-upload-list="false"
      :disabled="disabled"
      @change="handleChange"
      @preview="handlePreview"
    >
      <div>
        <i
          v-if="!loading"
          slot="default"
          class="iconfont icon-ge_shangchuan"
          style="font-size: 18px; color: #0ea8d0"
        />
        <a-icon v-else type="loading" />
        <div class="ant-upload-text" style="font-size: 12px; color: #666">
          {{ $t("UPLOAD") }}
        </div>
      </div>
    </a-upload>
    <div v-if="!disabled" class="upload-info">
      {{ `* ${$t("PDF_VIDEO_NOT_EXCEED_25")}!` }}
    </div>
    <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: ".mp4, .pdf, .PDF",
    },
    // 最大值文件个数限制
    limit: {
      type: Number,
      default: 1,
    },
    mutiple: {
      type: Boolean,
      default: false,
    },
    fileUrlList: {
      type: Array,
      default() {
        return [];
      },
    },
    isShowUploadButton: {
      type: Boolean,
      default: true,
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  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(newValue, oldValue) {
        this.images = [];
        if (!newValue.length) return;
        this.images = newValue.map((item) => {
          const obj = {};
          obj.url = fetchFileUrl(item.fileUrl, this);
          obj.fileUrl = item.fileUrl;
          obj.name = item.name;
          obj.status = "done";
          obj.uid = item.fileUrl;
          return obj;
        });
      },
      immediate: false,
    },
    fileUrlList: {
      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, this);
            obj.fileUrl = item.fileUrl;
            obj.name = item.name;
            obj.status = "done";
            obj.percent = 100;
            obj.uid = item.fileUrl;
            return obj;
          });
          this.showUploadInfo.showRemoveIcon = this.isShowUploadButton;
          this.curCount = this.fileList.length;
        } else {
          this.fileList = [];
        }
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    // 限制图片大小
    // eslint-disable-next-line
    beforeUpload(file, fileList) {
      const len = fileList.length + this.images.length;
      const suffixs = [".mp4", ".pdf", ".PDF", ".MP4"];
      const i = file.name.lastIndexOf(".");
      const suffix = file.name.slice(i);
      const isLt5M = file.size / 1024 / 1024 < 25;
      // 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("CUSTOM_FILE_SIZE_WARNING").replace("{}", 25)
          );
          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;
        this.$emit("canSave", 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 = {
        //     name: item.name ? item.name : item?.response?.data?.fileName,
        //     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);
        const result = info.fileList.findIndex((file) => {
          return file.percent < 100;
        });
        if (result === -1) {
          this.loading = false;
          this.$emit("canSave", false);
        }
      }
      const list = [];
      info.fileList.forEach((item) => {
        const data = {
          name: item.name ? item.name : item?.response?.data?.fileName,
          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);
      this.fileList = [...info.fileList];
    },
    isVideo(fileUrl) {
      if (fileUrl) {
        const i = fileUrl.lastIndexOf(".");
        const suffix = fileUrl.slice(i);
        const fileType = this.checkFileType(suffix);
        return fileType === "video";
      }
      return false;
    },
    checkFileType(suffix) {
      let fileType = "img";
      if (suffix === ".PDF" || suffix === ".pdf") {
        fileType = "pdf";
      } else if (suffix === ".mp4") {
        fileType = "video";
      }
      return fileType;
    },
    // 删除
    handleDelete(file, index) {
      const idx = this.fileList.findIndex((item) => {
        const fileUrl = item.fileUrl
          ? item.fileUrl
          : item?.response?.data?.fileUrl;
        if (fileUrl === file.fileUrl) {
          return true;
        }
        return false;
      });
      this.images.splice(index, 1);
      if (idx > -1) {
        this.$refs.aUpload.handleRemove(this.fileList[idx]);
        this.fileList.splice(idx, 1);
      }
      const resultUrl = [...this.images]; // .map((item) => item.fileUrl).join(",");
      this.$emit("input", resultUrl);
    },
    // 預覽圖片
    handlePreview(file) {
      window.open(
        fetchFileUrl(
          file.fileUrl ? file.fileUrl : file.response.data.fileUrl,
          this
        )
      );
    },
  },
};
</script>
<style lang="less" scope>
.login-name {
  position: absolute;
  bottom: -25px;
}
.file_list_multiple {
  // display: inline-block;
  vertical-align: top;
  flex-flow: row wrap;
  justify-content: space-between;
  .file_item {
    display: inline-block;
    width: 19%;
    height: 56px;
    line-height: 56px;
    background: #f4f7f9;
    border-radius: 4px;
    .iconfont {
      display: inline-block;
      font-size: 32px;
      color: rgba(0, 104, 150, 1);
    }
    .file_item_text {
      display: inline-block;
      width: calc(100% - 52px);
      vertical-align: top;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .progress-line {
      position: absolute;
      top: 100%;
      left: 0;
      transform: translateY(-50%);
    }
    .file_item_cancel {
      display: none;
      font-size: 20px;
      color: #999;
      right: 10px;
    }
  }
  & > i {
    width: 19%;
  }
  .file_item.not-disabled:hover {
    padding-right: 40px;
    .file_item_cancel {
      display: inline-block;
    }
  }
  .file_item.not-finish {
    background: rgba(244, 247, 249, 0.5);
  }
}
.upload-info {
  margin-top: -1.3rem;
  font-size: 14px;
  line-height: 40px;
  color: #c0c4cc;
}
</style>
