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

import java.util.Date;
import com.ruoyi.web.modules.technology.domain.BizPracticalTraining;

/**
 * 培训状态计算与展示字段填充（training_status 入库，enrollStatus 供管理端兼容展示）。
 */
public final class PracticalTrainingEnrollStatusResolver
{
    private PracticalTrainingEnrollStatusResolver()
    {
    }

    /**
     * 按业务规则计算培训状态编码（006001–006004）。
     */
    public static String resolveTrainingStatus(BizPracticalTraining row, Date now)
    {
        if (row == null || now == null)
        {
            return PracticalTrainingRules.TRAINING_STATUS_NOT_STARTED;
        }
        if (row.getPublishStatus() == null
                || row.getPublishStatus() == PracticalTrainingRules.PUBLISH_STATUS_DRAFT)
        {
            return PracticalTrainingRules.TRAINING_STATUS_NOT_STARTED;
        }
        Date regStart = row.getRegistrationStartTime();
        Date regEnd = row.getRegistrationEndTime();
        if (regEnd != null && !now.before(regEnd))
        {
            return PracticalTrainingRules.TRAINING_STATUS_CLOSED;
        }
        if (regStart != null && now.before(regStart))
        {
            return PracticalTrainingRules.TRAINING_STATUS_NOT_STARTED;
        }
        Integer actual = row.getActualEnrolledCount();
        Integer planned = row.getPlannedHeadCount();
        if (actual != null && planned != null && actual >= planned)
        {
            return PracticalTrainingRules.TRAINING_STATUS_FULL;
        }
        if (regStart != null && regEnd != null && !now.before(regStart) && now.before(regEnd))
        {
            return PracticalTrainingRules.TRAINING_STATUS_ENROLLING;
        }
        return PracticalTrainingRules.TRAINING_STATUS_NOT_STARTED;
    }

    /** @deprecated 使用 {@link #resolveTrainingStatus}；保留供单测与兼容 */
    public static int resolveEnrollStatus(BizPracticalTraining row, Date now)
    {
        return PracticalTrainingRules.enrollStatusFromTrainingStatus(resolveTrainingStatus(row, now));
    }

    public static void applyEnrollStatus(BizPracticalTraining row, Date now)
    {
        if (row == null)
        {
            return;
        }
        String trainingStatus = resolveTrainingStatus(row, now);
        row.setTrainingStatus(trainingStatus);
        int enrollStatus = PracticalTrainingRules.enrollStatusFromTrainingStatus(trainingStatus);
        row.setEnrollStatus(enrollStatus);
        row.setEnrollStatusName(PracticalTrainingRules.enrollStatusName(enrollStatus));
        row.setCanOffline(canOffline(row, now));
    }

    public static boolean canOffline(BizPracticalTraining row, Date now)
    {
        if (row == null || now == null || !PracticalTrainingRules.canOffline(row.getPublishStatus()))
        {
            return false;
        }
        Date regStart = row.getRegistrationStartTime();
        return regStart != null && now.before(regStart);
    }
}
