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

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.industryservice.domain.BizYakDiseaseWarning;

/**
 * 牦牛疾病预警 — 查询日期边界与预警文案拼装。
 * <p>
 * 时区统一 {@code Asia/Shanghai}：列表筛选将 {@code startDate}/{@code endDate}（yyyy-MM-dd）
 * 转为当日 00:00:00.000～23:59:59.999 写入 {@code alertTimeBegin}/{@code alertTimeEnd}。
 * </p>
 */
public final class YakDiseaseWarningValidation
{
    private static final String DATE_PATTERN = "yyyy-MM-dd";

    private static final TimeZone ZONE = TimeZone.getTimeZone("Asia/Shanghai");

    private YakDiseaseWarningValidation()
    {
    }

    /**
     * 解析并注入预警时间查询上下界。
     * <ul>
     *   <li>起止皆空：清空上下界；</li>
     *   <li>仅开始日：上界取「今天」日末；</li>
     *   <li>开始晚于结束：抛「开始日期不能晚于结束日期」。</li>
     * </ul>
     */
    public static void applyDateRange(BizYakDiseaseWarning query)
    {
        if (query == null)
        {
            return;
        }
        String start = StringUtils.trim(query.getStartDate());
        String end = StringUtils.trim(query.getEndDate());
        query.setStartDate(start);
        query.setEndDate(end);
        if (StringUtils.isEmpty(start) && StringUtils.isEmpty(end))
        {
            query.setAlertTimeBegin(null);
            query.setAlertTimeEnd(null);
            return;
        }
        Date startDay = StringUtils.isNotEmpty(start) ? parseDate(start) : null;
        Date endDay = StringUtils.isNotEmpty(end) ? parseDate(end) : null;
        if (startDay != null && endDay != null && startDay.after(endDay))
        {
            throw new ServiceException(YakDiseaseWarningRules.MSG_DATE_RANGE_INVALID);
        }
        if (startDay != null)
        {
            query.setAlertTimeBegin(dayBegin(startDay));
        }
        if (endDay != null)
        {
            query.setAlertTimeEnd(dayEnd(endDay));
        }
        else if (startDay != null)
        {
            query.setAlertTimeEnd(dayEnd(new Date()));
        }
    }

    /**
     * 生成入库 {@code alert_message}。
     * <p>优先使用 {@code presetMessage}；否则按预警类型用实测值/参考范围拼自然语言模板。</p>
     *
     * @param warningType   预警类型，可空
     * @param measuredValue 实测值描述，如 {@code 39.8℃}
     * @param referenceRange 参考范围描述
     * @param presetMessage 分析器或第三方已给出的全文，非空则直接采用
     */
    public static String buildAlertMessage(Integer warningType, String measuredValue, String referenceRange,
            String presetMessage)
    {
        if (StringUtils.isNotEmpty(presetMessage))
        {
            return presetMessage.trim();
        }
        String measured = StringUtils.trim(measuredValue);
        String reference = StringUtils.trim(referenceRange);
        if (warningType != null && warningType == YakDiseaseWarningRules.WARNING_TYPE_TEMP)
        {
            if (StringUtils.isNotEmpty(measured))
            {
                return "当前实测体温" + measured + "，超出" + (StringUtils.isNotEmpty(reference) ? reference : "正常体温参考范围")
                        + "，触发体温异常预警。";
            }
        }
        if (warningType != null && warningType == YakDiseaseWarningRules.WARNING_TYPE_STEPS)
        {
            if (StringUtils.isNotEmpty(measured))
            {
                return "当前运动量" + measured + "，偏离" + (StringUtils.isNotEmpty(reference) ? reference : "常态参考")
                        + "，触发运动量异常预警。";
            }
        }
        if (warningType != null && warningType == YakDiseaseWarningRules.WARNING_TYPE_QUARANTINE)
        {
            return StringUtils.isNotEmpty(presetMessage) ? presetMessage.trim()
                    : "检疫结果异常或阳性集中，触发健康预警。";
        }
        if (warningType != null && warningType == YakDiseaseWarningRules.WARNING_TYPE_DIAGNOSIS)
        {
            return StringUtils.isNotEmpty(presetMessage) ? presetMessage.trim()
                    : "诊疗发病记录集中，触发健康预警。";
        }
        if (StringUtils.isNotEmpty(measured))
        {
            return "监测指标异常：" + measured + "。";
        }
        return "健康监测触发预警，请补充现场观察。";
    }

    private static Date parseDate(String text)
    {
        try
        {
            SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN);
            sdf.setTimeZone(ZONE);
            sdf.setLenient(false);
            return sdf.parse(text);
        }
        catch (ParseException e)
        {
            throw new ServiceException("日期格式应为 yyyy-MM-dd");
        }
    }

    private static Date dayBegin(Date day)
    {
        Calendar cal = Calendar.getInstance(ZONE);
        cal.setTime(day);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    private static Date dayEnd(Date day)
    {
        Calendar cal = Calendar.getInstance(ZONE);
        cal.setTime(day);
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 999);
        return cal.getTime();
    }
}
