<template>
  <el-dialog
    class="page-dialog"
    :visible.sync="modalIsShow"
    title="预览"
    fullscreen
    append-to-body
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @open="visibleChange"
    @close="dialogClose"
  >
    <div class="infinite-list-wrapper" style="overflow: auto">
      <ul
        class="list"
        v-infinite-scroll="load"
        infinite-scroll-disabled="disabled"
      >
        <li v-for="url in imageList" :key="url" style="margin-bottom: 10px">
          <image-watermark :content="content" :url="url"></image-watermark>
        </li>
      </ul>
      <p v-if="loading">
        <i class="el-icon-loading"></i>
      </p>
    </div>
    <div slot="footer"></div>
  </el-dialog>
</template>

<script>
import ImageWatermark from "./ImageWatermark.vue";
import { attachmentPreview } from "@/modules/login/api";

export default {
  name: "preview-attachment",
  components: { ImageWatermark },
  props: {
    attachmentIds: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      sources: [],
      imageList: [],
      content: "",
      loading: false,
      pageSize: 2,
    };
  },
  computed: {
    noMore() {
      return this.sources.length === 0;
    },
    disabled() {
      return this.loading || this.noMore;
    },
  },
  created() {
    const { loginName, realName } = this.$ls.get("user", {});
    this.content = `${realName}(${loginName})`;
  },
  methods: {
    visibleChange() {
      this.getAttachments();
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    dialogClose() {
      this.sources = [];
      this.imageList = [];
    },
    async getAttachments() {
      if (!this.attachmentIds || !this.attachmentIds.length) return;
      const res = await attachmentPreview(this.attachmentIds);
      this.sources = (res || []).map((item) => item.url);

      if (this.sources.length) this.load();
    },
    load() {
      this.loading = true;
      const imgs = this.sources.splice(0, this.pageSize);
      this.imageList.push(...imgs);

      this.$nextTick(() => {
        this.loading = false;
      });
    },
  },
};
</script>
