<template>
    <div class="pdf-preview" ref="pdfPreviewRef">
        <div v-if="loading" class="loading-wrapper">
            <el-progress :percentage="percentage" :stroke-width="15" striped striped-flow />
        </div>

        <div
            class="wapper"
            :style="{
                transform: `translate(-50%,-50%) scale(${scaleData})`,
                height: `${pageHeight}`
            }"
        >
            <div class="pdf-wrap" ref="pdfWrapRef">
                <vue-pdf-embed
                    :source="state.source"
                    :class="['vue-pdf-embed', { 'fullscreen-pdf': isFullscreen }]"
                    :page="state.pageNum"
                    :width="wrapperWidth"
                    @loaded.once="onPdfLoaded"
                    @progress="onPdfProgress"
                />
            </div>
        </div>

        <div class="page-tool" v-if="!loading" :class="{ collapsed: !toolsShow }">
            <div class="page-tool-item" @click="toggleToolsState">
                {{ toolsShow ? '隐藏' : '工具栏' }}
            </div>
            <template v-if="toolsShow">
                <div class="page-tool-item">{{ state.pageNum }}/{{ state.numPages }}</div>
                <div class="page-tool-item" @click="lastPage">上一页</div>
                <div class="page-tool-item" @click="nextPage">下一页</div>
                <div class="page-tool-item" @click="pageZoomOut">放大</div>
                <div class="page-tool-item" @click="pageZoomIn">缩小</div>
                <div class="page-tool-item" @click="pageZoomBack">还原</div>
                <div class="page-tool-item" @click="toggleFullScreen">
                    {{ isFullscreen ? '退出全屏' : '全屏' }}
                </div>
            </template>
        </div>
    </div>
</template>

<script setup lang="ts">
import { reactive, onMounted, computed, ref, onUnmounted } from 'vue'
import VuePdfEmbed from 'vue-pdf-embed'
import screenfull from 'screenfull'

const props = defineProps({
    pdfUrl: {
        type: String,
        required: true
    },
    fileSize: {
        type: Number,
        required: true
    }
})

const state = reactive({
    source: props.pdfUrl,
    pageNum: 1,
    numPages: 0
})

const loading = ref(false)
const loadedSize = ref(0)
const scaleData = ref(1.0)
const pageHeight = ref('100%')
const isFullscreen = ref(false)
const toolsShow = ref(true)
const pdfPreviewRef = ref()
const pdfWrapRef = ref()
const wrapperWidth = ref(0)
const isScrolling = ref(false)

const percentage = computed(() => {
    return Number(((loadedSize.value / props.fileSize) * 100).toFixed(0))
})

// PDF 事件处理
function onPdfProgress(progress: any) {
    loadedSize.value = progress.loaded
}

function onPdfLoaded(pdf: any) {
    state.numPages = pdf.numPages
    loading.value = false
}

// 页面控制
function lastPage() {
    if (state.pageNum > 1) {
        state.pageNum -= 1
    }
}

function nextPage() {
    if (state.pageNum < state.numPages) {
        state.pageNum += 1
    }
}

// 缩放控制
function pageZoomOut() {
    if (scaleData.value < 2) {
        scaleData.value += 0.1
        pageHeight.value = parseInt(pageHeight.value) - 5.0 + '%'
    }
}

function pageZoomIn() {
    if (scaleData.value > 1) {
        scaleData.value -= 0.1
        pageHeight.value = parseInt(pageHeight.value) + 5.0 + '%'
    }
}

function pageZoomBack() {
    scaleData.value = 1.0
    pageHeight.value = '100%'
}

// 全屏控制
function handleFullScreenChange() {
    isFullscreen.value = screenfull.isFullscreen
}

function toggleFullScreen() {
    if (!screenfull.isEnabled) return
    screenfull.toggle(pdfPreviewRef.value)
}

// 工具栏控制
function toggleToolsState() {
    toolsShow.value = !toolsShow.value
    const tool = document.querySelector('.page-tool') as HTMLElement
    if (!tool) return

    if (toolsShow.value) {
        // 显示时回到底部中央
        tool.style.bottom = '20px'
        tool.style.right = 'auto'
        tool.style.left = '50%'
        tool.style.transform = 'translateX(-50%)'
    } else {
        // 隐藏时移到右下角
        tool.style.bottom = '20px'
        tool.style.right = '20px'
        tool.style.left = 'auto'
        tool.style.transform = 'none'
    }
}

// 尺寸监听
let resizeObserver: ResizeObserver | null = null

function setupResizeObserver() {
    if (!pdfWrapRef.value) return

    resizeObserver = new ResizeObserver((entries) => {
        for (const entry of entries) {
            wrapperWidth.value = entry.contentRect.width
        }
    })
    resizeObserver.observe(pdfWrapRef.value)
}

function destroyResizeObserver() {
    resizeObserver?.disconnect()
}

// 滚轮翻页功能
function handleWheel(event: WheelEvent) {
    if (event.ctrlKey || isScrolling.value) return // 防抖检查

    const container = pdfWrapRef.value
    if (!container) return

    const { scrollTop, scrollHeight, clientHeight } = container

    if (event.deltaY > 0) {
        // 向下滚动，检查是否到达底部
        if (scrollTop + clientHeight >= scrollHeight - 5 && state.pageNum < state.numPages) {
            event.preventDefault()
            isScrolling.value = true
            nextPage()
            setTimeout(() => {
                container.scrollTop = 0
                isScrolling.value = false
            }, 300)
        }
    } else {
        // 向上滚动，检查是否到达顶部
        if (scrollTop <= 5 && state.pageNum > 1) {
            event.preventDefault()
            isScrolling.value = true
            lastPage()
            setTimeout(() => {
                container.scrollTop = container.scrollHeight - container.clientHeight
                isScrolling.value = false
            }, 300)
        }
    }
}

function setupWheelListener() {
    if (pdfWrapRef.value) {
        pdfWrapRef.value.addEventListener('wheel', handleWheel, { passive: false })
    }
}

function destroyWheelListener() {
    if (pdfWrapRef.value) {
        pdfWrapRef.value.removeEventListener('wheel', handleWheel)
    }
}

onMounted(() => {
    loading.value = true
    setupResizeObserver()
    setupWheelListener()
    if (screenfull.isEnabled) {
        screenfull.on('change', handleFullScreenChange)
    }
})

onUnmounted(() => {
    if (screenfull.isEnabled) {
        screenfull.off('change', handleFullScreenChange)
    }
    destroyResizeObserver()
    destroyWheelListener()
})
</script>

<style lang="scss" scoped>
.pdf-preview {
    position: relative;
    height: 100%;
    width: 100%;
    max-width: 1200px;
    box-sizing: border-box;
    overflow: hidden;
    // background: rgba(11, 47, 77, 1);
    /* 设置滚动条的样式  background-color: #0f3a5c;*/
    ::-webkit-scrollbar {
        width: 10px !important;
        height: 10px !important;
        background-color: transparent;
        border-radius: 0;
    }

    /* 滚动槽 */
    ::-webkit-scrollbar-track {
        border-radius: 6px;
        background-color: transparent !important;
    }

    /* 滚动条滑块 */
    ::-webkit-scrollbar-thumb {
        border-radius: 6px;
        background-color: rgba($color: $border-color-base, $alpha: 0.5);
    }
}

.loading-wrapper {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 60%;
    z-index: 10;
}

.pdf-wrap {
    height: 100%;
    width: 100%;
    overflow-y: auto;
    overflow-x: hidden;
}

.wapper {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 50%;
    left: 50%;
}

.vue-pdf-embed {
    width: 100%;
    height: 100%;
    margin: 0 auto;
    transition: all 0.3s ease;
}

.fullscreen-pdf {
    width: 100vw !important;
    height: 100vh !important;
}

.page-tool {
    position: absolute;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    align-items: center;
    background: rgba(11, 47, 77, 0.9);
    color: white;
    border-radius: 25px;
    z-index: 20;
    backdrop-filter: blur(10px);
    transition: all 0.3s ease;

    &.collapsed {
        width: auto;

        .page-tool-item:not(:first-child) {
            display: none;
        }
    }
}

.page-tool-item {
    padding: 12px 16px;
    cursor: pointer;
    white-space: nowrap;
    font-size: 14px;
    transition: background-color 0.2s ease;

    &:hover {
        background-color: rgba(255, 255, 255, 0.1);
    }

    &:first-child {
        border-radius: 25px 0 0 25px;
    }

    &:last-child {
        border-radius: 0 25px 25px 0;
    }

    &:only-child {
        border-radius: 25px;
    }
}
</style>
