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

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.web.modules.industryservice.domain.BizYakHerdInventory;
import com.ruoyi.web.modules.industryservice.support.YakHerdInventoryExcelParser.ParsedRow;

@DisplayName("YakHerdInventoryExcelExporter")
class YakHerdInventoryExcelExporterTest
{
    private final YakHerdInventoryExcelExporter exporter = new YakHerdInventoryExcelExporter();

    @Test
    @DisplayName("2026样例表无库数据时导出应清空样例存栏数")
    void exportFromSampleWorkbookClearsData() throws Exception
    {
        try (java.io.InputStream sample = getClass().getResourceAsStream("/excel/yak_herd_inventory_2026.xlsx");
                org.apache.poi.ss.usermodel.Workbook sampleWb = org.apache.poi.ss.usermodel.WorkbookFactory.create(sample))
        {
            org.apache.poi.ss.usermodel.Sheet sheet = sampleWb.getSheetAt(0);
            int header = YakHerdInventoryExcelParser.detectHeaderRow(sheet);
            int dataStart = header + 3;
            org.apache.poi.ss.usermodel.DataFormatter fmt = new org.apache.poi.ss.usermodel.DataFormatter();
            org.apache.poi.ss.usermodel.Row firstData = sheet.getRow(dataStart);
            String yakBefore = fmt.formatCellValue(firstData.getCell(YakHerdInventoryExcelParser.COL_YAK_GENDER_TOTAL));
            assertTrue(com.ruoyi.common.utils.StringUtils.isNotEmpty(yakBefore), "样例表首行应有存栏数");

            String[] townNames = {
                "巴青乡", "江绵乡", "岗切乡", "雅安镇", "拉西镇",
                "本塔乡", "杂色镇", "贡日乡", "玛如乡", "阿秀乡"
            };
            java.util.List<SysDept> towns = new java.util.ArrayList<>();
            for (int i = 0; i < townNames.length; i++)
            {
                SysDept d = new SysDept();
                d.setDeptId(100L + i);
                d.setDeptName(townNames[i]);
                d.setOrderNum(13 + i);
                towns.add(d);
            }
            byte[] bytes = exporter.exportWorkbook(sampleWb, 2026, 5, towns, Collections.emptyMap(), null);
            try (org.apache.poi.ss.usermodel.Workbook out = org.apache.poi.ss.usermodel.WorkbookFactory.create(
                    new java.io.ByteArrayInputStream(bytes)))
            {
                java.util.List<ParsedRow> rows = YakHerdInventoryExcelParser.parse(
                        new java.io.ByteArrayInputStream(bytes));
                for (ParsedRow row : rows)
                {
                    assertTrue(row.getYakTotal() == null || row.getYakTotal() == 0,
                            row.getTownName() + " 导出后不应含样例存栏数，实际=" + row.getYakTotal());
                }
            }
        }
    }

    @Test
    @DisplayName("无填报数据时全县乡镇导出均不应含存栏数")
    void exportAllTownsEmptyClearsTemplateSampleData() throws Exception
    {
        String[] townNames = {
            "巴青乡", "江绵乡", "岗切乡", "雅安镇", "拉西镇",
            "本塔乡", "杂色镇", "贡日乡", "玛如乡", "阿秀乡"
        };
        java.util.List<SysDept> towns = new java.util.ArrayList<>();
        for (int i = 0; i < townNames.length; i++)
        {
            SysDept town = new SysDept();
            town.setDeptId(100L + i);
            town.setDeptName(townNames[i]);
            town.setOrderNum(13 + i);
            towns.add(town);
        }

        byte[] bytes = exporter.export(2026, 5, towns, Collections.emptyMap());
        try (java.io.ByteArrayInputStream in = new java.io.ByteArrayInputStream(bytes))
        {
            java.util.List<ParsedRow> rows = YakHerdInventoryExcelParser.parse(in);
            assertEquals(10, rows.size());
            for (ParsedRow row : rows)
            {
                assertTrue(row.getYakTotal() == null || row.getYakTotal() == 0,
                        row.getTownName() + " 不应有存栏数，实际=" + row.getYakTotal());
            }
        }
    }

    @Test
    @DisplayName("按年月导出全县乡镇 Excel")
    void exportByYear() throws Exception
    {
        SysDept town = new SysDept();
        town.setDeptId(101L);
        town.setDeptName("巴青乡");
        town.setOrderNum(13);

        BizYakHerdInventory inv = new BizYakHerdInventory();
        inv.setTownDeptId(101L);
        inv.setTownName("巴青乡");
        inv.setVillageCount(26);
        inv.setHerdsmanHouseholdCount(1605);
        inv.setBreedingBullCount(504);
        inv.setBullCastratedCount(7653);
        inv.setCowYoungCount(2301);
        inv.setCowAdultCount(11129);
        inv.setInsuredYakCount(100);
        inv.setMilkingCowCount(10);
        inv.setFertileCowCount(20);
        inv.setSheepTotal(50);
        YakHerdInventoryValidation.recalculateDerived(inv);

        Map<Long, BizYakHerdInventory> map = new HashMap<>();
        map.put(101L, inv);

        byte[] bytes = exporter.export(2026, 5, Collections.singletonList(town), map);
        assertNotNull(bytes);
        assertTrue(bytes.length > 1000);

        try (java.io.ByteArrayInputStream in = new java.io.ByteArrayInputStream(bytes))
        {
            java.util.List<ParsedRow> rows = YakHerdInventoryExcelParser.parse(in);
            assertTrue(rows.size() >= 1);
            assertTrue(rows.stream().anyMatch(r -> Integer.valueOf(21687).equals(r.getYakTotal())));
            try (org.apache.poi.ss.usermodel.Workbook wb = org.apache.poi.ss.usermodel.WorkbookFactory.create(
                    new java.io.ByteArrayInputStream(bytes)))
            {
                int header = YakHerdInventoryExcelParser.detectHeaderRow(wb.getSheetAt(0));
                org.apache.poi.ss.usermodel.Row dataRow = wb.getSheetAt(0).getRow(header + 3);
                org.apache.poi.ss.usermodel.DataFormatter fmt = new org.apache.poi.ss.usermodel.DataFormatter();
                assertEquals("13430", fmt.formatCellValue(dataRow.getCell(YakHerdInventoryExcelParser.COL_YAK_GENDER_COW)));
                assertEquals("13430", fmt.formatCellValue(dataRow.getCell(YakHerdInventoryExcelParser.COL_COW_SECTION_TOTAL)));
            }
        }
    }
}
