/**
 * HTML转图片工具
 * 基于 html2canvas + canvas2image
 */

/**
 * 将HTML元素转换为canvas
 * @param {HTMLElement} element - DOM元素
 * @param {Object} options - 配置参数
 * @param {number} [options.scale=2] - 缩放比例
 * @param {number} [options.width] - 指定宽度
 * @param {number} [options.height] - 指定高度
 * @param {boolean} [options.useCORS=true] - 是否支持跨域
 * @param {number} [options.dpi=window.devicePixelRatio] - DPI
 * @returns {Promise<HTMLCanvasElement>}
 */
export async function html2canvas(element, options = {}) {
    const {
        scale = 2,
        width,
        height,
        useCORS = true,
        dpi = window.devicePixelRatio,
        onclone,
    } = options;

    const opts = {
        scale,
        useCORS,
        dpi,
        logging: false,
        backgroundColor: '#ffffff',
    };

    if (width) opts.width = width;
    if (height) opts.height = height;

    // 添加 onclone 回调用于调试
    if (onclone) {
        opts.onclone = onclone;
    }

    const html2canvasFn = window.html2canvas;
    if (!html2canvasFn) {
        throw new Error('html2canvas not loaded, please include html2canvas.min.js');
    }

    return html2canvasFn(element, opts);
}

/**
 * 将canvas转换为dataURL
 * @param {HTMLCanvasElement} canvas
 * @param {string} [type='image/png']
 * @param {number} [quality=1.0]
 * @returns {string}
 */
export function canvasToDataURL(canvas, type = 'image/png', quality = 1.0) {
    return canvas.toDataURL(type, quality);
}

/**
 * 将canvas转换为Blob
 * @param {HTMLCanvasElement} canvas
 * @param {string} [type='image/png']
 * @param {number} [quality=1.0]
 * @returns {Promise<Blob>}
 */
export function canvasToBlob(canvas, type = 'image/png', quality = 1.0) {
    return new Promise((resolve, reject) => {
        canvas.toBlob(blob => {
            if (blob) {
                resolve(blob);
            } else {
                reject(new Error('Canvas to Blob failed'));
            }
        }, type, quality);
    });
}

/**
 * 将HTML元素直接转成dataURL图片
 * @param {HTMLElement} element - DOM元素
 * @param {Object} options - html2canvas配置
 * @param {string} [type='image/png'] - 图片类型
 * @param {number} [quality=1.0] - 图片质量
 * @returns {Promise<string>} dataURL
 */
export async function htmlToDataURL(element, options = {}, type = 'image/png', quality = 1.0) {
    const canvas = await html2canvas(element, options);
    return canvasToDataURL(canvas, type, quality);
}

/**
 * 将HTML元素直接转成Blob
 * @param {HTMLElement} element - DOM元素
 * @param {Object} options - html2canvas配置
 * @param {string} [type='image/png'] - 图片类型
 * @param {number} [quality=1.0] - 图片质量
 * @returns {Promise<Blob>}
 */
export async function htmlToBlob(element, options = {}, type = 'image/png', quality = 1.0) {
    const canvas = await html2canvas(element, options);
    return canvasToBlob(canvas, type, quality);
}

/**
 * 下载canvas为图片
 * @param {HTMLCanvasElement} canvas
 * @param {string} filename - 文件名（不带扩展名）
 * @param {string} [type='png'] - 图片格式 ('png' | 'jpeg' | 'webp')
 */
export function downloadCanvas(canvas, filename, type = 'png') {
    const mimeType = `image/${type}`;
    const dataURL = canvasToDataURL(canvas, mimeType, 1.0);

    const link = document.createElement('a');
    link.download = `${filename}.${type}`;
    link.href = dataURL;
    link.click();
}

/**
 * 将HTML元素转成图片并下载
 * @param {HTMLElement} element - DOM元素
 * @param {string} filename - 文件名（不带扩展名）
 * @param {Object} options - html2canvas配置
 * @param {string} [type='png'] - 图片格式
 */
export async function htmlToImage(element, filename, options = {}, type = 'png') {
    const canvas = await html2canvas(element, options);
    downloadCanvas(canvas, filename, type);
}

/**
 * 将dataURL保存为图片文件
 * @param {string} dataURL - 图片dataURL
 * @param {string} filename - 文件名（不带扩展名）
 */
export function downloadDataURL(dataURL, filename) {
    const link = document.createElement('a');
    link.download = filename;
    link.href = dataURL;
    link.click();
}

/**
 * 将Blob保存为图片文件
 * @param {Blob} blob - 图片Blob
 * @param {string} filename - 文件名（不带扩展名）
 */
export async function downloadBlob(blob, filename) {
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.download = filename;
    link.href = url;
    link.click();
    setTimeout(() => URL.revokeObjectURL(url), 100);
}
