import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
import { useState, useEffect, useRef } from 'react';
import Flex from "@/components/Flex";
import { Modal, Progress } from 'antd';
import dayjs from 'dayjs';
import useSaveFile from '@/stores/useSaveFile';

/**
 * @function 下载Excel文件
 * @param {Object} res  接口返回的数据
 * @param {string} name 文件名
 */
export const downloadExcelFile = (res, name = 'download') => {
    let fileName = `${name}.xlsx`;
    const blob = new Blob([res?.data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    });
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(downloadUrl);
};

export const exportToPDF = async (elementId, fileName = 'document.pdf') => {
    try {
        const element = document.getElementById(elementId);
        if (!element) throw new Error('Element not found');

        // 1. 设置PDF为适合内容的方向
        const isLandscape = element.scrollWidth > element.scrollHeight;
        const pdf = new jsPDF({
            orientation: isLandscape ? 'landscape' : 'portrait',
            unit: 'px' // 使用像素单位保持精确比例
        });

        // 2. 设置高质量截图参数
        const canvas = await html2canvas(element, {
            scale: 2, // 提高清晰度
            logging: true,
            useCORS: true,
            allowTaint: true,
            backgroundColor: '#FFFFFF',
            onclone: (clonedDoc) => {
                // 确保所有内容可见
                clonedDoc.body.style.overflow = 'visible';
                clonedDoc.body.style.width = `${element.scrollWidth}px`;
            }
        });

        // 3. 计算PDF页面尺寸（保持内容原始比例）
        const contentWidth = canvas.width;
        const contentHeight = canvas.height;
        const pdfWidth = pdf.internal.pageSize.getWidth();
        const pdfHeight = (contentHeight * pdfWidth) / contentWidth;

        // 4. 如果内容高度超过PDF最大高度，自动调整
        const maxPdfHeight = pdf.internal.pageSize.getHeight() * 10; // 允许10页高度
        const finalPdfHeight = Math.min(pdfHeight, maxPdfHeight);

        // 5. 添加图像到PDF（单页）
        pdf.addImage(
            canvas.toDataURL('image/png', 1.0), // 最高质量PNG
            'PNG',
            0, // x
            0, // y
            pdfWidth,
            finalPdfHeight,
            undefined,
            'FAST' // 平衡速度和质量
        );

        // 6. 保存PDF
        pdf.save(fileName);
    } catch (error) {
        console.error('PDF导出错误:', error);
        throw error;
    }
};




const PdfExportProcess = ({ total, title, onFinish }) => {

    const { setActionShow } = useSaveFile();
    const [current, setCurrent] = useState(0)
    const pdfRef = useRef({
        pdf: new jsPDF({
            orientation: 'landscape',
            unit: 'pt', // 使用像素单位保持精确比例,
            format: [841.89,400]
        }), 
        padding: 8, 
        a4Width: 842,
    });

    useEffect(() => {
        exportPdf();
    }, [current]);

    ///////////////////////////////////////// 逻辑方法

    const exportPdf = () => {

        function goNextPage (img){
            if(img){
                let ptWidth = (pdfRef.current.a4Width - pdfRef.current.padding * 2);
                const ptHeight = ptWidth / img.width * img.height;
                pdfRef.current.pdf.addImage(img, 'JPEG', pdfRef.current.padding, pdfRef.current.padding, ptWidth, ptHeight);
            }
            if (current < total - 1) {
                if(img) {
                    pdfRef.current.pdf.addPage();
                }
                setCurrent(current + 1);
            } else {
                if (onFinish) {
                    setActionShow(true);
                    onFinish();
                }
                pdfRef.current.pdf.save(`${title}_${dayjs().format("YYYYMMDD_HHmmss")}.pdf`);
            }
        }
        html2canvas(document.getElementById("operationExport" + current), {
            useCORS: true, allowTaint: true, scale: 1.5
        }).then(img => {
            goNextPage(img);
        }).catch(()=>{
            goNextPage();
        });
    };


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

    return <Flex>
        <Progress percent={current * 100 / total}
            format={(percent) => percent.toFixed(2) + '%'}
            size={'default'}
            strokeColor="#1890FF"
            trailColor='#E8E8E8' />
    </Flex>;
};


/**
 * 保存pdf文件
 * @param pageTotal 总页数
 * @param title 文件名称
 */
export const savePdf = async (pageTotal, title) => {
    let modal = Modal.confirm({
        title: "导出分析报告",
        width: 500,
        centered:true,
        content: <PdfExportProcess title={title}
            total={pageTotal}
            onFinish={() => {
                modal.destroy();
            }} />
    });
};