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

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.diagnosis.domain.BizServiceAppointment;

/**
 * 我的预约（机构）入参校验。
 */
public final class OrgAppointmentValidation
{
    private static final String DATE_PATTERN = "yyyy-MM-dd";

    private OrgAppointmentValidation()
    {
    }

    public static void validateListQuery(BizServiceAppointment query)
    {
        if (query == null)
        {
            return;
        }
        Integer status = query.getStatus();
        if (status != null && !ServiceAppointmentRules.isOrgListStatusValid(status))
        {
            throw new ServiceException("状态筛选无效");
        }
        validateDateRange(query.getStartDate(), query.getEndDate());
    }

    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("结束日期不能早于开始日期");
        }
    }

    private static Date parseQueryDate(String text, String label)
    {
        try
        {
            SimpleDateFormat fmt = new SimpleDateFormat(DATE_PATTERN);
            fmt.setLenient(false);
            return fmt.parse(text.trim());
        }
        catch (ParseException ex)
        {
            throw new ServiceException(label + "格式无效，应为 yyyy-MM-dd");
        }
    }
}
