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

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.industryservice.domain.BizLivestockProductOutput;

/**
 * 畜牧产品产量登记 Excel 解析（对齐 livestock_product_output_import_template.xlsx）
 * <p>表头约 1～3 行，数据从「乡镇/村/肉产量」表头行 +1 起；导入跳过合计行。</p>
 */
public final class LivestockProductOutputExcelParser
{
    public static final String TEMPLATE_CLASSPATH = "templates/livestock_product_output_import_template.xlsx";

    static final int COL_SEQ = 0;

    static final int COL_TOWN = 1;

    static final int COL_VILLAGE = 2;

    static final int COL_MEAT = 3;

    static final int COL_MILK = 4;

    static final int COL_LAST = COL_MILK;

    private static final DataFormatter FORMATTER = new DataFormatter();

    private LivestockProductOutputExcelParser()
    {
    }

    public static List<ParsedRow> parse(InputStream inputStream)
    {
        try (Workbook workbook = WorkbookFactory.create(inputStream))
        {
            Sheet sheet = resolveSheet(workbook);
            int headerRowIndex = detectHeaderRow(sheet);
            if (headerRowIndex < 0)
            {
                throw new ServiceException("未识别到表头行（乡镇/村/肉产量）");
            }
            int dataStartRow = headerRowIndex + 1;
            List<ParsedRow> rows = new ArrayList<>();
            for (int i = dataStartRow; i <= sheet.getLastRowNum(); i++)
            {
                Row row = sheet.getRow(i);
                if (row == null)
                {
                    continue;
                }
                String seqText = cellString(row, COL_SEQ);
                String townName = cellString(row, COL_TOWN);
                String villageName = cellString(row, COL_VILLAGE);
                if (StringUtils.isNotEmpty(seqText) && seqText.contains("合计"))
                {
                    break;
                }
                if (StringUtils.isNotEmpty(townName) && townName.contains("合计"))
                {
                    break;
                }
                if (StringUtils.isEmpty(townName) && StringUtils.isEmpty(villageName))
                {
                    continue;
                }
                ParsedRow parsed = new ParsedRow();
                parsed.setExcelRowNum(i + 1);
                parsed.setTownName(townName);
                parsed.setVillageName(villageName);
                parsed.setMeatOutput(cellDecimal(row, COL_MEAT));
                parsed.setMilkOutput(cellDecimal(row, COL_MILK));
                rows.add(parsed);
            }
            return rows;
        }
        catch (ServiceException ex)
        {
            throw ex;
        }
        catch (Exception ex)
        {
            throw new ServiceException("Excel 解析失败：" + ex.getMessage());
        }
    }

    static Sheet resolveSheet(Workbook workbook)
    {
        for (int i = 0; i < workbook.getNumberOfSheets(); i++)
        {
            Sheet sheet = workbook.getSheetAt(i);
            String name = sheet.getSheetName();
            if (name != null && (name.contains("畜牧产品") || name.contains("产量")))
            {
                return sheet;
            }
        }
        return workbook.getSheetAt(0);
    }

    static int detectHeaderRow(Sheet sheet)
    {
        int last = Math.min(sheet.getLastRowNum(), 30);
        for (int i = 0; i <= last; i++)
        {
            Row row = sheet.getRow(i);
            if (row == null)
            {
                continue;
            }
            String townHeader = cellString(row, COL_TOWN);
            String villageHeader = cellString(row, COL_VILLAGE);
            String meatHeader = cellString(row, COL_MEAT);
            if (StringUtils.isNotEmpty(townHeader) && townHeader.contains("乡镇")
                    && StringUtils.isNotEmpty(villageHeader) && villageHeader.contains("村")
                    && StringUtils.isNotEmpty(meatHeader) && meatHeader.contains("肉"))
            {
                return i;
            }
        }
        return -1;
    }

    static String cellString(Row row, int colIndex)
    {
        Cell cell = row.getCell(colIndex);
        if (cell == null)
        {
            return null;
        }
        String text = FORMATTER.formatCellValue(cell);
        return StringUtils.isEmpty(text) ? null : text.trim();
    }

    static BigDecimal cellDecimal(Row row, int colIndex)
    {
        String text = cellString(row, colIndex);
        if (StringUtils.isEmpty(text))
        {
            return null;
        }
        try
        {
            return new BigDecimal(text.replace(",", ""));
        }
        catch (NumberFormatException ex)
        {
            throw new ServiceException("第" + (row.getRowNum() + 1) + "行数字格式错误");
        }
    }

    public static BizLivestockProductOutput toEntity(ParsedRow parsed, Integer statYear, Integer statMonth,
            Long townDeptId, String townName, Long villageDeptId, String villageName)
    {
        BizLivestockProductOutput row = new BizLivestockProductOutput();
        row.setStatYear(statYear);
        row.setStatMonth(statMonth);
        row.setTownDeptId(townDeptId);
        row.setTownName(townName);
        row.setVillageDeptId(villageDeptId);
        row.setVillageName(villageName);
        row.setMeatOutput(parsed.getMeatOutput());
        row.setMilkOutput(parsed.getMilkOutput());
        return row;
    }

    public static class ParsedRow
    {
        private int excelRowNum;

        private String townName;

        private String villageName;

        private BigDecimal meatOutput;

        private BigDecimal milkOutput;

        public int getExcelRowNum()
        {
            return excelRowNum;
        }

        public void setExcelRowNum(int excelRowNum)
        {
            this.excelRowNum = excelRowNum;
        }

        public String getTownName()
        {
            return townName;
        }

        public void setTownName(String townName)
        {
            this.townName = townName;
        }

        public String getVillageName()
        {
            return villageName;
        }

        public void setVillageName(String villageName)
        {
            this.villageName = villageName;
        }

        public BigDecimal getMeatOutput()
        {
            return meatOutput;
        }

        public void setMeatOutput(BigDecimal meatOutput)
        {
            this.meatOutput = meatOutput;
        }

        public BigDecimal getMilkOutput()
        {
            return milkOutput;
        }

        public void setMilkOutput(BigDecimal milkOutput)
        {
            this.milkOutput = milkOutput;
        }
    }
}
