<template>
    <div :class="['report_page', { 'full_screen': isShowFullScreen }]" style="position: absolute;top: -9999999px;z-index: -10;">
        <!-- 点击封面进入全屏 -->
        <div class="joint_print_area">
            <!-- 点击封面进入全屏预览模式 -->
            <!-- <BookCover :bookBg="`${bookBg}_bg`" :title="coverTitle" :subtitle="subtitle" :showButton="true" :requestLoading="requestLoading" :openLoading="openLoading" @openFullScreen="openFullScreen" :style="{width:`${bookWidth}px`,height:`${bookHeight}px`,margin:'0 auto'}" v-if="!isShowFullScreen"></BookCover> -->
            <!-- 全屏预览 -->
            <div id="canvas" v-if="isShowFullScreen">
                <!-- 右上角放大缩小按钮 -->
                <div class="close-zoom-icon" @click="CloseFullScreen"><img class="close" src="@/assets/icon/close.webp" /><span>关闭全屏</span></div>
                <div class="magazine-viewport">
                    <div class="container">
                        <!-- 翻书容器 -->
                        <div class="magazine" id="flipbook" ref="bookContainer">
                            <!-- 封面 -->
                            <BookCover :showButton="false" :bookBg="`${bookBg}_bg`" :title="coverTitle" :subtitle="subtitle"></BookCover>
                            <div class="area_page" v-for="(page, index) in bookPages" :key="index">
                                <!-- 插槽：自定义每页内容 -->
                                <slot :page="index + 1" :content="page"></slot>
                                <!-- <div class="area_page_number">第 {{ currentPage }} 页</div> -->
                            </div>
                            <!-- 封面 -->
                            <BookCover :showButton="false" :isCover="true" :bookBg="`${bookBg}_cover_bg`"></BookCover>
                            <template v-if="bookPages.length % 2 !== 0">
                                <BookCover :showButton="false" :isCover="true" :bookBg="`${bookBg}_cover_bg`"></BookCover>
                            </template>
                        </div>
                    </div>
                    <!-- Next button -->
                    <div ignore="1" class="next-button"><i class="el-icon-arrow-right"></i></div>
                    <!-- Previous button -->
                    <div ignore="1" class="previous-button"><i class="el-icon-arrow-left"></i></div>
                </div>
                <!-- 翻页控制按钮 -->
                <div class="thumbnails">
                    <div class="book_controls">
                        <div class="zoom">
                            <img class="zoom_icon zoom_in_icon" src="@/assets/icon/enlarge_icon.png" />
                            <img class="zoom_icon zoom_out_icon" src="@/assets/icon/shrink_icon.png" />
                        </div>
                        <div class="page_size">
                            <span class="butn_prev" @click="prevPage"><img src="@/assets/report/turn_prev.webp" /></span>
                            <span class="page_info">{{ currentPage }}{{ bookPages.length }}</span>
                            <span class="butn_next" @click="nextPage"><img src="@/assets/report/turn_next.webp" /></span>
                        </div>
                        <el-button class="download" type="primary" :loading="loading" @click="DownloadPdf">下载报告册</el-button>
                    </div>
                </div>
                <!-- <div class="page_dialog">
                    <el-dialog title="下载PDF" class="page_dialog" :visible.sync="showReportLoading" width="500px" top="15%" append-to-body>
                        <div class="report_loading">
                            <div class="report_loading_icon">
                            <img src="@/assets/report/report_loading.png">
                            </div>
                            <div class="report_loading_title">正在努力生成PDF中，请稍等...</div> 
                            <div class="report_loading_progress">
                            <el-progress :text-inside="true" color="#2E64FA" text-color="#ffffff" :stroke-width="16" :percentage="targetProgress"></el-progress>
                            </div>
                        </div>
                    </el-dialog>
                </div> -->
            </div>
            <!-- 下载模版 -->
            <!-- style="position: absolute;top: -9999999px;z-index: -10;" -->
            <div class="magazine-viewport web_mode">
                <!-- 封面 -->
                <BookCover class="web_cover web_area_page" :showButton="false" :bookBg="`${bookBg}_bg`" :title="coverTitle" :subtitle="subtitle"></BookCover>
                <slot type="web_mode"></slot>
                <!-- 封面 -->
                <BookCover class="web_cover web_area_page" :showButton="false" :isCover="true" :bookBg="`${bookBg}_cover_bg`"></BookCover>
            </div>
        </div>
    </div>
</template>

<script>
// import $ from 'jquery';  // 先导入 jQuery
// import 'turn.js'; 
import turn from '@/utils/turn.js';
import zoom from './js/zoom.min.js';
import BookCover from './bookCover.vue';
import { disableControls, addPage,largeMagazineWidth,resizeViewport,setArrows,loadLargePage,loadSmallPage } from './js/magazine.js';
import { jsPDF } from "jspdf";
import html2canvas from "html2canvas";
import domtoimage from 'dom-to-image';
import { mapGetters } from "vuex";
export default {
    props: {
        // 书页数据（数组长度建议为偶数）
        bookPages: {
            type: Array,
            required: true,
            default: () => []
        },
        bookBg:{
            type:String,
            default: 'grade_leader'
        },
        coverTitle:{//封面标题
            type:String,
            default: '联校总分分析报告册'
        },
        subtitle:{//封面副标题
            type:String,
            default: '联校总分分析报告册'
        },
        requestLoading:{
            type:Boolean,
            default: false
        },//接口请求的loading
        openLoading:{
            type:Boolean,
            default: false
        },//开发全屏预览
        
    },
    components:{BookCover},
    data() {
        return {
            isShowFullScreen: false,
            bookHeight:780,//封面高度
            bookWidth:600,//封面宽度
            currentPage: '', // 当前页码
            totalPages: 0, // 总页数（由 turn.js 计算）
            showReportLoading:false,
            targetProgress:0,
            loading:false
        };
    },
    computed: {
        ...mapGetters(["userInfo"]),
        reportTitle() {
            return this?.$store?.state?.report?.examSelectItem?.examName ?? '';
        }
    },
    mounted() {
        //设置书本宽度和高度
        this.setBookSize();
        // 监听窗口大小变化，实时更新
        window.addEventListener('resize', this.setBookSize);
    },
    beforeDestroy() {
        // 销毁翻书实例，避免内存泄漏
        if (this.$refs.bookContainer) {
            $(this.$refs.bookContainer).turn('destroy');
        }
        window.removeEventListener('resize', this.setBookSize);
    },
    methods: {
        //设置书本宽度和高度
        setBookSize(){
            const bookHeight = $(window).height() - 120;//书本高度
            this.bookHeight = bookHeight;
            this.bookWidth = Math.round(bookHeight * 0.706);// 书本宽度 0.706 宽高的比例
        },
        //点击查看全屏
        openFullScreen(){
            this.$emit('OpenBookImages');
        },
        //打开全屏预览
        showFullScreen() {
            $('#canvas').hide();
            this.isShowFullScreen = true;//是否显示全屏
            this.initBook(); // 初始化翻书效果
        },
        // 初始化翻书效果
        initBook() {
            const b_height = $(window).height() - 120;//书本高度
            const b_width = Math.round(b_height * 0.706) * 2;// 书本宽度 0.706 宽高的比例
            this.$nextTick(() => {
                $('#canvas').fadeIn(1000);
                const $book = $(this.$refs.bookContainer);
                if ($book.width() == 0 || $book.height() == 0) {
                    setTimeout(loadApp, 10);
                    return;
                }
                // 初始化 turn.js
                const _that = this;
                const totalPages = this.bookPages.length;//总页数
                $book.turn({
                    // 页面尺寸（A4 高度示例）
                    // height: 1285, // 单页高度（对应 A4 72dpi 高度）
                    // width: 1816, // 单页宽度（对应 A4 72dpi 宽度）908
                    width: b_width, // 书本宽度
                    height: b_height, // 书本高度
                    duration: 1000,   //翻页速度，值越小越快
                    autoCenter: true, // 自动居中
                    acceleration: false,//设置硬件加速模式，用于触摸设备此值必须是真的
                    gradients: true,//置翻页时是否显示翻页跟阴影
                    display: 'double', // 双页显示（适合PC端）
                    elevation: 50, // 翻页阴影高度（增强立体感）
                    pages: totalPages,
                    when: {
                        // 翻页前触发
                        turning: function (event, page, view) {
                            const book = $(this);
                            const pages = book.turn('pages') - 2;
                            if(page > 1 && page < pages){
                                console.log(page , pages)
                                const prev = view[0] - 1;
                                const next = view[1] < pages ? view[1] - 1 : '';
                                _that.currentPage = next?`${prev}-${next}/`:`${prev}/`;
                            }else{
                                _that.currentPage = '';
                            }
                            // 显示和隐藏按钮
                            disableControls(page);
                        },
                        // 翻页后触发
                        turned: function (event, page, view) {
                            // 显示和隐藏按钮
                            disableControls(page);
                            $(this).turn('center');
                            if (page == 1) {
                                // 表示调用翻页 API 并指定翻页效果为 “Peel（ peeling，即 “剥开” 效果）”，且翻页的起始位置为右下角（br 是 bottom right 的缩写）
                                $(this).turn('peel', 'br');
                            }
                        },
                        // missing: function (event, pages) {
                        // 	// Add pages that aren't in the magazine
                        // 	for (var i = 0; i < pages.length; i++){
                        //         addPage(pages[i], $(this));
                        //     }
                        // }
                    }
                });
                // 初始化页码信息
                // this.totalPages = $book.turn('pages');
                // Zoom.js

                $('#canvas .magazine-viewport').zoom({

                    flipbook: $('.magazine'),

                    max: function () {

                        return largeMagazineWidth() / $('.magazine').width();

                    },

                    when: {

                        swipeLeft: function () {

                            $(this).zoom('flipbook').turn('next');

                        },

                        swipeRight: function () {

                            $(this).zoom('flipbook').turn('previous');

                        },



                        resize: function (event, scale, page, pageElement) {

                            // if (scale == 1)

                            //     loadSmallPage(page, pageElement);

                            // else

                            //     loadLargePage(page, pageElement);

                        },

                        zoomIn: function () {

                            $('.made').hide();

                            $('.magazine').removeClass('animated').addClass('zoom-in');

                            $('.zoom-icon').removeClass('zoom-icon-in').addClass('zoom-icon-out');

                            // if (!window.escTip && !$.isTouch) {

                            //     escTip = true;

                            //     $('<div />', { 'class': 'exit-message' }).

                            //         html('<div>Press ESC to exit</div>').

                            //         appendTo($('body')).

                            //         delay(2000).

                            //         animate({ opacity: 0 }, 500, function () {

                            //             $(this).remove();

                            //         });

                            // }

                        },

                        zoomOut: function () {

                            $('.exit-message').hide();

                            $('.thumbnails').fadeIn();

                            $('.made').fadeIn();

                            $('.zoom-icon').removeClass('zoom-icon-out').addClass('zoom-icon-in');

                            setTimeout(function () {

                                $('.magazine').addClass('animated').removeClass('zoom-in');

                                resizeViewport();

                            }, 0);

                        }

                    }

                });


                $(document).keydown(function (e) {

                    const previous = 37, next = 39, esc = 27;

                    switch (e.keyCode) {

                        case previous:

                            // left arrow

                            $('.magazine').turn('previous');

                            e.preventDefault();

                            break;

                        case next:

                            //right arrow

                            $('.magazine').turn('next');

                            e.preventDefault();

                            break;

                        case esc:

                            $('#canvas .magazine-viewport').zoom('zoomOut');

                            e.preventDefault();

                            break;

                    }

                });


                $(window).resize(function () {

                    resizeViewport();

                }).bind('orientationchange', function () {

                    resizeViewport();

                });
                // Events for the next button

                $('.next-button').click(function () {

                    $('.magazine').turn('next');

                    setTimeout(function () {

                        setArrows();

                    }, 300);

                });



                // Events for the next button	

                $('.previous-button').bind($.mouseEvents.over, function () {

                    $(this).addClass('previous-button-hover');

                }).bind($.mouseEvents.out, function () {

                    $(this).removeClass('previous-button-hover');

                }).bind($.mouseEvents.down, function () {

                    $(this).addClass('previous-button-down');

                }).bind($.mouseEvents.up, function () {

                    $(this).removeClass('previous-button-down');

                }).click(function () {

                    $('.magazine').turn('previous');

                    setTimeout(function () {

                        setArrows();

                    }, 300);

                });
                // Zoom icon
                $('.zoom_in_icon').on('click', function () {
                    $('#canvas .magazine-viewport').zoom('zoomIn');
                });
                $('.zoom_out_icon').on('click', function () {
                    $('#canvas .magazine-viewport').zoom('zoomOut');
                });
                resizeViewport();

                $('.magazine').addClass('animated');
            })
        },
        //退出全屏
        CloseFullScreen() {
            this.isShowFullScreen = false;
        },
        // 上一页
        prevPage() {
            $('.magazine').turn('previous');
            setTimeout(function () {
                setArrows();
            }, 300);
        },
        // 下一页
        nextPage() {
            $('.magazine').turn('next');
            setTimeout(function () {
                setArrows();
            }, 300);
        },
        async DownloadPdf() {
            this.loading = true;
            this.targetProgress = 1;
            // this.showReportLoading = true;
            //获取所有的area_page 元素
            const elements = document.querySelectorAll(".web_mode .web_cover");
            const pdf = new jsPDF("p", "pt", "a4"); // 'p'表示纵向，'a4'表示A4纸张尺寸
            const pdfWidth = pdf.internal.pageSize.getWidth(); //获取pdf的宽度
            const pdfHeight = pdf.internal.pageSize.getHeight(); //获取pdf的高度
            let yPos = 0; //当前图像在pdf页面上的垂直位置的变量
            let i = 1;
            let imageList = [];
            // 遍历每个 area_page 元素并按顺序处理
            for (const element of elements) {
                await html2canvas(element, {
                    scale: 2, // 增加缩放比例
                    useCORS: true, // 允许跨域
                    logging: true, // 是否显示进度条
                    letterRendering: true, // 文字抗锯齿 启用字母渲染
                }).then(async(canvas) => {
                    // 将 Canvas 对象转换为 PNG 格式的 Data URL 字符串
                    const blob = await new Promise((resolve) => canvas.toBlob(resolve, "image/png"));
                    const imgUrl = URL.createObjectURL(blob);
                    imageList.push(imgUrl)
                });
            }
            imageList.splice(1, 0, ...this.bookPages);
            // console.log(imageList)
            const stepLens = imageList?.length || 1;
            for (const imgData of imageList) {
                const imgProps = pdf.getImageProperties(imgData); // 获取图像的属性，包括宽度和高度
                const imgWidth = imgProps.width;
                const imgHeight = imgProps.height;
                const ratio = Math.min(pdfWidth / imgWidth, pdfHeight / imgHeight); //计算图片的缩放比例
                const adjustWidth = imgWidth * ratio;
                const adjustHeight = imgHeight * ratio;

                // 在添加每个图像之前，检查当前页面的高度是否足够。如果不够，则添加新页面，并将 yPos 重置为 0
                if (yPos + adjustHeight > pdfHeight) {
                    pdf.addPage();
                    yPos = 0;
                }

                // 将图像添加到pdf中
                pdf.addImage(imgData, "PNG", 0, yPos, adjustWidth, adjustHeight);
                yPos += adjustHeight;

                // 如果添加图像后剩余空间不足一页，则添加新页面
                if (yPos > pdfHeight) {
                    pdf.addPage();
                    yPos = 0;
                }
                const currentProgress  = Math.min(Math.round((i / stepLens) * 100),100);
                this.targetProgress = currentProgress;
                i++;
            }
            // 保存pdf文件
            pdf.save(`${this.reportTitle}_${this.coverTitle}.pdf`);
            // this.showReportLoading = false; //关闭加载loading
            this.loading = false;
        },
        // async DownloadPdfNew() {
        //     //获取所有的area_page 元素
        //     const elements = document.querySelectorAll(".web_mode .web_area_page");
        //     this.loading = true;
        //     // this.targetProgress = 1;
        //     // this.showReportLoading = true;
        //     const pdf = new jsPDF("p", "pt", "a4"); // 'p'表示纵向，'a4'表示A4纸张尺寸
        //     const pdfWidth = pdf.internal.pageSize.getWidth(); //获取pdf的宽度
        //     const pdfHeight = pdf.internal.pageSize.getHeight(); //获取pdf的高度
        //     let yPos = 0; //当前图像在pdf页面上的垂直位置的变量
        //     // let i = 1;
        //     let imageList = [];
        //     // 遍历每个 area_page 元素并按顺序处理
        //     for (const element of elements) {
        //         await html2canvas(element, {
        //             scale: 2, // 增加缩放比例
        //             useCORS: true, // 允许跨域
        //             logging: true, // 是否显示进度条
        //             letterRendering: true, // 文字抗锯齿 启用字母渲染
        //         }).then(async(canvas) => {
        //             // 将 Canvas 对象转换为 PNG 格式的 Data URL 字符串
        //             const blob = await new Promise((resolve) => canvas.toBlob(resolve, "image/png"));
        //             const imgUrl = URL.createObjectURL(blob);
        //             imageList.push(imgUrl)
        //         });
        //     }
        //     // const stepLens = imageList?.length || 1;
        //     for (const imgData of imageList) {
        //         const imgProps = pdf.getImageProperties(imgData); // 获取图像的属性，包括宽度和高度
        //         const imgWidth = imgProps.width;
        //         const imgHeight = imgProps.height;
        //         const ratio = Math.min(pdfWidth / imgWidth, pdfHeight / imgHeight); //计算图片的缩放比例
        //         const adjustWidth = imgWidth * ratio;
        //         const adjustHeight = imgHeight * ratio;

        //         // 在添加每个图像之前，检查当前页面的高度是否足够。如果不够，则添加新页面，并将 yPos 重置为 0
        //         if (yPos + adjustHeight > pdfHeight) {
        //             pdf.addPage();
        //             yPos = 0;
        //         }

        //         // 将图像添加到pdf中
        //         pdf.addImage(imgData, "PNG", 0, yPos, adjustWidth, adjustHeight);
        //         yPos += adjustHeight;

        //         // 如果添加图像后剩余空间不足一页，则添加新页面
        //         if (yPos > pdfHeight) {
        //             pdf.addPage();
        //             yPos = 0;
        //         }
        //         // const currentProgress  = Math.min(Math.round((i / stepLens) * 100),100);
        //         // this.targetProgress = currentProgress;
        //         // i++;
        //     }
        //     // 保存pdf文件
        //     pdf.save(`${this.reportTitle}_${this.coverTitle}.pdf`);
        //     // this.showReportLoading = false; //关闭加载loading
        //     this.loading = false;
        //     this.$emit('PdfLoadEnd');
        // },
        async DownloadPdfNew() {
            //获取所有的area_page 元素
            const elements = document.querySelectorAll(".web_mode .web_area_page");
            const elLens = elements.length - 1;
            this.loading = true;
            // this.targetProgress = 1;
            // this.showReportLoading = true;
            const pdf = new jsPDF("p", "pt", "a4"); // 'p'表示纵向，'a4'表示A4纸张尺寸
            const pdfWidth = pdf.internal.pageSize.getWidth(); //获取pdf的宽度
            const pdfHeight = pdf.internal.pageSize.getHeight(); //获取pdf的高度
            // 遍历每个 area_page 元素并按顺序处理
            for (const [pageIndex, element] of Array.from(elements).entries()) {
                // 确保页面元素存在并可见
                await this.$nextTick();
                if (element) {
                    // 确保元素可见并已渲染
                    // 确保元素可见并已渲染，并设置为横向排列样式
                    element.style.visibility = 'visible';
                    element.offsetHeight; // 触发重排
                    // 等待元素完全渲染
                    await new Promise(resolve => setTimeout(resolve, 100));
                    
                    // 使用 dom-to-image 生成图片
                    const dataUrl = await domtoimage.toJpeg(element, {
                        quality: 0.8,// 降低质量以减小文件大小
                        // 获取完整尺寸
                        width: element.scrollWidth*2,
                        height: element.scrollHeight*2,
                        // 提高画布分辨率以获得更清晰的图像
                        // canvasWidth: element.scrollWidth * 2,
                        // canvasHeight: element.scrollHeight * 2,
                        // 新增高清配置
                        // pixelRatio: window.devicePixelRatio * 2,
                        style: {
                        'transform': 'scale(2)',
                        'transform-origin': 'left top',
                        'background-color': '#ffffff',
                        // 关键：背景图尺寸适配原元素
                        'background-size': `${element.scrollWidth}px ${element.scrollHeight}px`, // 优先铺满且完整显示
                        'background-position': 'top left',
                        'background-repeat': 'no-repeat', // 防止背景图重复导致视觉不完整
                        'overflow': 'visible',
                        'white-space': 'normal',
                        'position': 'relative',
                        'visibility': 'visible'
                        },
                        bgcolor: '#ffffff'
                    });
                    
                    // 获取图像属性并计算缩放比例
                    const imgProps = pdf.getImageProperties(dataUrl);

                    const imgWidth = imgProps.width;
                    const imgHeight = imgProps.height;
                    
                    // 计算缩放比例（保持宽高比）
                    const ratio = Math.min(pdfWidth / imgWidth, pdfHeight / imgHeight);
                    const adjustWidth = imgWidth * ratio;
                    const adjustHeight = imgHeight * ratio;

                    // 居中放置图像
                    const xPosition = (pdfWidth - adjustWidth) / 2;
                    const yPosition = (pdfHeight - adjustHeight) / 2;
                    // console.log("打印pdf图片尺寸", imgWidth, imgHeight);
                    // console.log("打印pdf页面尺寸", pdfWidth, pdfHeight);
                    // console.log("打印pdf缩放比例", ratio);
                    // console.log("打印pdf缩放后尺寸",adjustWidth, adjustHeight);
                    // console.log("打印pdf图片位置", xPosition, yPosition);
                    // 如果不是第一页，添加新页面
                    if (pageIndex > 0) 
                    {
                        pdf.addPage();
                    }
                    //处理封面图铺满屏
                    let pdfAdjustHeight = adjustHeight;
                    if(pageIndex == 0 || pageIndex == elLens){
                        pdfAdjustHeight = adjustHeight + 6
                    }
                    pdf.addImage(dataUrl, "JPEG", xPosition, yPosition - 6, adjustWidth, pdfAdjustHeight);
                }
            }
            // 保存pdf文件
            pdf.save(`${this.reportTitle}_${this.coverTitle}.pdf`);
            // this.showReportLoading = false; //关闭加载loading
            this.loading = false;
            this.$emit('PdfLoadEnd');
        },
    }
};
</script>

<style scoped lang="scss">
@import '../components/css/magazine.css'; // 引入 SCSS 文件

.report_page {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 0;
    box-sizing: border-box;
    background-color: #F0F4FB;
}

/* 书本容器样式 */
// #flipbook {
//     box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
// }

/* 单页样式（注意：宽度为书本的一半，因为默认双页显示） */
// .joint_print_area {
//     width: 50%;
//     height: 100%;
//     background-color: #fff;
//     overflow: hidden;
// }

// .area_page {
//     width: 100%;
//     height: 100%;
//     padding: 32px;
//     box-sizing: border-box;
//     // background: #FFFFFF;
//     box-shadow: inset 1px 0px 0px 0px #EEEEEE;
// }

/* 控制按钮样式 */
.book_controls {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 60px;
    background: #FFFFFF;
    // margin-top: 40px;
    padding: 12px 24px;
    box-sizing: border-box;

    .zoom {
        display: inline-flex;
        align-items: center;

        .zoom_icon {
            width: 32px;
            height: 32px;
            margin-right: 20px;
            cursor: pointer;
        }
    }

    .page_size {
        display: inline-flex;
        align-items: center;
        .butn_prev{
            width: 24px;
            height: 24px;
            margin-right: 15px;
            cursor: pointer;
        }
        .butn_next{
            width: 24px;
            height: 24px;
            margin-left: 15px;
            cursor: pointer;
        }
        img{
            width: 24px;
            height: 24px;
        }
        .page_info {
            font-weight: 500;
            font-size: 16px;
            color: #333333;
        }
    }

    .download {
        padding: 8px 16px;
        height: 36px;
        background-color: #2E64FA;
        border-radius: 4px;
        font-size: 14px;
        color: #FFFFFF;
        border: none;
        cursor: pointer;

        &:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
    }
}
</style>