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

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.industryservice.domain.BizVaccinationData;

/**
 * 疫苗接种数据填报校验（手工保存与导入共用）。
 */
public final class VaccinationDataValidation
{
    private VaccinationDataValidation()
    {
    }

    public static void validateRowForSave(BizVaccinationData row, TownDeptSupport townDeptSupport)
    {
        if (row == null)
        {
            throw new ServiceException("参数不能为空");
        }
        YakHerdInventoryMonthSupport.validateStatPeriod(row.getStatYear(), row.getStatMonth());
        if (row.getVillageDeptId() == null)
        {
            throw new ServiceException("所属村不能为空");
        }
        SysDept village = townDeptSupport.requireReportVillage(row.getVillageDeptId());
        if (village == null)
        {
            throw new ServiceException("所属村不合法");
        }
        SysDept town = townDeptSupport.requireReportTown(village.getParentId());
        if (town == null)
        {
            throw new ServiceException("所属村的上级乡镇不合法");
        }
        row.setVillageName(village.getDeptName());
        row.setTownDeptId(town.getDeptId());
        row.setTownName(town.getDeptName());

        validateNonNegative(row.getShouldVaccinateCount(), "应免数");
        validateNonNegative(row.getActualVaccinateCount(), "实免数");
        validateActualNotExceedShould(row);
        if (StringUtils.isNotEmpty(row.getRemark()) && row.getRemark().length() > 500)
        {
            throw new ServiceException("备注不能超过500字");
        }
        VaccinationDataDerivedSupport.applyDerived(row);
    }

    private static void validateNonNegative(Integer value, String label)
    {
        if (value != null && value < 0)
        {
            throw new ServiceException(label + "不能为负数");
        }
    }

    /** 实免数须小于等于应免数（两者均非空时） */
    public static void validateActualNotExceedShould(BizVaccinationData row)
    {
        if (row == null || row.getShouldVaccinateCount() == null || row.getActualVaccinateCount() == null)
        {
            return;
        }
        if (row.getActualVaccinateCount() > row.getShouldVaccinateCount())
        {
            throw new ServiceException("实免数不能大于应免数");
        }
    }
}
