<template>
  
  <!-- thumbnailUrls.length &&  -->
  <div class="pdf-viewer" v-if="props.showPage">
    <!-- 左侧缩略图 -->
    <div class="thumbnails" v-if="thumbnailUrls.length && props.showPage">
      <div
        v-for="(thumb, index) in thumbnailUrls"
        :key="index"
        class="thumbnail-item"
        :class="{ active: currentPage === index + 1 }"
        @click="goToPage(index + 1)"
      >
        <img :src="thumb" alt="Page thumbnail" />
        <!-- <span>第 {{ index + 1 }} 页</span> -->
        <span>{{ index + 1 }}</span>
      </div>
    </div>

    <!-- 右侧主预览区 -->
    <div class="main-preview" >
      <div class="pdf-container" ref="pdfContainer"></div>
      <div class="toolbar">
        <span :class="['pre_nav',{'first':currentPage === 1} ]"  @click="currentPage <= 1 ? '' : prevPage()">
            <el-icon><ArrowLeftBold /></el-icon>
        </span>
        <span :class="['next_nav',{'end':currentPage >= totalPages}]" @click="currentPage >= totalPages ?  '' : nextPage()">
            <el-icon><ArrowRightBold /></el-icon>
        </span>
        <!-- <span>第 {{ currentPage }} / {{ totalPages }} 页</span> -->
        <!-- <input v-model.number="scale" type="number" min="0.5" max="3" step="0.1" /> 倍 -->
      </div>
    </div>
  </div>
         
  <div class="vue_pdf" v-else>
    <!-- <div class="progress">进度：{{ progressPercent }} %</div> -->
    <VuePdfEmbed 
        class="pdf_preview"
        annotation-layer 
        :scale="1"
        text-layer 
        @rendered="HandlePdfRender"
        :source="props.pdfUrl"
        @loaded="HandlePdfLoaded"
    >
        <template #after-page="{page}">
            <span  class="page_index">
                {{ page }} / {{ totalPages }}  
            </span>
        </template>
    </VuePdfEmbed>
  </div>

</template>

<script setup lang="ts">
import { ref, onMounted, watch,computed } from 'vue';
import pdfjsLib from './pdf.js';


import VuePdfEmbed from 'vue-pdf-embed'
// optional styles
import 'vue-pdf-embed/dist/styles/annotationLayer.css'
import 'vue-pdf-embed/dist/styles/textLayer.css'



const props = defineProps({
  pdfUrl: {
    type: String,
    required: true
  },
  showPage:{
    type:Boolean,
    required:false,
    default:true
  },
  initCourseLearnPage:{
      type:Number,
      required:false,
      default:0
  }

});


const emit = defineEmits(['pageChange'])

// const vuePdfDom = ref()
// 响应式数据
const currentPage = ref(1);
const totalPages = ref(0);
const scale = ref(1);
const thumbnailUrls = ref([]);
const pdfContainer = ref(null);
let pdfDoc = null;

// 加载 PDF  // 带分页
async function loadPdf() {
  try {
    const loadingTask = pdfjsLib.getDocument(props.pdfUrl);
    pdfDoc = await loadingTask.promise;
    totalPages.value = pdfDoc.numPages;
    let tmp = Math.floor(props.initCourseLearnPage * 0.01 * totalPages.value)
    currentPage.value = (tmp === 0 ? 1 : tmp)
    // 生成所有缩略图
    thumbnailUrls.value = [];
    for (let i = 1; i <= pdfDoc.numPages; i++) {
      const thumbUrl = await renderPageToImageUrl(i, 0.2); // 小尺寸缩略图
      thumbnailUrls.value.push(thumbUrl);
    }

    // 渲染第一页
    await renderCurrentPage();
    //  如果 pdf只有一页，默认进度显示100%，
    if(totalPages.value <= 1){
      emit('pageChange',{totalPage:totalPages.value,currentPage:currentPage.value})
    }

  } catch (error) {
    console.error('加载 PDF 失败:', error);
  }
}

// 渲染指定页为图片 URL（用于缩略图或主视图）
async function renderPageToImageUrl(pageNum, renderScale) {
  const page = await pdfDoc.getPage(pageNum);
  const viewport = page.getViewport({ scale: renderScale });
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  canvas.height = viewport.height;
  canvas.width = viewport.width;

  await page.render({
    canvasContext: ctx,
    viewport: viewport
  }).promise;

  return canvas.toDataURL();
}

// 渲染当前页到主区域
const renderCurrentPage = async()=> {
  if (!pdfDoc) return;
  const container = pdfContainer.value;
  container.innerHTML = ''; // 清空

  const imageUrl = await renderPageToImageUrl(currentPage.value, scale.value);
  const img = document.createElement('img');
  img.src = imageUrl;
  img.style.maxWidth = '100%';
  img.style.display = 'block';
  img.style.margin = '0 auto'
  container.appendChild(img);
}

// 翻页
const  prevPage=()=> {
  console.log('点击翻页了')
  if (currentPage.value > 1){
    currentPage.value--;
    renderCurrentPage()
    emit('pageChange',{totalPage:totalPages.value,currentPage:currentPage.value})
  }
}
const nextPage=()=> {
  console.log('点击翻页了')
  if (currentPage.value < totalPages.value){
    currentPage.value++;
    renderCurrentPage()
    emit('pageChange',{totalPage:totalPages.value,currentPage:currentPage.value})
  }
}
const goToPage=(page)=> {
  currentPage.value = page;
  renderCurrentPage()
  emit('pageChange',{totalPage:totalPages.value,currentPage:currentPage.value})
}


const timeoutFlag = ref()
const pageTotalHeight = ref(0)
const currentReadHeight = ref(0)

const progressPercent = computed(()=>{
    if(currentReadHeight.value == 0 || pageTotalHeight.value == 0){
        return 0
    }
    return Math.round((currentReadHeight.value / pageTotalHeight.value) * 100)
})



// 防抖
// 不再连续滚动的时候，记录最后一次滚动的位置，
// 200毫秒内没有再次滚动，就认为用户停止了滚动，此时记录用户的阅读进度
const HandleScroll = (e)=>{
  console.log('页面监听滚动')
    if(timeoutFlag.value){
      clearTimeout(timeoutFlag.value)
    }
    timeoutFlag.value =  setTimeout(() => {

        let totalHeight = e.target.scrollHeight  //总高度
        let scrollTop = e.target.scrollTop   //滚动高度
        let pageHeight = e.target.clientHeight // 客户端高度

        // 用户阅读进度  = ( pageHeight + scrollTop ) / totalHeight
        console.log('滚动事件',e)
        console.log('滚动高度',scrollTop)
        console.log('总高度',totalHeight)
        console.log('客户端高度',pageHeight)

        pageTotalHeight.value = Math.floor(Number(totalHeight)) || 0
        currentReadHeight.value = Math.floor( Number(pageHeight) + Number(scrollTop) ) || 0

        emit('pageChange',{currentProcess:progressPercent.value})
        
        clearTimeout(timeoutFlag.value)
        timeoutFlag.value = null

    }, 200);
}

// pdf 的重定向
const HandlePageRedirect = (dom)=>{
  // props.initCourseLearnPage
  // 根据百分比 换算滚动高度
  let totalHeight = dom.scrollHeight  //总高度
  let pageHeight = dom.clientHeight // 客户端高度

  let realScroll =  props.initCourseLearnPage * 0.01 * totalHeight - pageHeight
  let scrollTop =  realScroll  > 0 ? realScroll : 0

  console.log('高度 - / -',pageHeight,totalHeight)
  console.log('触发滚动了',scrollTop)
    dom.scrollTo({
        top: scrollTop,
        left: 0,
        behavior: 'smooth'
    });

  pageTotalHeight.value = Math.floor(Number(totalHeight)) || 0
  // 用户阅读进度  = ( pageHeight + scrollTop ) / totalHeight
  currentReadHeight.value = Math.floor( Number(pageHeight) + Number(scrollTop) ) || 0
  emit('pageChange',{currentProcess:progressPercent.value})
}



// 渲染在后
const HandlePdfRender = ()=>{
  console.log('pdf渲染完成')

  let vuePdfDom = document.querySelectorAll('.pdf_preview')
  console.log('dom',vuePdfDom)
  HandlePageRedirect(vuePdfDom[0])
}
// 加载在前
const HandlePdfLoaded = ({_pdfInfo,_transport})=>{
    console.log('pdf加载',_pdfInfo)
    // pdf的总页数
    totalPages.value = _pdfInfo.numPages

    let vuePdfDom = document.querySelectorAll('.pdf_preview')
    console.log('dom',vuePdfDom)

    vuePdfDom[0]?.addEventListener('scroll',
    (e)=>{
      // emit('pageChange',{currentProcess:`${progressPercent.value}%`})

      HandleScroll(e)
    },false)



}


// 监听变化
watch(() => props.pdfUrl, ()=>{
  if(props.showPage){
    loadPdf()
  }
});
watch(scale, ()=>{
  if(props.showPage){
    renderCurrentPage()
  }
});

// 初始化
onMounted(() => {
  if(props.showPage){
    loadPdf();
  }
});
</script>

<style lang="scss" scoped>
.pdf-viewer {
  display: flex;
  background-color: #e8eaee;
  height: 100%;
  overflow: auto;
}

.thumbnails {
  width: 120px;
  overflow-y: auto;
  border-right: 1px solid #eee;
  padding:20px 0 20px 10px;
  scrollbar-width:none;
  &::-webkit-scrollbar {
    display: none; /* Chrome, Safari, Opera*/
  }
    
  .thumbnail-item {
    cursor: pointer;
    margin-bottom: 10px;
    text-align: center;
    font-size: 12px;
    color: #333;
    position: relative;
    display: flex;


    img {
      width: 100%;
      border: 1px solid white;
      border-radius: 4px;
    }

    span{
      position: absolute;
      bottom: 10px;
      left: 10px;
      display: flex; 
      align-items: center;
      justify-content: center;
      width: 20px;
      height: 20px;
      background-color:rgba(0, 0, 0,0.2);
      color: white;
    }

    &.active {
      border-radius: 4px;
      img{
        border-color: #2E64FA;
      }
      span{
        background-color:rgba(0, 0, 0,0.5);
      }
    }
  }
}

.main-preview {
  position: relative;
  flex: 1;
  display: flex;
  flex-direction: column;

    
  .toolbar {
    display: flex;
    justify-content: space-between;
    position: absolute;
    width: calc(100% - 100px);
    bottom:50%;
    left: calc( 50px);

    .pre_nav,
    .next_nav{
        line-height: 1;
        border-radius: 20px;
        padding:10px;
        background-color: #415058;
        color:white;
    }
    .first,
    .end{
        background-color: #c3c8d0;
    }
  }
    
  .pdf-container {
    position: relative;
    width: 100%;
    flex: 1;
    margin: 0 auto;
    padding: 20px;
    overflow: auto;
  }
}


.page_index{
  position: absolute;
  bottom: 50px;
  display: inline-block;
  width: 100%;
  text-align: center;
}

.vue_pdf{
  position: relative;
  display: flex;
  flex-direction: column;
  overflow: auto;
  .progress{
    z-index: 100;
    background-color: rgb(241, 235, 235);
    position: absolute;
    top:50px;
    right: 50px;
  }
}

.vue-pdf-embed.pdf_preview{
    width: 100% !important;
    height: 100% !important;
    box-sizing: border-box;
    overflow: auto;
    > :deep(div){
      position: relative;
      overflow: auto;
      width: 100%;

      .vue-pdf-embed__page{
        position: relative;
        overflow: auto;
        width: 100% !important;
        height: 100% !important;
        box-sizing: border-box;
        padding: 20px;
        background-color: #e8eaee !important;

        canvas{
            width: 100% !important;
            height: 100%;
            background-color: #e8eaee !important;
        }
        .annotationLayer,
        .textLayer{
            width: 100% !important;
            height: 100% !important;
        }
      }
    }
}

</style>
