import * as pdfjsLib from 'pdfjs-dist'

// 设置worker路径
pdfjsLib.GlobalWorkerOptions.workerSrc = '/static/libs/pdf.worker.min.mjs'

// 设置兼容性配置
pdfjsLib.GlobalWorkerOptions.useSystemFonts = false
pdfjsLib.GlobalWorkerOptions.disableFontFace = false

// 全局存储PDF状态
const pdfViewers = new Map()

// 触摸事件阈值（像素）
const TOUCH_MOVE_THRESHOLD = 5 // 移动超过5px算拖拽，否则算点击

// ======================== 主函数 ========================

/**
 * 加载并显示PDF文档
 * @param {string} url - PDF文件URL
 * @param {string} id - Canvas元素ID
 * @returns {Promise} Promise对象
 */
export const seepdf = function(url, id) {
    return new Promise((resolve, reject) => {
        try {
            // 清理之前的PDF查看器
            cleanupPdfViewer(id)
            
            // 创建容器
            const containerInfo = createPdfContainer(id)
            if (!containerInfo || !containerInfo.canvas) {
                reject(new Error(`Canvas元素 ${id} 创建失败`))
                return
            }
            
            const { container, canvas } = containerInfo
            
            // 显示加载状态
            showLoadingState(container, id)
            
            // 加载PDF文档
            const loadingTask = pdfjsLib.getDocument({
                url: url,
                cMapUrl: 'https://unpkg.com/pdfjs-dist@3.11.174/cmaps/',
                cMapPacked: true,
                disableStream: true,
                disableAutoFetch: true,
                disableRange: true  // 提高兼容性
            })
            
            loadingTask.promise.then(async (pdf) => {
                try {
                    // 存储PDF信息
                    const pdfInfo = {
                        pdf: pdf,
                        currentPage: 1,
                        totalPages: pdf.numPages,
                        currentScale: 1.0,
                        currentRotation: 0, // 添加旋转角度属性
                        pages: new Map(),
                        container: container,
                        canvas: canvas,
                        isDragging: false,
                        dragStartX: 0,
                        dragStartY: 0,
                        scrollStartX: 0,
                        scrollStartY: 0,
                        canDrag: false, // 当图片比容器大时才允许拖拽
                        touchData: {
                            startX: 0,
                            startY: 0,
                            lastX: 0,
                            lastY: 0,
                            startTime: 0,
                            isTouchMoving: false,
                            hasMoved: false
                        }
                    }
                    pdfViewers.set(id, pdfInfo)
                    
                    // 初始化拖拽功能
                    initDragFunctionality(id)
                    
                    // 初始化多页支持
                    await initMultiPagePDF(id, pdf)
                    
                    // 添加分页控件（如果多页）
                    if (pdf.numPages > 1) {
                        addPaginationControls(container, id, pdf.numPages)
                    }
                    
                    // 初始化缩放功能
                    setTimeout(() => {
                        initZoomControls(id)
                    }, 100)
                    
                    // 初始适应窗口
                    setTimeout(() => {
                        zoomToFit(id)
                    }, 150)
                    
                    // 隐藏加载状态
                    hideLoadingState(id)
                    
                    resolve(pdfInfo)
                } catch (error) {
                    hideLoadingState(id)
                    showErrorState(container, id, 'PDF初始化失败')
                    console.error('PDF初始化失败:', error)
                    reject(error)
                }
            }).catch((error) => {
                hideLoadingState(id)
                showErrorState(container, id, 'PDF加载失败')
                console.error('PDF加载失败:', error)
                reject(error)
            })
        } catch (error) {
            console.error('PDF查看器创建失败:', error)
            reject(error)
        }
    })
}

// ======================== 清理函数 ========================

/**
 * 清理PDF查看器
 */
function cleanupPdfViewer(canvasId) {
    // 清理容器
    const container = document.getElementById(`${canvasId}-container`)
    if (container) {
        container.remove()
    }
    
    // 清理控件
    const zoomControls = document.getElementById(`zoom-controls-${canvasId}`)
    if (zoomControls) {
        zoomControls.remove()
    }
    
    const paginationControls = document.getElementById(`pagination-controls-${canvasId}`)
    if (paginationControls) {
        paginationControls.remove()
    }
    
    const loadingOverlay = document.getElementById(`pdf-loading-${canvasId}`)
    if (loadingOverlay) {
        loadingOverlay.remove()
    }
    
    const errorOverlay = document.getElementById(`pdf-error-${canvasId}`)
    if (errorOverlay) {
        errorOverlay.remove()
    }
    
    // 清理PDF数据
    if (pdfViewers.has(canvasId)) {
        const viewer = pdfViewers.get(canvasId)
        if (viewer && viewer.pdf) {
            viewer.pdf.destroy()
        }
        if (viewer && viewer.pages) {
            viewer.pages.clear()
        }
        pdfViewers.delete(canvasId)
    }
}

// ======================== 容器创建 ========================

/**
 * 创建PDF容器
 */
function createPdfContainer(canvasId) {
    const containerId = `${canvasId}-container`
    
    // 创建容器
    const container = document.createElement('div')
    container.id = containerId
    container.className = 'pdf-viewer-container'
    container.style.cssText = `
        position: relative;
        width: 100%;
        height: 500px;
        overflow: auto;
        border: 1px solid #ddd;
        background-color: #f5f5f5;
        border-radius: 4px;
        cursor: grab;
        user-select: none;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        touch-action: pan-y; /* 允许垂直滚动，防止浏览器默认行为 */
    `
    
    // 创建Canvas
    const canvas = document.createElement('canvas')
    canvas.id = canvasId
    canvas.style.cssText = `
        display: block;
        margin: 0 auto;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        pointer-events: none;
    `
    
    // 添加到容器
    container.appendChild(canvas)
    
    // 添加到页面
    const dialogBody = document.querySelector('#el-dialog__body') || 
                      document.querySelector('.dialog-body') || 
                      document.body
    
    // 清除可能存在的旧容器
    const oldContainer = dialogBody.querySelector(`#${containerId}`)
    if (oldContainer) {
        oldContainer.remove()
    }
    
    dialogBody.appendChild(container)
    
    // 添加缩放控件
    addZoomControls(container, canvasId)
    
    return { container, canvas }
}

// ======================== 拖拽功能 ========================

/**
 * 初始化拖拽功能
 */
function initDragFunctionality(canvasId) {
    const viewer = pdfViewers.get(canvasId)
    if (!viewer || !viewer.container) return
    
    const container = viewer.container
    let isDragging = false
    let dragStartX, dragStartY
    let scrollStartX, scrollStartY
    
    // 鼠标按下事件
    container.addEventListener('mousedown', (e) => {
        if (!viewer.canDrag) return
        
        if (e.button === 0) { // 左键
            e.preventDefault()
            e.stopPropagation()
            isDragging = true
            dragStartX = e.clientX
            dragStartY = e.clientY
            scrollStartX = container.scrollLeft
            scrollStartY = container.scrollTop
            
            // 更改鼠标样式
            container.style.cursor = 'grabbing'
            container.style.cursor = '-webkit-grabbing'
        }
    })
    
    // 鼠标移动事件
    container.addEventListener('mousemove', (e) => {
        if (!isDragging || !viewer.canDrag) return
        
        e.preventDefault()
        e.stopPropagation()
        
        const deltaX = e.clientX - dragStartX
        const deltaY = e.clientY - dragStartY
        
        // 反向移动容器滚动位置（实现拖拽效果）
        container.scrollLeft = scrollStartX - deltaX
        container.scrollTop = scrollStartY - deltaY
    })
    
    // 鼠标抬起事件
    const handleMouseUp = (e) => {
        if (isDragging) {
            e.preventDefault()
            e.stopPropagation()
            isDragging = false
            
            // 恢复鼠标样式
            if (viewer.canDrag) {
                container.style.cursor = 'grab'
            } else {
                container.style.cursor = 'default'
            }
        }
    }
    
    document.addEventListener('mouseup', handleMouseUp)
    
    // 鼠标离开容器事件
    container.addEventListener('mouseleave', () => {
        if (isDragging) {
            isDragging = false
            
            // 恢复鼠标样式
            if (viewer.canDrag) {
                container.style.cursor = 'grab'
            } else {
                container.style.cursor = 'default'
            }
        }
    })
    
    // 触摸屏支持
    let touchScrollStartX, touchScrollStartY
    
    container.addEventListener('touchstart', (e) => {
        if (!viewer.canDrag || e.touches.length !== 1) return
        
        e.preventDefault()
        e.stopPropagation()
        
        const touch = e.touches[0]
        viewer.touchData.startX = touch.clientX
        viewer.touchData.startY = touch.clientY
        viewer.touchData.lastX = touch.clientX
        viewer.touchData.lastY = touch.clientY
        viewer.touchData.startTime = Date.now()
        viewer.touchData.isTouchMoving = false
        viewer.touchData.hasMoved = false
        
        touchScrollStartX = container.scrollLeft
        touchScrollStartY = container.scrollTop
    }, { passive: false })
    
    container.addEventListener('touchmove', (e) => {
        if (!viewer.canDrag || e.touches.length !== 1) return
        
        e.preventDefault()
        e.stopPropagation()
        
        const touch = e.touches[0]
        const currentX = touch.clientX
        const currentY = touch.clientY
        
        // 计算移动距离
        const deltaX = currentX - viewer.touchData.startX
        const deltaY = currentY - viewer.touchData.startY
        
        // 检查是否超过了阈值
        if (!viewer.touchData.isTouchMoving) {
            const moveDistance = Math.sqrt(deltaX * deltaX + deltaY * deltaY)
            if (moveDistance > TOUCH_MOVE_THRESHOLD) {
                viewer.touchData.isTouchMoving = true
                viewer.touchData.hasMoved = true
            }
        }
        
        if (viewer.touchData.isTouchMoving) {
            // 拖拽逻辑
            const moveDeltaX = currentX - viewer.touchData.lastX
            const moveDeltaY = currentY - viewer.touchData.lastY
            
            // 反向移动容器滚动位置
            container.scrollLeft -= moveDeltaX
            container.scrollTop -= moveDeltaY
            
            // 更新最后位置
            viewer.touchData.lastX = currentX
            viewer.touchData.lastY = currentY
        }
    }, { passive: false })
    
    container.addEventListener('touchend', (e) => {
        if (!viewer.canDrag) return
        
        e.preventDefault()
        e.stopPropagation()
        
        const touch = e.changedTouches[0]
        const endX = touch.clientX
        const endY = touch.clientY
        
        // 计算移动距离
        const deltaX = endX - viewer.touchData.startX
        const deltaY = endY - viewer.touchData.startY
        const moveDistance = Math.sqrt(deltaX * deltaX + deltaY * deltaY)
        
        // 如果没有移动或移动距离很小，且时间很短，认为是点击
        const touchDuration = Date.now() - viewer.touchData.startTime
        
        if (!viewer.touchData.hasMoved && touchDuration < 300) {
            // 这是点击事件，可以触发翻页
            handleTouchClick(canvasId, endX, endY)
        }
        
        // 重置触摸数据
        resetTouchData(viewer)
    }, { passive: false })
    
    container.addEventListener('touchcancel', () => {
        resetTouchData(viewer)
    }, { passive: false })
    
    // 防止文本选择
    container.addEventListener('selectstart', (e) => {
        if (viewer.canDrag) {
            e.preventDefault()
        }
    })
    
    // 存储拖拽状态到viewer
    viewer.isDragging = isDragging
    viewer.dragStartX = dragStartX
    viewer.dragStartY = dragStartY
    viewer.scrollStartX = scrollStartX
    viewer.scrollStartY = scrollStartY
    
    // 防止容器内的按钮响应触摸事件
    const preventTouchOnButtons = (e) => {
        if (e.target.tagName === 'BUTTON' || e.target.closest('button')) {
            e.stopPropagation()
        }
    }
    
    const zoomControls = document.getElementById(`zoom-controls-${canvasId}`)
    const paginationControls = document.getElementById(`pagination-controls-${canvasId}`)
    
    if (zoomControls) {
        zoomControls.addEventListener('touchstart', preventTouchOnButtons)
        zoomControls.addEventListener('touchmove', preventTouchOnButtons)
        zoomControls.addEventListener('touchend', preventTouchOnButtons)
    }
    
    if (paginationControls) {
        paginationControls.addEventListener('touchstart', preventTouchOnButtons)
        paginationControls.addEventListener('touchmove', preventTouchOnButtons)
        paginationControls.addEventListener('touchend', preventTouchOnButtons)
    }
}

/**
 * 处理触摸点击事件
 */
function handleTouchClick(canvasId, x, y) {
    const viewer = pdfViewers.get(canvasId)
    if (!viewer || viewer.totalPages <= 1) return
    
    const container = viewer.container
    const rect = container.getBoundingClientRect()
    
    // 计算相对于容器中心的位置
    const containerWidth = container.clientWidth
    const clickX = x - rect.left
    
    // 左侧1/3区域：上一页
    if (clickX < containerWidth / 3) {
        if (viewer.currentPage > 1) {
            goToPage(canvasId, viewer.currentPage - 1)
        }
    }
    // 右侧1/3区域：下一页
    else if (clickX > containerWidth * 2 / 3) {
        if (viewer.currentPage < viewer.totalPages) {
            goToPage(canvasId, viewer.currentPage + 1)
        }
    }
    // 中间区域：显示/隐藏控件
    else {
        toggleControls(canvasId)
    }
}

/**
 * 切换控件显示/隐藏
 */
function toggleControls(canvasId) {
    const zoomControls = document.getElementById(`zoom-controls-${canvasId}`)
    const paginationControls = document.getElementById(`pagination-controls-${canvasId}`)
    
    if (zoomControls && paginationControls) {
        const isVisible = zoomControls.style.display !== 'none'
        
        zoomControls.style.display = isVisible ? 'none' : 'flex'
        paginationControls.style.display = isVisible ? 'none' : 'flex'
        
        // 5秒后自动隐藏
        setTimeout(() => {
            zoomControls.style.display = 'none'
            paginationControls.style.display = 'none'
        }, 5000)
    }
}

/**
 * 重置触摸数据
 */
function resetTouchData(viewer) {
    viewer.touchData = {
        startX: 0,
        startY: 0,
        lastX: 0,
        lastY: 0,
        startTime: 0,
        isTouchMoving: false,
        hasMoved: false
    }
}

/**
 * 更新拖拽状态（当缩放或页面变化时调用）
 */
function updateDragState(canvasId) {
    const viewer = pdfViewers.get(canvasId)
    if (!viewer || !viewer.container || !viewer.canvas) return
    
    const container = viewer.container
    const canvas = viewer.canvas
    
    // 检查是否需要拖拽（canvas尺寸是否大于容器可视区域）
    const isCanvasLargerThanContainer = 
        canvas.width > container.clientWidth || 
        canvas.height > container.clientHeight
    
    viewer.canDrag = isCanvasLargerThanContainer
    
    // 更新鼠标样式
    if (isCanvasLargerThanContainer) {
        container.style.cursor = viewer.isDragging ? 'grabbing' : 'grab'
        container.style.cursor = viewer.isDragging ? '-webkit-grabbing' : '-webkit-grab'
        container.style.touchAction = 'none' // 完全控制触摸行为
    } else {
        container.style.cursor = 'default'
        container.style.touchAction = 'pan-y' // 恢复垂直滚动
    }
}

// ======================== 加载状态 ========================

/**
 * 显示加载状态
 */
function showLoadingState(container, canvasId) {
    const loadingHTML = `
        <div id="pdf-loading-${canvasId}" style="
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.9);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        ">
            <div class="spinner" style="
                width: 40px;
                height: 40px;
                border: 4px solid #f3f3f3;
                border-top: 4px solid #409eff;
                border-radius: 50%;
                animation: spin 1s linear infinite;
                margin-bottom: 10px;
            "></div>
            <div style="color: #606266; font-size: 14px;">加载中...</div>
            <style>
                @keyframes spin {
                    0% { transform: rotate(0deg); }
                    100% { transform: rotate(360deg); }
                }
            </style>
        </div>
    `
    
    container.insertAdjacentHTML('beforeend', loadingHTML)
}

/**
 * 隐藏加载状态
 */
function hideLoadingState(canvasId) {
    const loadingOverlay = document.getElementById(`pdf-loading-${canvasId}`)
    if (loadingOverlay) {
        loadingOverlay.style.display = 'none'
    }
}

/**
 * 显示错误状态
 */
function showErrorState(container, canvasId, message) {
    const errorHTML = `
        <div id="pdf-error-${canvasId}" style="
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.95);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            color: #f56c6c;
        ">
            <div style="font-size: 48px; margin-bottom: 20px;">❌</div>
            <div style="font-size: 16px; margin-bottom: 10px;">${message}</div>
            <div style="font-size: 12px; color: #909399;">请检查PDF文件或网络连接</div>
        </div>
    `
    
    container.insertAdjacentHTML('beforeend', errorHTML)
}

// ======================== 缩放控件 ========================

/**
 * 添加缩放控件（带旋转按钮）
 */
function addZoomControls(container, canvasId) {
    const controlsHTML = `
        <div class="pdf-zoom-controls" id="zoom-controls-${canvasId}">
            <style>
                #zoom-controls-${canvasId} {
                    position: fixed;
                    bottom: 20px;
                    right: 20px;
                    display: flex;
                    align-items: center;
                    gap: 10px;
                    background: white;
                    padding: 8px 12px;
                    border-radius: 25px;
                    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
                    z-index: 10000;
                    transition: opacity 0.3s ease;
                }
                #zoom-controls-${canvasId} button {
                    width: 36px;
                    height: 36px;
                    border: none;
                    border-radius: 50%;
                    font-size: 18px;
                    cursor: pointer;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    transition: all 0.2s;
                    touch-action: manipulation;
                }
                #zoom-controls-${canvasId} button:hover {
                    transform: scale(1.1);
                }
                #zoom-controls-${canvasId} button:active {
                    transform: scale(0.95);
                }
                #zoom-out-${canvasId} {
                    background: #f56c6c;
                    color: white;
                }
                #zoom-in-${canvasId} {
                    background: #67c23a;
                    color: white;
                }
                #zoom-fit-${canvasId} {
                    background: #409eff;
                    color: white;
                }
                #zoom-actual-${canvasId} {
                    background: #909399;
                    color: white;
                }
                #rotate-left-${canvasId} {
                    background: #e6a23c;
                    color: white;
                }
                #rotate-right-${canvasId} {
                    background: #e6a23c;
                    color: white;
                }
                #zoom-display-${canvasId} {
                    font-size: 14px;
                    font-weight: bold;
                    min-width: 50px;
                    text-align: center;
                    color: #333;
                }
            </style>
            
            <button id="rotate-left-${canvasId}" title="向左旋转90°">↺</button>
            <button id="zoom-out-${canvasId}" title="缩小">−</button>
            <span id="zoom-display-${canvasId}">100%</span>
            <button id="zoom-in-${canvasId}" title="放大">+</button>
            <button id="zoom-fit-${canvasId}" title="适应窗口">⌂</button>
            <button id="zoom-actual-${canvasId}" title="实际大小">1:1</button>
            <button id="rotate-right-${canvasId}" title="向右旋转90°">↻</button>
        </div>
    `
    
    container.insertAdjacentHTML('beforeend', controlsHTML)
}

/**
 * 初始化缩放控件
 */
function initZoomControls(canvasId) {
    const viewer = pdfViewers.get(canvasId)
    if (!viewer) {
        console.warn(`PDF查看器 ${canvasId} 未找到`)
        return
    }
    
    // 等待DOM渲染
    setTimeout(() => {
        const zoomInBtn = document.getElementById(`zoom-in-${canvasId}`)
        const zoomOutBtn = document.getElementById(`zoom-out-${canvasId}`)
        const zoomFitBtn = document.getElementById(`zoom-fit-${canvasId}`)
        const zoomActualBtn = document.getElementById(`zoom-actual-${canvasId}`)
        const rotateLeftBtn = document.getElementById(`rotate-left-${canvasId}`)
        const rotateRightBtn = document.getElementById(`rotate-right-${canvasId}`)
        
        // 检查元素是否存在
        if (!zoomInBtn || !zoomOutBtn || !zoomFitBtn || !zoomActualBtn || !rotateLeftBtn || !rotateRightBtn) {
            console.error('缩放控件元素未找到')
            return
        }
        
        // 放大功能
        zoomInBtn.onclick = async (e) => {
            e.preventDefault()
            e.stopPropagation()
            const newScale = Math.min(viewer.currentScale + 0.25, 5.0)
            await zoomTo(canvasId, newScale)
        }
        
        // 缩小功能
        zoomOutBtn.onclick = async (e) => {
            e.preventDefault()
            e.stopPropagation()
            const newScale = Math.max(viewer.currentScale - 0.25, 0.2)
            await zoomTo(canvasId, newScale)
        }
        
        // 适应窗口
        zoomFitBtn.onclick = async (e) => {
            e.preventDefault()
            e.stopPropagation()
            await zoomToFit(canvasId)
        }
        
        // 实际大小
        zoomActualBtn.onclick = async (e) => {
            e.preventDefault()
            e.stopPropagation()
            await zoomTo(canvasId, 1.0)
        }
        
        // 向左旋转
        rotateLeftBtn.onclick = async (e) => {
            e.preventDefault()
            e.stopPropagation()
            await rotateLeft(canvasId)
        }
        
        // 向右旋转
        rotateRightBtn.onclick = async (e) => {
            e.preventDefault()
            e.stopPropagation()
            await rotateRight(canvasId)
        }
        
        // 鼠标滚轮缩放
        const container = viewer.container
        if (container) {
            container.addEventListener('wheel', async (e) => {
                if (e.ctrlKey || e.metaKey) {
                    e.preventDefault()
                    const delta = e.deltaY > 0 ? -0.1 : 0.1
                    const newScale = Math.max(0.2, Math.min(5.0, viewer.currentScale + delta))
                    await zoomTo(canvasId, newScale)
                }
            }, { passive: false })
        }
        
        // 双击缩放
        const canvas = viewer.canvas
        if (canvas) {
            canvas.addEventListener('dblclick', async (e) => {
                const rect = canvas.getBoundingClientRect()
                const x = e.clientX - rect.left
                const y = e.clientY - rect.top
                
                if (viewer.viewport) {
                    const zoomCenter = {
                        x: x / viewer.currentScale,
                        y: y / viewer.currentScale
                    }
                    
                    const newScale = viewer.currentScale < 2.0 ? 2.0 : 1.0
                    await zoomTo(canvasId, newScale, zoomCenter)
                }
            })
        }
        
        // 初始化显示
        updateZoomDisplay(canvasId, viewer.currentScale)
        
        console.log(`缩放控件初始化完成: ${canvasId}`)
    }, 50)
}

// ======================== 页面渲染 ========================

/**
 * 渲染页面（支持旋转）
 */
async function renderPage(canvasId, pageNum = null) {
    const viewer = pdfViewers.get(canvasId)
    if (!viewer) {
        console.warn(`PDF查看器 ${canvasId} 未找到`)
        return
    }
    
    // 确定页码
    const pageNumber = pageNum || viewer.currentPage || 1
    
    // 检查边界
    if (pageNumber < 1 || pageNumber > viewer.totalPages) {
        console.error(`页码 ${pageNumber} 超出范围 (1-${viewer.totalPages})`)
        return
    }
    
    // 获取或加载页面
    let page = viewer.pages.get(pageNumber)
    if (!page) {
        try {
            page = await viewer.pdf.getPage(pageNumber)
            viewer.pages.set(pageNumber, page)
        } catch (error) {
            console.error(`加载第 ${pageNumber} 页失败:`, error)
            return
        }
    }
    
    const canvas = viewer.canvas
    if (!canvas) {
        console.error(`Canvas ${canvasId} 未找到`)
        return
    }
    
    const context = canvas.getContext('2d')
    
    // 获取当前旋转角度
    const rotation = viewer.currentRotation || 0
    
    // 创建viewport时应用旋转
    const viewport = page.getViewport({ 
        scale: viewer.currentScale,
        rotation: rotation
    })
    
    // 设置Canvas尺寸
    canvas.height = viewport.height
    canvas.width = viewport.width
    canvas.style.height = 'auto'
    
    // 更新状态
    viewer.currentPage = pageNumber
    viewer.viewport = viewport
    viewer.currentPageObj = page
    
    // 渲染页面
    const renderContext = {
        canvasContext: context,
        viewport: viewport
    }
    
    // 清除之前的内容
    context.clearRect(0, 0, canvas.width, canvas.height)
    
    // 渲染新内容
    try {
        await page.render(renderContext).promise
        
        // 更新显示
        updateZoomDisplay(canvasId, viewer.currentScale)
        updateRotationDisplay(canvasId, rotation)
        
        if (viewer.totalPages > 1) {
            updatePageDisplay(canvasId, pageNumber, viewer.totalPages)
        }
        
        // 更新拖拽状态
        setTimeout(() => {
            updateDragState(canvasId)
        }, 50)
        
        // 预加载相邻页面
        preloadAdjacentPages(canvasId, pageNumber)
        
        console.log(`第 ${pageNumber} 页渲染完成 (旋转: ${rotation}°)`)
    } catch (error) {
        console.error(`渲染第 ${pageNumber} 页失败:`, error)
    }
}

/**
 * 初始化多页PDF
 */
async function initMultiPagePDF(canvasId, pdf) {
    const viewer = pdfViewers.get(canvasId)
    if (!viewer) return
    
    viewer.totalPages = pdf.numPages
    
    // 渲染第一页
    await renderPage(canvasId, 1)
    
    // 预加载下一页（如果有多页）
    if (pdf.numPages > 1) {
        setTimeout(() => preloadPage(canvasId, 2), 300)
    }
}

/**
 * 预加载页面
 */
async function preloadPage(canvasId, pageNum) {
    const viewer = pdfViewers.get(canvasId)
    if (!viewer || viewer.pages.has(pageNum) || pageNum < 1 || pageNum > viewer.totalPages) {
        return
    }
    
    try {
        const page = await viewer.pdf.getPage(pageNum)
        viewer.pages.set(pageNum, page)
        console.log(`预加载第 ${pageNum} 页完成`)
    } catch (error) {
        console.error(`预加载第 ${pageNum} 页失败:`, error)
    }
}

/**
 * 预加载相邻页面
 */
function preloadAdjacentPages(canvasId, currentPage) {
    const viewer = pdfViewers.get(canvasId)
    if (!viewer) return
    
    // 预加载下一页
    if (currentPage < viewer.totalPages) {
        preloadPage(canvasId, currentPage + 1)
    }
    
    // 预加载上一页
    if (currentPage > 1) {
        preloadPage(canvasId, currentPage - 1)
    }
}

// ======================== 分页功能 ========================

/**
 * 添加分页控件
 */
function addPaginationControls(container, canvasId, totalPages) {
    if (totalPages <= 1) return
    
    const controlsHTML = `
        <div class="pdf-pagination-controls" id="pagination-controls-${canvasId}">
            <style>
                #pagination-controls-${canvasId} {
                    position: absolute;
                    top: 10px;
                    left: 50%;
                    transform: translateX(-50%);
                    display: flex;
                    align-items: center;
                    gap: 10px;
                    background: rgba(255, 255, 255, 0.9);
                    padding: 8px 16px;
                    border-radius: 25px;
                    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                    z-index: 100;
                    transition: opacity 0.3s ease;
                }
                #pagination-controls-${canvasId} button {
                    width: 36px;
                    height: 36px;
                    border: none;
                    border-radius: 50%;
                    font-size: 16px;
                    cursor: pointer;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    transition: all 0.2s;
                    touch-action: manipulation;
                }
                #pagination-controls-${canvasId} button:hover {
                    transform: scale(1.1);
                }
                #pagination-controls-${canvasId} button:disabled {
                    opacity: 0.5;
                    cursor: not-allowed;
                    transform: none;
                }
                #page-prev-${canvasId} {
                    background: #f56c6c;
                    color: white;
                }
                #page-next-${canvasId} {
                    background: #67c23a;
                    color: white;
                }
                #page-display-${canvasId} {
                    font-size: 14px;
                    font-weight: bold;
                    min-width: 80px;
                    text-align: center;
                    color: #333;
                }
            </style>
            
            <button id="page-prev-${canvasId}" title="上一页">‹</button>
            <span id="page-display-${canvasId}">1 / ${totalPages}</span>
            <button id="page-next-${canvasId}" title="下一页">›</button>
        </div>
    `
    
    container.insertAdjacentHTML('beforeend', controlsHTML)
    
    // 初始化分页控件
    initPaginationControls(canvasId)
}

/**
 * 初始化分页控件
 */
function initPaginationControls(canvasId) {
    const viewer = pdfViewers.get(canvasId)
    if (!viewer) return
    
    setTimeout(() => {
        const prevBtn = document.getElementById(`page-prev-${canvasId}`)
        const nextBtn = document.getElementById(`page-next-${canvasId}`)
        
        if (!prevBtn || !nextBtn) return
        
        prevBtn.onclick = async (e) => {
            e.preventDefault()
            e.stopPropagation()
            if (viewer.currentPage > 1) {
                await goToPage(canvasId, viewer.currentPage - 1)
            }
        }
        
        nextBtn.onclick = async (e) => {
            e.preventDefault()
            e.stopPropagation()
            if (viewer.currentPage < viewer.totalPages) {
                await goToPage(canvasId, viewer.currentPage + 1)
            }
        }
        
        // 更新按钮状态
        updatePaginationButtons(canvasId)
    }, 100)
}

/**
 * 跳转到指定页
 */
async function goToPage(canvasId, pageNum) {
    const viewer = pdfViewers.get(canvasId)
    if (!viewer || pageNum < 1 || pageNum > viewer.totalPages) {
        return
    }
    
    await renderPage(canvasId, pageNum)
    updatePaginationButtons(canvasId)
}

/**
 * 更新分页按钮状态
 */
function updatePaginationButtons(canvasId) {
    const viewer = pdfViewers.get(canvasId)
    if (!viewer) return
    
    const prevBtn = document.getElementById(`page-prev-${canvasId}`)
    const nextBtn = document.getElementById(`page-next-${canvasId}`)
    
    if (prevBtn) {
        prevBtn.disabled = viewer.currentPage <= 1
    }
    if (nextBtn) {
        nextBtn.disabled = viewer.currentPage >= viewer.totalPages
    }
}

// ======================== 缩放功能 ========================

/**
 * 缩放到指定比例
 */
async function zoomTo(canvasId, scale, center = null) {
    const viewer = pdfViewers.get(canvasId)
    if (!viewer) {
        console.error(`PDF查看器 ${canvasId} 未找到`)
        return
    }
    
    // 限制缩放范围
    scale = Math.max(0.2, Math.min(5.0, scale))
    viewer.currentScale = scale
    
    // 如果有中心点，计算滚动位置
    if (center && viewer.viewport) {
        const container = viewer.container
        if (container) {
            const oldScale = viewer.currentScale
            const scaleRatio = scale / oldScale
            
            const scrollLeft = (container.scrollLeft + center.x * oldScale) * scaleRatio - center.x * scale
            const scrollTop = (container.scrollTop + center.y * oldScale) * scaleRatio - center.y * scale
            
            // 渲染页面
            await renderPage(canvasId)
            
            // 设置滚动位置
            setTimeout(() => {
                container.scrollLeft = Math.max(0, scrollLeft)
                container.scrollTop = Math.max(0, scrollTop)
                
                // 更新拖拽状态
                updateDragState(canvasId)
            }, 10)
            
            return
        }
    }
    
    // 普通缩放
    await renderPage(canvasId)
    
    // 更新拖拽状态
    setTimeout(() => {
        updateDragState(canvasId)
    }, 50)
}

/**
 * 适应窗口缩放
 */
async function zoomToFit(canvasId) {
    const viewer = pdfViewers.get(canvasId)
    if (!viewer) {
        console.error(`PDF查看器 ${canvasId} 未找到`)
        return
    }
    
    const container = viewer.container
    const canvas = viewer.canvas
    
    if (!container || !canvas) {
        console.error(`容器或Canvas未找到: ${canvasId}`)
        return
    }
    
    // 获取容器尺寸（减去边距）
    const containerWidth = container.clientWidth - 40
    const containerHeight = container.clientHeight - 40
    
    if (containerWidth <= 0 || containerHeight <= 0) {
        console.warn('容器尺寸无效')
        return
    }
    
    // 获取页面原始尺寸
    const viewport = viewer.currentPageObj.getViewport({ scale: 1.0 })
    const pageWidth = viewport.width
    const pageHeight = viewport.height
    
    // 计算适应比例
    const scaleX = containerWidth / pageWidth
    const scaleY = containerHeight / pageHeight
    const scale = Math.min(scaleX, scaleY) * 0.95  // 95%填充，留出边距
    
    await zoomTo(canvasId, scale)
}

// ======================== 旋转功能 ========================

/**
 * 旋转PDF页面
 * @param {string} canvasId - Canvas元素ID
 * @param {number} rotationChange - 旋转角度变化（90或-90）
 */
export async function rotatePDF(canvasId, rotationChange) {
    const viewer = pdfViewers.get(canvasId)
    if (!viewer) {
        console.error(`PDF查看器 ${canvasId} 未找到`)
        return
    }
    
    try {
        // 更新旋转角度
        let newRotation = (viewer.currentRotation + rotationChange) % 360
        if (newRotation < 0) newRotation += 360
        viewer.currentRotation = newRotation
        
        // 重新渲染当前页面
        await renderPage(canvasId, viewer.currentPage)
        
        // 更新拖拽状态
        setTimeout(() => {
            updateDragState(canvasId)
        }, 50)
        
    } catch (error) {
        console.error('旋转PDF失败:', error)
    }
}

/**
 * 更新旋转角度显示
 */
function updateRotationDisplay(canvasId, rotation) {
    // 可选：在界面上显示当前旋转角度
    const rotationDisplay = document.getElementById(`rotation-display-${canvasId}`)
    if (rotationDisplay) {
        rotationDisplay.textContent = `${rotation}°`
    }
}

/**
 * 向左旋转90度
 */
export function rotateLeft(canvasId) {
    return rotatePDF(canvasId, -90)
}

/**
 * 向右旋转90度
 */
export function rotateRight(canvasId) {
    return rotatePDF(canvasId, 90)
}

/**
 * 重置旋转角度
 */
export function resetRotation(canvasId) {
    const viewer = pdfViewers.get(canvasId)
    if (!viewer) return
    
    viewer.currentRotation = 0
    return renderPage(canvasId, viewer.currentPage)
}

// ======================== 更新显示 ========================

/**
 * 更新缩放显示
 */
function updateZoomDisplay(canvasId, scale) {
    const display = document.getElementById(`zoom-display-${canvasId}`)
    if (display) {
        display.textContent = `${Math.round(scale * 100)}%`
    }
}

/**
 * 更新页码显示
 */
function updatePageDisplay(canvasId, currentPage, totalPages) {
    const display = document.getElementById(`page-display-${canvasId}`)
    if (display) {
        display.textContent = `${currentPage} / ${totalPages}`
    }
}

// ======================== 外部接口函数 ========================

/**
 * 下一页
 */
export function nextPage(canvasId) {
    const viewer = pdfViewers.get(canvasId)
    if (viewer && viewer.currentPage < viewer.totalPages) {
        return goToPage(canvasId, viewer.currentPage + 1)
    }
    return Promise.resolve()
}

/**
 * 上一页
 */
export function prevPage(canvasId) {
    const viewer = pdfViewers.get(canvasId)
    if (viewer && viewer.currentPage > 1) {
        return goToPage(canvasId, viewer.currentPage - 1)
    }
    return Promise.resolve()
}

/**
 * 跳转到指定页
 */
export function goToPageNumber(canvasId, pageNum) {
    return goToPage(canvasId, pageNum)
}

/**
 * 获取PDF信息
 */
export function getPDFInfo(canvasId) {
    const viewer = pdfViewers.get(canvasId)
    if (viewer) {
        return {
            currentPage: viewer.currentPage,
            totalPages: viewer.totalPages,
            scale: viewer.currentScale,
            rotation: viewer.currentRotation,
            canDrag: viewer.canDrag,
            isDragging: viewer.isDragging
        }
    }
    return null
}

/**
 * 获取当前缩放比例
 */
export function getCurrentZoom(canvasId) {
    const viewer = pdfViewers.get(canvasId)
    return viewer ? viewer.currentScale : null
}

/**
 * 获取当前旋转角度
 */
export function getCurrentRotation(canvasId) {
    const viewer = pdfViewers.get(canvasId)
    return viewer ? viewer.currentRotation : null
}

/**
 * 设置缩放比例
 */
export function setZoom(canvasId, scale) {
    return zoomTo(canvasId, scale)
}

/**
 * 启用/禁用拖拽
 */
export function setDragEnabled(canvasId, enabled) {
    const viewer = pdfViewers.get(canvasId)
    if (viewer) {
        viewer.canDrag = enabled
        updateDragState(canvasId)
    }
}

/**
 * 重置所有PDF查看器
 */
export function resetAllPDFViewers() {
    for (const [canvasId, viewer] of pdfViewers.entries()) {
        cleanupPdfViewer(canvasId)
    }
    pdfViewers.clear()
}

/**
 * 初始化键盘快捷键
 */
export function initPDFKeyboardShortcuts() {
    document.addEventListener('keydown', async (e) => {
        const activeCanvas = getActivePDFCanvas()
        if (!activeCanvas) return
        
        const canvasId = activeCanvas.id
        const viewer = pdfViewers.get(canvasId)
        if (!viewer) return
        
        // Ctrl/Cmd + R：向右旋转
        if ((e.ctrlKey || e.metaKey) && e.key === 'r') {
            e.preventDefault()
            await rotateRight(canvasId)
        }
        
        // Ctrl/Cmd + Shift + R：向左旋转
        if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'R') {
            e.preventDefault()
            await rotateLeft(canvasId)
        }
        
        if (e.ctrlKey || e.metaKey) {
            switch(e.key) {
                case '+':
                case '=':
                    e.preventDefault()
                    await zoomTo(canvasId, Math.min(viewer.currentScale + 0.25, 5.0))
                    break
                    
                case '-':
                    e.preventDefault()
                    await zoomTo(canvasId, Math.max(viewer.currentScale - 0.25, 0.2))
                    break
                    
                case '0':
                    e.preventDefault()
                    await zoomToFit(canvasId)
                    break
                    
                case '1':
                    if (e.shiftKey) {
                        e.preventDefault()
                        await zoomTo(canvasId, 1.0)
                    }
                    break
            }
        } else {
            switch(e.key) {
                case 'ArrowLeft':
                    if (viewer.currentPage > 1) {
                        e.preventDefault()
                        await prevPage(canvasId)
                    }
                    break
                    
                case 'ArrowRight':
                    if (viewer.currentPage < viewer.totalPages) {
                        e.preventDefault()
                        await nextPage(canvasId)
                    }
                    break
                    
                case 'Home':
                    e.preventDefault()
                    await goToPage(canvasId, 1)
                    break
                    
                case 'End':
                    e.preventDefault()
                    await goToPage(canvasId, viewer.totalPages)
                    break
            }
        }
    })
}

/**
 * 获取当前激活的PDF Canvas
 */
function getActivePDFCanvas() {
    const canvases = document.querySelectorAll('canvas[id^="see"]')
    for (const canvas of canvases) {
        if (canvas.offsetParent !== null) {
            return canvas
        }
    }
    return null
}

// ======================== 默认导出 ========================

export default {
    seepdf,
    nextPage,
    prevPage,
    goToPageNumber,
    getPDFInfo,
    getCurrentZoom,
    getCurrentRotation,
    setZoom,
    setDragEnabled,
    resetAllPDFViewers,
    initPDFKeyboardShortcuts,
    // 旋转功能
    rotatePDF,
    rotateLeft,
    rotateRight,
    resetRotation
}

// 全局暴露（可选）
if (typeof window !== 'undefined') {
    window.PDFViewer = {
        seepdf,
        nextPage,
        prevPage,
        goToPageNumber,
        getPDFInfo,
        getCurrentZoom,
        getCurrentRotation,
        setZoom,
        setDragEnabled,
        resetAllPDFViewers,
        initPDFKeyboardShortcuts,
        rotatePDF,
        rotateLeft,
        rotateRight,
        resetRotation
    }
}