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

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.io.InputStream;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.ClassPathResource;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.modules.industryservice.support.VaccinationDataExcelParser.ParsedRow;

@DisplayName("VaccinationDataExcelParser")
class VaccinationDataExcelParserTest
{
    @Test
    @DisplayName("识别表头并解析示例村行")
    void parseOfficialTemplate() throws Exception
    {
        try (InputStream in = new ClassPathResource(VaccinationDataExcelParser.TEMPLATE_CLASSPATH).getInputStream())
        {
            List<ParsedRow> rows = VaccinationDataExcelParser.parse(in);
            assertEquals(2, rows.size());
            assertEquals("雅安镇", rows.get(0).getTownName());
            assertEquals("雅安镇荣嘎村", rows.get(0).getVillageName());
            assertEquals(12000, rows.get(0).getShouldVaccinateCount());
            assertEquals(11800, rows.get(0).getActualVaccinateCount());
            assertEquals("雅安镇公随村", rows.get(1).getVillageName());
            assertEquals(13000, rows.get(1).getShouldVaccinateCount());
            assertEquals(12695, rows.get(1).getActualVaccinateCount());
        }
    }

    @Test
    @DisplayName("识别主表头行并跳过子表头")
    void detectHeaderAndSkipSubHeader() throws Exception
    {
        try (InputStream in = new ClassPathResource(VaccinationDataExcelParser.TEMPLATE_CLASSPATH).getInputStream())
        {
            org.apache.poi.ss.usermodel.Workbook wb = org.apache.poi.ss.usermodel.WorkbookFactory.create(in);
            org.apache.poi.ss.usermodel.Sheet sheet = VaccinationDataExcelParser.resolveSheet(wb);
            int header = VaccinationDataExcelParser.detectHeaderRow(sheet);
            assertEquals(2, header);
            wb.close();
        }
    }

    @Test
    @DisplayName("免疫率派生与实免不超过应免硬校验")
    void derivedImmunityRateAndActualConstraint()
    {
        com.ruoyi.web.modules.industryservice.domain.BizVaccinationData row =
                new com.ruoyi.web.modules.industryservice.domain.BizVaccinationData();
        row.setShouldVaccinateCount(12000);
        row.setActualVaccinateCount(11800);
        VaccinationDataDerivedSupport.applyDerived(row);
        assertEquals("98.33", row.getImmunityRate().toPlainString());
        assertEquals("98.33%", VaccinationDataDerivedSupport.formatImmunityRatePercent(row.getImmunityRate()));
        VaccinationDataValidation.validateActualNotExceedShould(row);

        row.setActualVaccinateCount(13000);
        ServiceException ex = assertThrows(ServiceException.class,
                () -> VaccinationDataValidation.validateActualNotExceedShould(row));
        assertEquals("实免数不能大于应免数", ex.getMessage());
    }
}
