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

import java.math.BigDecimal;
import java.util.Date;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.industrypolicy.domain.BizSubsidyProject;

/**
 * 项目与补贴-项目入参校验。
 */
public final class SubsidyProjectValidation
{
    private SubsidyProjectValidation()
    {
    }

    public static void trimFieldsForSave(BizSubsidyProject 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(intro.isEmpty() ? null : intro);
        }
        if (row.getCoverFileUrl() != null)
        {
            row.setCoverFileUrl(row.getCoverFileUrl().trim());
        }
        if (row.getCoverFilePath() != null)
        {
            row.setCoverFilePath(row.getCoverFilePath().trim());
        }
        if (row.getRemark() != null)
        {
            String remark = row.getRemark().trim();
            row.setRemark(remark.isEmpty() ? null : remark);
        }
    }

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

    public static void validateIntroduction(String introduction)
    {
        if (introduction != null && introduction.length() > 50)
        {
            throw new ServiceException("项目简介不能超过50个字符");
        }
    }

    public static void validateInvestmentAmount(BigDecimal amount)
    {
        if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0)
        {
            throw new ServiceException("投资金额须大于0");
        }
        if (amount.scale() > 2)
        {
            throw new ServiceException("投资金额最多保留2位小数");
        }
        if (amount.stripTrailingZeros().scale() > 2)
        {
            throw new ServiceException("投资金额最多保留2位小数");
        }
    }

    public static void validatePlanDates(Date projectStartDate, Date plannedEndDate)
    {
        if (projectStartDate == null)
        {
            throw new ServiceException("项目开始日期不能为空");
        }
        if (plannedEndDate == null)
        {
            throw new ServiceException("预计完成日期不能为空");
        }
        Date s = SubsidyProjectStatusResolver.truncateToDay(projectStartDate);
        Date e = SubsidyProjectStatusResolver.truncateToDay(plannedEndDate);
        if (e.before(s))
        {
            throw new ServiceException("预计完成日期不能早于项目开始日期");
        }
    }

    public static void validateActualEndDateWhenCompleted(Date actualEndDate)
    {
        if (actualEndDate == null)
        {
            throw new ServiceException("执行状态为已完成时，实际完成日期不能为空");
        }
        Date end = SubsidyProjectStatusResolver.truncateToDay(actualEndDate);
        Date today = SubsidyProjectStatusResolver.truncateToDay(new Date());
        if (end.after(today))
        {
            throw new ServiceException("实际完成日期不能为未来日期");
        }
    }

    public static void validateExecStatus(Integer execStatus)
    {
        if (execStatus == null || execStatus < SubsidyProjectRules.EXEC_NOT_STARTED
                || execStatus > SubsidyProjectRules.EXEC_COMPLETED)
        {
            throw new ServiceException("执行状态须为1～3（1未开始2进行中3已完成）");
        }
    }

    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 (!SubsidyProjectRules.isCoverExtensionAllowed(coverPath))
        {
            throw new ServiceException("封面格式不支持，允许：jpg、jpeg、png");
        }
        if (!coverPath.startsWith(Constants.RESOURCE_PREFIX))
        {
            throw new ServiceException("封面存储路径非法");
        }
    }

    public static void validateDateRange(String startDate, String endDate)
    {
        boolean hasStart = StringUtils.isNotEmpty(startDate);
        boolean hasEnd = StringUtils.isNotEmpty(endDate);
        if (!hasStart && !hasEnd)
        {
            return;
        }
        Date start = hasStart ? parseQueryDate(startDate, "开始日期") : null;
        Date end = hasEnd ? parseQueryDate(endDate, "结束日期") : null;
        if (start != null && end != null && start.after(end))
        {
            throw new ServiceException("项目开始日期筛选：开始不能晚于结束");
        }
    }

    public static void validateRowForSave(BizSubsidyProject row)
    {
        trimFieldsForSave(row);
        validateProjectName(row.getProjectName());
        validateIntroduction(row.getIntroduction());
        validateInvestmentAmount(row.getInvestmentAmount());
        validatePlanDates(row.getProjectStartDate(), row.getPlannedEndDate());
        validateExecStatus(row.getExecStatus());
        validateCoverPair(row.getCoverFileUrl(), row.getCoverFilePath());
    }

    private static Date parseQueryDate(String text, String label)
    {
        Date date = DateUtils.parseDate(text);
        if (date == null)
        {
            throw new ServiceException(label + "格式不正确，须为 yyyy-MM-dd");
        }
        return date;
    }
}
