<template>
  <div v-loading="loading" class="photocopy">
    <template v-if="!noData">
      <div class="photocopy-left">
        <el-image :src="baseUrl + list[curIndex]?.thumb" fit="contain" />

        <div class="photocopy-left__prev" @click="handlePrev" />
        <div class="photocopy-left__next" @click="handleNext" />

        <div class="photocopy-left__magnify" @click="viewerVisible = true" />

        <div class="photocopy-left__pagination">
          {{ curIndex + 1 }}/{{ total }}
        </div>
      </div>

      <el-scrollbar class="photocopy-right">
        <div
          v-if="list[curIndex]?.description"
          v-html="list[curIndex].description"
        />

        <div v-else id="reader" />
      </el-scrollbar>
    </template>

    <el-empty v-else description="暂无数据" style="width: 100%" />
  </div>

  <el-image-viewer
    v-if="viewerVisible"
    :url-list="list.map((i) => `${baseUrl}${i.thumb}`)"
    :initial-index="curIndex"
    @close="viewerVisible = false"
  />
</template>

<script setup>
import { watch, ref, nextTick, onUnmounted } from "vue";
import { usePagination } from "@lsq/base";
import { useEpubStore } from "@/stores";
import { getMediaListApi } from "@/api";
import { getBaseUrl } from "@/utils";

const props = defineProps(["detail", "isLogin"]);
const curIndex = ref(0);
const viewerVisible = ref(false);
const baseUrl = getBaseUrl();
const epubStore = useEpubStore(window.pinia);

const { total, loading, list, noData, getList } = usePagination(
  async (params) => {
    return getMediaListApi({
      ...params,
      pageSize: 999,
      bookId: props.detail.id,
      type: "img",
    });
  }
);

const handlePrev = () => {
  curIndex.value = Math.max(curIndex.value - 1, 0);
  epubStore.prePage();
};

const handleNext = () => {
  curIndex.value = Math.min(curIndex.value + 1, list.value.length - 1);
  epubStore.nextPage();
};

const handleInit = async () => {
  await getList();
  nextTick(() => {
    epubStore.init({
      ghost: true,
      url: baseUrl + props.detail.filePath,
    });
  });
};

watch(
  () => props.detail,
  () => {
    props.detail && handleInit();
  },
  {
    immediate: true,
  }
);

onUnmounted(() => {
  epubStore.clear();
});
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>
