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

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.prosperity.domain.BizCommonProsperityProject;
import com.ruoyi.web.modules.prosperity.domain.BizCommonProsperityProjectOpImage;

/**
 * 共同富裕项目入参校验。
 */
public final class CommonProsperityProjectValidation
{
    private CommonProsperityProjectValidation()
    {
    }

    public static void trimFieldsForSave(BizCommonProsperityProject row)
    {
        if (row == null)
        {
            return;
        }
        if (row.getProjectName() != null)
        {
            row.setProjectName(row.getProjectName().trim());
        }
        if (row.getIntroduction() != null)
        {
            String intro = row.getIntroduction().trim();
            row.setIntroduction(StringUtils.isEmpty(intro) ? null : intro);
        }
        if (row.getProjectContent() != null)
        {
            String content = row.getProjectContent().trim();
            row.setProjectContent(StringUtils.isEmpty(content) ? null : content);
        }
        if (row.getImplStatus() != null)
        {
            String status = row.getImplStatus().trim();
            row.setImplStatus(StringUtils.isEmpty(status) ? null : status);
        }
        if (row.getVideoFileUrl() != null)
        {
            row.setVideoFileUrl(row.getVideoFileUrl().trim());
        }
        if (row.getVideoFilePath() != null)
        {
            row.setVideoFilePath(row.getVideoFilePath().trim());
        }
        if (row.getCoverFileUrl() != null)
        {
            row.setCoverFileUrl(row.getCoverFileUrl().trim());
        }
        if (row.getCoverFilePath() != null)
        {
            row.setCoverFilePath(row.getCoverFilePath().trim());
        }
        if (row.getOperationImages() != null)
        {
            for (BizCommonProsperityProjectOpImage img : row.getOperationImages())
            {
                if (img == null)
                {
                    continue;
                }
                if (img.getFileUrl() != null)
                {
                    img.setFileUrl(img.getFileUrl().trim());
                }
                if (img.getFilePath() != null)
                {
                    img.setFilePath(img.getFilePath().trim());
                }
            }
        }
    }

    public static void validateProjectName(String projectName)
    {
        if (StringUtils.isEmpty(projectName) || projectName.length() < 1 || projectName.length() > 64)
        {
            throw new ServiceException("项目名称须为1～64个字符");
        }
    }

    public static void validateProjectType(Integer projectType)
    {
        if (projectType == null || projectType < 1 || projectType > 3)
        {
            throw new ServiceException("项目类型须为1～3（1和美乡村建设2人居环境整治提升3其他项目投入）");
        }
    }

    /** 选填；有值时长度 1～50 */
    public static void validateIntroduction(String introduction)
    {
        if (StringUtils.isEmpty(introduction))
        {
            return;
        }
        if (introduction.length() > 50)
        {
            throw new ServiceException("项目简介不能超过50个字符");
        }
    }

    /** 选填；有值时长度不超过 500 */
    public static void validateProjectContent(String projectContent)
    {
        if (StringUtils.isEmpty(projectContent))
        {
            return;
        }
        if (projectContent.length() > 500)
        {
            throw new ServiceException("建设规模及内容不能超过500个字符");
        }
    }

    public static void validateInvestmentAmount(BigDecimal amount)
    {
        if (amount == null)
        {
            return;
        }
        if (amount.compareTo(BigDecimal.ZERO) < 0)
        {
            throw new ServiceException("投资金额不能为负数");
        }
        if (amount.scale() > 4)
        {
            throw new ServiceException("投资金额最多保留4位小数");
        }
    }

    public static void validateImplYear(Integer implYear)
    {
        if (implYear == null)
        {
            throw new ServiceException("实施年限不能为空");
        }
        int current = Calendar.getInstance().get(Calendar.YEAR);
        int minYear = current - CommonProsperityProjectRules.IMPL_YEAR_LOOKBACK;
        if (implYear < minYear || implYear > current)
        {
            throw new ServiceException("实施年限须为当前年及向前共5个自然年");
        }
    }

    public static void validateImplStatus(String implStatus)
    {
        if (StringUtils.isNotEmpty(implStatus) && implStatus.length() > 500)
        {
            throw new ServiceException("实施情况不能超过500个字符");
        }
    }

    public static void validateOperationImages(List<BizCommonProsperityProjectOpImage> images)
    {
        if (images == null || images.isEmpty())
        {
            throw new ServiceException("运营图片至少需要1张，最多3张");
        }
        if (images.size() > 3)
        {
            throw new ServiceException("运营图片至少需要1张，最多3张");
        }
        Set<Integer> sortOrders = new HashSet<>();
        for (BizCommonProsperityProjectOpImage img : images)
        {
            if (img == null)
            {
                throw new ServiceException("运营图片数据无效");
            }
            if (StringUtils.isEmpty(img.getFileUrl()) || StringUtils.isEmpty(img.getFilePath()))
            {
                throw new ServiceException("运营图片 url 与 path 不能为空");
            }
            Integer sort = img.getSortOrder();
            if (sort == null || sort < 1 || sort > 3)
            {
                throw new ServiceException("运营图片排序须为1～3");
            }
            if (!sortOrders.add(sort))
            {
                throw new ServiceException("运营图片排序不能重复");
            }
            if (!CommonProsperityProjectRules.isOperationImageExtensionAllowed(img.getFilePath()))
            {
                throw new ServiceException("运营图片格式不支持，允许：jpg、jpeg、png");
            }
            if (!img.getFilePath().startsWith(Constants.RESOURCE_PREFIX))
            {
                throw new ServiceException("运营图片存储路径非法");
            }
        }
    }

    public static void validateVideoPair(String videoUrl, String videoPath)
    {
        boolean hasUrl = StringUtils.isNotEmpty(videoUrl);
        boolean hasPath = StringUtils.isNotEmpty(videoPath);
        if (hasUrl != hasPath)
        {
            throw new ServiceException("运营视频 url 与 path 须同时填写或同时为空");
        }
        if (!hasPath)
        {
            return;
        }
        if (!CommonProsperityProjectRules.isVideoExtensionAllowed(videoPath))
        {
            throw new ServiceException("运营视频格式不支持，允许：mp4");
        }
        if (!videoPath.startsWith(Constants.RESOURCE_PREFIX))
        {
            throw new ServiceException("运营视频存储路径非法");
        }
    }

    public static void validateCoverPair(String coverUrl, String coverPath)
    {
        boolean hasUrl = StringUtils.isNotEmpty(coverUrl);
        boolean hasPath = StringUtils.isNotEmpty(coverPath);
        if (hasUrl != hasPath)
        {
            throw new ServiceException("封面 url 与 path 须同时填写或同时为空");
        }
        if (!hasPath)
        {
            return;
        }
        if (!CommonProsperityProjectRules.isCoverExtensionAllowed(coverPath))
        {
            throw new ServiceException("封面格式不支持，允许：jpg、jpeg、png");
        }
        if (!coverPath.startsWith(Constants.RESOURCE_PREFIX))
        {
            throw new ServiceException("封面存储路径非法");
        }
    }

    public static void validateRowForSave(BizCommonProsperityProject row)
    {
        trimFieldsForSave(row);
        validateProjectName(row.getProjectName());
        validateProjectType(row.getProjectType());
        validateIntroduction(row.getIntroduction());
        validateProjectContent(row.getProjectContent());
        validateInvestmentAmount(row.getInvestmentAmount());
        validateImplYear(row.getImplYear());
        validateImplStatus(row.getImplStatus());
        validateOperationImages(row.getOperationImages());
        validateVideoPair(row.getVideoFileUrl(), row.getVideoFilePath());
        validateCoverPair(row.getCoverFileUrl(), row.getCoverFilePath());
    }
}
