<template>
  <div>
    <div class="header">
      <el-button type="primary" link class="back" @click="goBack"
        >返回</el-button
      >
      {{ title || "微方志" }}
      <el-button
        type="text"
        class="search"
        :icon="Search"
        @click="handleOpenSearch"
      >
        全文搜索
      </el-button>
    </div>
    <BookReader
      :pages="pages"
      :is-pdf="true"
      :pdfUrl="pdfUrl"
      :bookmarks="bookmarks"
      :enableTextLayer="true"
      ref="bookReaderRef"
    />
    <SearchBar ref="searchBarRef" @locatePage="locatePage" />
  </div>
</template>
<script setup>
import { getDocumentDetail, getDocumentBookmarks } from "@/api";
import BookReader from "@/components/BookReader/index.vue";
import { Search } from "@element-plus/icons-vue";
const route = useRoute();
const router = useRouter();
/* props */
/* emit */
/* data */
const title = ref("");
const pages = ref([]);
const bookmarks = ref([]);
const pdfUrl = ref("");
const searchBarRef = ref(null);
const bookReaderRef = ref(null);

/* computed */
/* methods */
async function loadData(id) {
  const res = await getDocumentDetail(id);
  pages.value = res.map((item) => {
    return {
      ...item,
      page_url: import.meta.env.VITE_API_BASE_URL + "/static/" + item.page_url,
      images: item.images.map((img) => {
        return {
          ...img,
          url: import.meta.env.VITE_API_BASE_URL + "/static/" + img.url,
        };
      }),
    };
  });
}

function goBack() {
  // router.go(-1);
  router.push("/");
}

async function fetchBookmarks(id) {
  try {
    const res = await getDocumentBookmarks(id);
    if (res.status == "success") {
      localStorage.setItem(`bookmarks-${id}`, JSON.stringify(res.bookmarks));
      bookmarks.value = res.bookmarks;
    }
  } catch (error) {
    console.log(error);
  } finally {
  }
}

function handleOpenSearch() {
  searchBarRef.value.show();
}

function locatePage(pageNum) {
  if (bookReaderRef.value) {
    bookReaderRef.value.goToPage(pageNum);
  }
}

onMounted(() => {
  const { id } = route.params;
  title.value = route.query.title;
  pdfUrl.value = route.query.pdfUrl;
  loadData(id);
  const bookmarksData = JSON.parse(localStorage.getItem(`bookmarks-${id}`));
  if (bookmarksData) {
    bookmarks.value = bookmarksData;
  } else {
    fetchBookmarks(id);
  }
});
</script>
<style lang="scss" scoped>
.header {
  background-color: #444;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  height: 46px;
  padding: 0 40px;
  .back {
    position: absolute;
    left: 20px;
    top: 50%;
    transform: translateY(-50%);
  }
  .search {
    position: absolute;
    right: 20px;
    top: 50%;
    transform: translateY(-50%);
    color: #fff;
  }
}
</style>
