/**
 * 图片压缩工具类
 * 将图片压缩到指定尺寸和文件大小
 */

export interface CompressOptions {
    width?: number;
    height?: number;
    quality?: number;
    maxSize?: number; // KB
}

export const compressImage = (
    file: File,
    options: CompressOptions = {}
): Promise<File> => {
    const {
        quality = 0.8
    } = options;

    return new Promise((resolve, reject) => {
        if (!file || !file.type.includes('image')) {
            reject(new Error('无效的图片文件'));
            return;
        }

        const fileSizeKB = file.size / 1024;
        const targetSizeKB = fileSizeKB / 2;

        console.log(`原文件: ${fileSizeKB.toFixed(1)}KB, 目标: ${targetSizeKB.toFixed(1)}KB`);

        // 对于小文件，直接尝试转换格式压缩
        if (fileSizeKB < 300 && file.type === 'image/png') {
            console.log('PNG小文件，尝试转换为JPEG格式压缩');

            const reader = new FileReader();
            reader.onload = (e) => {
                const img = new Image();
                img.onload = () => {
                    compressSmallPngToJpeg(img, file, targetSizeKB, resolve, reject);
                };
                img.onerror = () => reject(new Error('图片加载失败'));
                img.src = e.target?.result as string;
            };
            reader.onerror = () => reject(new Error('文件读取失败'));
            reader.readAsDataURL(file);
            return;
        }

        // 正常压缩流程
        const reader = new FileReader();
        reader.onload = (e) => {
            const img = new Image();
            img.onload = () => {
                compressToHalfSize(img, file, quality, resolve, reject);
            };
            img.onerror = () => reject(new Error('图片加载失败'));
            img.src = e.target?.result as string;
        };
        reader.onerror = () => reject(new Error('文件读取失败'));
        reader.readAsDataURL(file);
    });
};

// PNG小文件转JPEG压缩
function compressSmallPngToJpeg(
    img: HTMLImageElement,
    originalFile: File,
    targetSizeKB: number,
    resolve: (file: File) => void,
    reject: (error: Error) => void
) {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');

    if (!ctx) {
        reject(new Error('浏览器不支持Canvas'));
        return;
    }

    console.log(`PNG转JPEG: ${img.width}x${img.height}, 目标: ${targetSizeKB.toFixed(1)}KB`);

    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage(img, 0, 0, img.width, img.height);

    // 尝试转换为JPEG格式并压缩
    const compressAsJpeg = (quality: number): void => {
        canvas.toBlob(
            (blob) => {
                if (!blob) {
                    reject(new Error('JPEG转换失败'));
                    return;
                }

                const sizeKB = blob.size / 1024;
                console.log(`JPEG质量: ${quality.toFixed(2)}, 大小: ${sizeKB.toFixed(1)}KB`);

                if (sizeKB <= targetSizeKB || quality <= 0.1) {
                    // 创建新的JPEG文件
                    const jpegFileName = originalFile.name.replace(/\.png$/i, '.jpg');
                    const compressedFile = new File([blob], jpegFileName, {
                        type: 'image/jpeg',
                        lastModified: Date.now()
                    });

                    const originalSizeKB = originalFile.size / 1024;
                    console.log(`✅ PNG→JPEG压缩完成: ${originalSizeKB.toFixed(1)}KB → ${sizeKB.toFixed(1)}KB`);
                    resolve(compressedFile);
                } else {
                    const nextQuality = Math.max(0.1, quality - 0.1);
                    compressAsJpeg(nextQuality);
                }
            },
            'image/jpeg', // 强制转换为JPEG
            quality
        );
    };

    compressAsJpeg(0.7); // 从0.7质量开始
}

// 图片处理函数 - 压缩到原文件一半大小
function compressToHalfSize(
    img: HTMLImageElement,
    originalFile: File,
    initialQuality: number,
    resolve: (file: File) => void,
    reject: (error: Error) => void
) {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');

    if (!ctx) {
        reject(new Error('浏览器不支持Canvas'));
        return;
    }

    const originalSizeKB = originalFile.size / 1024;
    const targetSizeKB = originalSizeKB / 2;

    console.log(`原图: ${img.width}x${img.height}, ${originalSizeKB.toFixed(1)}KB`);
    console.log(`目标: 压缩到 ${targetSizeKB.toFixed(1)}KB (原大小的一半)`);

    // 对于小文件(< 200KB)，直接用低质量压缩，不测试
    if (originalSizeKB < 200) {
        console.log(`小文件直接压缩模式`);
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.drawImage(img, 0, 0, img.width, img.height);

        // 直接从低质量开始压缩
        const compressDirectly = (quality: number): void => {
            canvas.toBlob((blob) => {
                if (!blob) {
                    reject(new Error('图片处理失败'));
                    return;
                }

                const sizeKB = blob.size / 1024;
                console.log(`直接压缩 质量: ${quality.toFixed(2)}, 大小: ${sizeKB.toFixed(1)}KB, 目标: ${targetSizeKB.toFixed(1)}KB`);

                if (sizeKB <= targetSizeKB || quality <= 0.1) {
                    const compressedFile = new File([blob], originalFile.name, {
                        type: originalFile.type,
                        lastModified: Date.now()
                    });

                    const compressionRatio = (sizeKB / originalSizeKB * 100).toFixed(1);
                    console.log(`✅ 小文件压缩完成: ${originalSizeKB.toFixed(1)}KB → ${sizeKB.toFixed(1)}KB (${compressionRatio}%)`);
                    resolve(compressedFile);
                } else {
                    const nextQuality = Math.max(0.1, quality - 0.1);
                    compressDirectly(nextQuality);
                }
            }, originalFile.type, quality);
        };

        compressDirectly(0.5); // 从0.5开始
        return;
    }

    // 大文件才做测试
    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage(img, 0, 0, img.width, img.height);

    // 先用初始质量测试一下
    canvas.toBlob((testBlob) => {
        if (!testBlob) {
            reject(new Error('图片处理失败'));
            return;
        }

        const testSizeKB = testBlob.size / 1024;
        console.log(`=== 详细分析 ===`);
        console.log(`原文件: ${originalSizeKB.toFixed(1)}KB`);
        console.log(`目标大小: ${targetSizeKB.toFixed(1)}KB (原大小的一半)`);
        console.log(`Canvas处理测试: ${testSizeKB.toFixed(1)}KB`);
        console.log(`变化: ${testSizeKB > originalSizeKB ? '+' : ''}${(testSizeKB - originalSizeKB).toFixed(1)}KB`);
        console.log(`是否需要继续压缩: ${testSizeKB > targetSizeKB ? '是' : '否'}`);

        // 如果初始处理后比原文件大很多(超过10%)，直接返回原文件
        if (testSizeKB > originalSizeKB * 1.1) {
            console.log(`⚠️ Canvas处理后变大超过10%，直接返回原文件`);
            resolve(originalFile);
            return;
        }

        // 如果Canvas处理后已经达到或接近目标大小，直接返回
        if (testSizeKB <= targetSizeKB) {
            console.log(`✅ Canvas处理后已经达到目标大小，直接返回`);
            const compressedFile = new File([testBlob], originalFile.name, {
                type: originalFile.type,
                lastModified: Date.now()
            });
            resolve(compressedFile);
            return;
        }

        // 开始压缩循环 - 只降低质量，不提高
        const compress = (currentQuality: number): void => {
            canvas.toBlob(
                (blob) => {
                    if (!blob) {
                        reject(new Error('图片处理失败'));
                        return;
                    }

                    const sizeKB = blob.size / 1024;
                    console.log(`质量: ${currentQuality.toFixed(2)}, 大小: ${sizeKB.toFixed(1)}KB, 目标: ${targetSizeKB.toFixed(1)}KB`);

                    // 如果达到目标大小，立即返回
                    if (sizeKB <= targetSizeKB) {
                        const compressedFile = new File([blob], originalFile.name, {
                            type: originalFile.type,
                            lastModified: Date.now()
                        });

                        const compressionRatio = (sizeKB / originalSizeKB * 100).toFixed(1);
                        console.log(`✅ 压缩完成!`);
                        console.log(`大小: ${originalSizeKB.toFixed(1)}KB → ${sizeKB.toFixed(1)}KB (${compressionRatio}%)`);

                        resolve(compressedFile);
                    } else if (currentQuality <= 0.1) {
                        // 质量已经很低但还没达到目标，返回当前结果
                        const compressedFile = new File([blob], originalFile.name, {
                            type: originalFile.type,
                            lastModified: Date.now()
                        });

                        const compressionRatio = (sizeKB / originalSizeKB * 100).toFixed(1);
                        console.log(`⚠️ 已达到最低质量，无法继续压缩`);
                        console.log(`大小: ${originalSizeKB.toFixed(1)}KB → ${sizeKB.toFixed(1)}KB (${compressionRatio}%)`);

                        resolve(compressedFile);
                    } else {
                        // 文件还是太大，继续降低质量
                        const nextQuality = Math.max(0.05, currentQuality - 0.1);
                        console.log(`文件还是太大(${sizeKB.toFixed(1)}KB > ${targetSizeKB.toFixed(1)}KB)，降低质量到 ${nextQuality.toFixed(2)}`);
                        compress(nextQuality);
                    }
                },
                originalFile.type,
                currentQuality
            );
        };

        // 从初始质量开始压缩
        compress(initialQuality);

    }, originalFile.type, initialQuality);
}