export interface ResizeHalfOptions {
    quality?: number;
}

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

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

        const reader = new FileReader();
        reader.onload = (e) => {
            const img = new Image();
            img.onload = () => {
                resizeToHalfDimensions(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);
    });
};

/**
 * 图片处理函数 - 将图片长宽分辨率精确减半
 */
function resizeToHalfDimensions(
    img: HTMLImageElement,
    originalFile: File,
    quality: 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 halfWidth = Math.floor(img.width / 2);
    const halfHeight = Math.floor(img.height / 2);

    console.log(`原图尺寸: ${img.width}x${img.height}`);
    console.log(`减半后尺寸: ${halfWidth}x${halfHeight}`);

    // 设置canvas尺寸为原图的一半
    canvas.width = halfWidth;
    canvas.height = halfHeight;

    // 在canvas上绘制缩小后的图片
    // 使用平滑缩放算法以获得更好的图像质量
    ctx.imageSmoothingEnabled = true;
    ctx.imageSmoothingQuality = 'high';
    ctx.drawImage(img, 0, 0, halfWidth, halfHeight);

    // 将canvas转换为Blob并创建新的File对象
    canvas.toBlob(
        (blob) => {
            if (!blob) {
                reject(new Error('图片处理失败'));
                return;
            }

            // 创建新的文件名，添加_resize_half后缀
            const fileNameParts = originalFile.name.split('.');
            const extension = fileNameParts.pop();
            const fileNameWithoutExtension = fileNameParts.join('.');
            const newFileName = `${fileNameWithoutExtension}_half.${extension}`;

            // 创建压缩后的文件对象
            const resizedFile = new File([blob], newFileName, {
                type: originalFile.type,
                lastModified: Date.now()
            });

            console.log(`✅ 图片尺寸减半完成: ${img.width}x${img.height} → ${halfWidth}x${halfHeight}`);
            console.log(`文件大小: ${(originalFile.size / 1024).toFixed(1)}KB → ${(resizedFile.size / 1024).toFixed(1)}KB`);

            resolve(resizedFile);
        },
        originalFile.type,
        quality
    );
}