<script setup lang="ts">
import { ref, shallowRef } from 'vue';
import VuePdfEmbed from 'vue-pdf-embed';
import { useLoading } from '~/packages/hooks';

defineOptions({
  name: 'PdfPreview'
});

const source = defineModel('source', {
  default: 'https://xiaoxian521.github.io/hyperlink/pdf/Cookie%E5%92%8CSession%E5%8C%BA%E5%88%AB%E7%94%A8%E6%B3%95.pdf'
});

withDefaults(defineProps<{ title?: string }>(), { title: 'PDF预览' });

const { loading, endLoading } = useLoading(true);
const pdfRef = shallowRef<InstanceType<typeof VuePdfEmbed> | null>(null);

// 是否分页显示
const showAllPages = ref(false);
// 当前页码
const currentPage = ref<undefined | number>(1);
// 旋转角度
const pageCount = ref(1);

// 旋转角度
const rotations = [0, 90, 180, 270];
// 当前角度的索引值拿的是rotations的索引值，所以这里用的是0
const currentRotation = ref(0);

// 切换角度
function handleRotate() {
  currentRotation.value = (currentRotation.value + 1) % 4;
}

// 是否显示分页
function showAllPagesChange() {
  currentPage.value = showAllPages.value ? undefined : 1;
}

// 渲染完成
function onPdfRendered() {
  endLoading();

  if (pdfRef.value?.doc) {
    pageCount.value = pdfRef.value.doc.numPages;
  }
}

// 打印PDF文件
async function handlePrint() {
  // 随机名称
  await pdfRef.value?.print(undefined, getPdfName(), true);
}

// 下载PDF文件
async function handleDownload() {
  await pdfRef.value?.download(getPdfName());
}

function getPdfName() {
  const name = source.value.split('/');
  return decodeURIComponent(name[name.length - 1]) || 'pdf文档.pdf';
}
</script>

<template>
  <NCard
    :title="title"
    :bordered="false"
    class="h-full card-wrapper"
    content-class="overflow-hidden flex-col-stretch box-border"
  >
    <template #header-extra>
      <div class="flex-y-center justify-end gap-12px">
        <NCheckbox v-model:checked="showAllPages" @update:checked="showAllPagesChange">是否分页显示</NCheckbox>
        <ButtonIcon tooltip-content="旋转90度" @click="handleRotate">
          <icon-material-symbols-light-rotate-90-degrees-ccw-outline-rounded />
        </ButtonIcon>
        <ButtonIcon tooltip-content="打印" @click="handlePrint">
          <icon-mdi-printer />
        </ButtonIcon>
        <ButtonIcon tooltip-content="下载" @click="handleDownload">
          <icon-charm-download />
        </ButtonIcon>
      </div>
    </template>
    <NScrollbar class="flex-1-hidden">
      <NSkeleton v-if="loading" size="small" class="mt-12px" text :repeat="12" />
      <VuePdfEmbed
        ref="pdfRef"
        class="overflow-auto container"
        :class="{ 'h-0': loading }"
        :rotation="rotations[currentRotation]"
        :page="currentPage"
        :source="source"
        @rendered="onPdfRendered"
      />
    </NScrollbar>
    <div class="flex-center pt-20px">
      <div v-if="showAllPages" class="text-18px font-medium">共{{ pageCount }}页</div>
      <NPagination v-else v-model:page="currentPage" :page-count="pageCount" :page-size="1" />
    </div>
  </NCard>
</template>

<style scoped></style>
