<template>
  <page-pane
    v-loading.fullscreen.lock="loading"
    class="detail"
    :container-color="paneBgColor"
    :simple="isPhotocopy"
  >
    <component v-if="detail" :is="comp" :is-login="isLogin" :detail="detail" />
  </page-pane>

  <toolbar v-if="route.params.type === 'reader'" />
  <introduction-dialog v-model:visible="introductionVisible" :detail="detail" />
</template>

<script setup>
import { computed, ref, watch, onUnmounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { THEMES } from "@lsq/base";
import { getBookDetailApi, getBookDetail2Api } from "@/api";
import { storeToRefs } from "pinia";
import { useEpubStore, useDetailStore, useBaseStore } from "@/stores";
import Toolbar from "./components/Toolbar/index.vue";
import Reader from "./components/Reader/index.vue";
import Photocopy from "./components/Photocopy/index.vue";
import DetailVideo from "./components/Video/index.vue";
import IntroductionDialog from "./components/IntroductionDialog.vue";

const route = useRoute();
const router = useRouter();
const baseStore = useBaseStore();
const epubStore = useEpubStore(window.pinia);
const detailStore = useDetailStore();
const { isLogin } = storeToRefs(baseStore);
const { introductionVisible, detail } = storeToRefs(detailStore);

const loading = ref(false);
const paneBgColor = computed(
  () => THEMES.find((theme) => theme.key === epubStore.curTheme).color
);
const isPhotocopy = computed(() => route.params.type === "photocopy");

const comp = computed(() => {
  switch (route.params.type) {
    case "photocopy":
      return Photocopy;
    case "video":
      return DetailVideo;
    default:
      return Reader;
  }
});

const getBookDetail = async () => {
  try {
    loading.value = true;
    const data = await (isLogin.value ? getBookDetail2Api : getBookDetailApi)(
      route.params.id
    );
    if (!data) {
      ElMessage.warning("图书丢失了");
      router.replace({ name: "home" });
      return;
    }
    detail.value = data;
  } finally {
    loading.value = false;
  }
};

watch(
  isLogin,
  () => {
    getBookDetail();
  },
  {
    immediate: true,
  }
);

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

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