package com.ruoyi.web.modules.content.support;

import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.web.modules.content.constant.BannerConstants;

/**
 * Banner 图片路径与宽高比辅助
 */
public final class BannerImageSupport
{
    private static final String IMAGE_EXT_PATTERN = "(?i).*\\.(jpg|jpeg|png)$";

    private BannerImageSupport()
    {
    }

    public static void validateImageUrl(String bannerImage)
    {
        if (StringUtils.isEmpty(bannerImage))
        {
            throw new com.ruoyi.common.exception.ServiceException("请上传图片");
        }
        if (!bannerImage.matches(IMAGE_EXT_PATTERN))
        {
            throw new com.ruoyi.common.exception.ServiceException("仅支持 jpg/png/jpeg，单张不超过 5MB");
        }
    }

    /**
     * 非 2:1 时返回 true；无法读取尺寸时返回 false
     */
    public static boolean isNonStandardAspectRatio(String bannerImage)
    {
        if (StringUtils.isEmpty(bannerImage))
        {
            return false;
        }
        try
        {
            String localPath = resolveLocalPath(bannerImage);
            if (localPath == null)
            {
                return false;
            }
            File file = new File(localPath);
            if (!file.isFile())
            {
                return false;
            }
            BufferedImage image = ImageIO.read(file);
            if (image == null || image.getHeight() <= 0)
            {
                return false;
            }
            double ratio = (double) image.getWidth() / image.getHeight();
            return Math.abs(ratio - BannerConstants.TARGET_ASPECT_RATIO) > BannerConstants.ASPECT_RATIO_TOLERANCE;
        }
        catch (Exception ignored)
        {
            return false;
        }
    }

    private static String resolveLocalPath(String bannerImage)
    {
        String path = bannerImage;
        if (path.startsWith(Constants.RESOURCE_PREFIX))
        {
            path = FileUtils.stripPrefix(path);
        }
        return RuoYiConfig.getProfile() + path;
    }
}
