/**
 * HTML转图片工具
 * 基于 html2canvas 实现，兼容低版本 Safari/微信
 */

import html2canvas from 'html2canvas';

/**
 * 将DOM元素转换为图片
 * @param {string|HTMLElement} selector - DOM选择器或元素
 * @param {Object} options - 配置选项
 * @param {number} [options.pixelRatio] - 像素比例，默认2
 * @param {string} [options.format] - 图片格式，'png'或'jpeg'，默认'png'
 * @param {number} [options.quality] - 图片质量，0-1，仅jpeg有效，默认1.0
 * @returns {Promise<string>} - 返回base64图片数据URL
 */
export async function toDataURL(selector, options = {}) {
    const {
        pixelRatio = 2,
        format = 'png',
        quality = 1.0
    } = options;

    const element = typeof selector === 'string' ? document.querySelector(selector) : selector;
    if (!element) throw new Error('Element not found');

    const canvas = await html2canvas(element, {
        scale: pixelRatio,
        useCORS: true,
        allowTaint: false,
        backgroundColor: '#ffffff',
        dpi: window.devicePixelRatio * pixelRatio,
        logging: false
    });

    const mimeType = format === 'jpeg' ? 'image/jpeg' : 'image/png';
    return canvas.toDataURL(mimeType, quality);
}

/**
 * 将DOM元素转换为图片并下载
 */
export async function toImageDownload(selector, filename = 'download', options = {}) {
    const dataUrl = await toDataURL(selector, options);
    const link = document.createElement('a');
    link.download = filename + '.png';
    link.href = dataUrl;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

/**
 * 转为 Blob
 */
export function toBlob(selector, options = {}) {
    return new Promise(async (resolve, reject) => {
        try {
            const dataUrl = await toDataURL(selector, options);
            const arr = dataUrl.split(',');
            const mime = arr[0].match(/:(.*?);/)[1];
            const bstr = atob(arr[1]);
            const u8arr = new Uint8Array(bstr.length);
            for (let i = 0; i < bstr.length; i++) {
                u8arr[i] = bstr.charCodeAt(i);
            }
            resolve(new Blob([u8arr], { type: mime }));
        } catch (e) {
            reject(e);
        }
    });
}

export default { toDataURL, toImageDownload, toBlob };