export async function mergeImage(urlList, CoordinateList) {
    if (!Array.isArray(urlList) || !Array.isArray(CoordinateList)) {
        return '';
    }

    if (CoordinateList.length === 0 || urlList.length === 0) {
        return '';
    }

    const imageUrlList = []

    for (let i = 0; i < CoordinateList.length; i++) {
        const { page, x, y, w, h } = CoordinateList[i];
        const urlIndex = page - 1;
        const url = urlList[urlIndex];
        const _url = GetImageUrl(url, x, y, w, h);
        imageUrlList.push(_url);
    }

    if (imageUrlList.length === 1) {
        return imageUrlList[0];
    } else {
        // 多张图片合并
        const finalImage = await MergerImage(imageUrlList);
        return finalImage;
    }
}

function loadImage(url) {
    return new Promise((resolve, reject) => {
        const img = new Image();
        img.crossOrigin = "Anonymous";
        // 在 onload 中读取宽高，确保为真实尺寸
        img.onload = () => {
            const width = img.naturalWidth || img.width;
            const height = img.naturalHeight || img.height;
            resolve({
                img,
                width,
                height
            });
        };
        img.onerror = (err) => reject(err);
        img.src = url;
    })
}

export function GetImageUrl(base, x, y, w, h) {
    return `${base}?x-oss-process=image/crop,x_${x},y_${y},w_${w},h_${h}`
}

export function MergerImage(imageUrlList) {
    // 简化：只接受 url 或 base64 字符串数组
    return new Promise(async (resolve, reject) => {
        try {
            // 确保是数组并过滤出有效字符串
            const inputs = imageUrlList.filter(item => item);
            if (inputs.length === 0) return resolve('');

            // 使用 loadImage 加载并直接用返回的宽高创建 canvas（避免再去读取图片尺寸）
            const canvases = [];
            for (const url of inputs) {
                const { img, width, height } = await loadImage(url);
                const c = document.createElement('canvas');
                c.width = width;
                c.height = height;
                const ctx = c.getContext('2d');
                // 只绘制一次图片到 canvas 用于后续合并/缩放
                ctx.drawImage(img, 0, 0, width, height);
                canvases.push(c);
            }

            // 计算最大宽度并按比例缩放到该宽度
            let maxWidth = 0;
            for (const c of canvases) if (c.width > maxWidth) maxWidth = c.width;

            const scaled = canvases.map(c => {
                if (c.width === maxWidth) return c;
                const scale = maxWidth / c.width;
                const nc = document.createElement('canvas');
                nc.width = maxWidth;
                nc.height = Math.round(c.height * scale);
                const ctx = nc.getContext('2d');
                // 使用源 canvas 进行缩放绘制
                ctx.drawImage(c, 0, 0, c.width, c.height, 0, 0, nc.width, nc.height);
                return nc;
            });

            // 合并
            let totalH = scaled.reduce((s, c) => s + c.height, 0);
            const finalCanvas = document.createElement('canvas');
            finalCanvas.width = maxWidth;
            finalCanvas.height = totalH;
            const fctx = finalCanvas.getContext('2d');

            let y = 0;
            for (const c of scaled) {
                fctx.drawImage(c, 0, 0, c.width, c.height, 0, y, c.width, c.height);
                y += c.height;
            }

            resolve(finalCanvas.toDataURL('image/jpeg'));
        } catch (err) {
            reject(err);
        }
    });
}