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

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.industryservice.domain.BizYakOutboundReport;

/**
 * 按年月导出牦牛出栏数据（基于导入模板填充）
 */
@Component
public class YakOutboundReportExcelExporter
{
    public static final String TEMPLATE_CLASSPATH = YakOutboundReportExcelParser.TEMPLATE_CLASSPATH;

    private static final int COL_SEQ = 0;

    private static final Pattern YEAR_IN_TEXT = Pattern.compile("(\\d{4})年");

    private static final Pattern MONTH_IN_PAREN = Pattern.compile("（\\s*\\d+\\s*月\\s*）|\\(\\s*\\d+\\s*月\\s*\\)|（X月）|\\(X月\\)",
            Pattern.CASE_INSENSITIVE);

    public byte[] export(Integer statYear, Integer statMonth, List<BizYakOutboundReport> reportList, String fillerName)
    {
        if (statYear == null)
        {
            throw new ServiceException("导出年份不能为空");
        }
        if (statMonth == null || statMonth < 1 || statMonth > 12)
        {
            throw new ServiceException("导出月份不合法");
        }
        if (!YakHerdInventoryYearSupport.isAllowedYear(statYear))
        {
            throw new ServiceException("导出年份不在可选范围内");
        }
        try (InputStream in = new ClassPathResource(TEMPLATE_CLASSPATH).getInputStream();
                Workbook workbook = WorkbookFactory.create(in))
        {
            return exportWorkbook(workbook, statYear, statMonth, reportList, fillerName);
        }
        catch (ServiceException ex)
        {
            throw ex;
        }
        catch (Exception ex)
        {
            throw new ServiceException("导出 Excel 失败：" + ex.getMessage());
        }
    }

    byte[] exportWorkbook(Workbook workbook, Integer statYear, Integer statMonth,
            List<BizYakOutboundReport> reportList, String fillerName)
    {
        try (ByteArrayOutputStream out = new ByteArrayOutputStream())
        {
            Sheet sheet = YakOutboundReportExcelParser.resolveSheet(workbook);
            int headerRowIndex = YakOutboundReportExcelParser.detectHeaderRow(sheet);
            if (headerRowIndex < 0)
            {
                throw new ServiceException("未识别到表头行（乡镇/村/户数/牦牛）");
            }
            updateTitleYearMonth(sheet, statYear, statMonth);
            updateFiller(sheet, fillerName);
            int dataStartRow = headerRowIndex + 1;
            CellStyle[] dataRowStyles = captureDataRowStyles(sheet, dataStartRow);
            Float dataRowHeight = captureRowHeight(sheet, dataStartRow);
            clearTemplateDataRegion(sheet, dataStartRow);
            Totals totals = new Totals();
            int rowIndex = dataStartRow;
            int seq = 1;
            if (reportList != null)
            {
                for (BizYakOutboundReport report : reportList)
                {
                    if (report == null)
                    {
                        continue;
                    }
                    Row row = getOrCreateRow(sheet, rowIndex);
                    clearDataCells(row);
                    setIntegerCell(row, COL_SEQ, seq++);
                    setStringCell(row, YakOutboundReportExcelParser.COL_TOWN, report.getTownName());
                    fillDataRow(row, report);
                    applyDataRowStyles(row, dataRowStyles, dataRowHeight);
                    if (report.getVillageDeptId() != null || report.getYakOutboundCount() != null
                            || report.getFarmerHouseholdCount() != null)
                    {
                        totals.add(report);
                    }
                    rowIndex++;
                }
            }
            Row totalRow = getOrCreateRow(sheet, rowIndex);
            clearDataCells(totalRow);
            setStringCell(totalRow, COL_SEQ, "合计");
            totals.writeToRow(totalRow);
            applyDataRowStyles(totalRow, dataRowStyles, dataRowHeight);
            mergeTotalLabelCells(sheet, rowIndex);
            removeRowsAfter(sheet, rowIndex);
            workbook.write(out);
            return out.toByteArray();
        }
        catch (ServiceException ex)
        {
            throw ex;
        }
        catch (Exception ex)
        {
            throw new ServiceException("导出 Excel 失败：" + ex.getMessage());
        }
    }

    private static void clearTemplateDataRegion(Sheet sheet, int fromRow)
    {
        // 清除表体区域合并（模板合计行曾合并「序号+乡镇+村」）；合计合并稍后由 mergeTotalLabelCells 重建
        for (int i = sheet.getNumMergedRegions() - 1; i >= 0; i--)
        {
            CellRangeAddress region = sheet.getMergedRegion(i);
            if (region.getFirstRow() >= fromRow)
            {
                sheet.removeMergedRegion(i);
            }
        }
        int lastRow = sheet.getLastRowNum();
        for (int i = fromRow; i <= lastRow; i++)
        {
            Row row = sheet.getRow(i);
            if (row == null)
            {
                continue;
            }
            clearDataCells(row);
            setStringCell(row, YakOutboundReportExcelParser.COL_TOWN, null);
            setStringCell(row, COL_SEQ, null);
        }
    }

    private static void removeRowsAfter(Sheet sheet, int lastKeepRowInclusive)
    {
        for (int i = sheet.getNumMergedRegions() - 1; i >= 0; i--)
        {
            CellRangeAddress region = sheet.getMergedRegion(i);
            if (region.getFirstRow() > lastKeepRowInclusive)
            {
                sheet.removeMergedRegion(i);
            }
        }
        int lastRow = sheet.getLastRowNum();
        for (int r = lastRow; r > lastKeepRowInclusive; r--)
        {
            Row row = sheet.getRow(r);
            if (row != null)
            {
                sheet.removeRow(row);
            }
        }
        if (sheet instanceof org.apache.poi.xssf.usermodel.XSSFSheet)
        {
            org.apache.poi.xssf.usermodel.XSSFSheet xssf = (org.apache.poi.xssf.usermodel.XSSFSheet) sheet;
            String endCol = org.apache.poi.ss.util.CellReference.convertNumToColString(
                    Math.max(YakOutboundReportExcelParser.COL_LAST, 0));
            xssf.getCTWorksheet().getDimension().setRef("A1:" + endCol + (lastKeepRowInclusive + 1));
        }
    }

    static void updateTitleYearMonth(Sheet sheet, int statYear, int statMonth)
    {
        DataFormatter formatter = new DataFormatter();
        int last = Math.min(sheet.getLastRowNum(), 4);
        for (int r = 0; r <= last; r++)
        {
            Row row = sheet.getRow(r);
            if (row == null)
            {
                continue;
            }
            short lastCell = row.getLastCellNum();
            if (lastCell < 0)
            {
                continue;
            }
            for (int c = 0; c < lastCell; c++)
            {
                Cell cell = row.getCell(c);
                if (cell == null)
                {
                    continue;
                }
                String text = formatter.formatCellValue(cell);
                // 跳过填表人/填表时间行，避免把「XXXX年X月」先改成统计年导致填表日期无法落到当月
                if (StringUtils.isEmpty(text) || !text.contains("年") || isFillerMetaText(text))
                {
                    continue;
                }
                Matcher yearMatcher = YEAR_IN_TEXT.matcher(text);
                String updated = text;
                if (yearMatcher.find())
                {
                    updated = yearMatcher.replaceAll(statYear + "年");
                }
                else if (updated.contains("XXXX年"))
                {
                    updated = updated.replace("XXXX年", statYear + "年");
                }
                Matcher monthMatcher = MONTH_IN_PAREN.matcher(updated);
                if (monthMatcher.find())
                {
                    updated = monthMatcher.replaceFirst("（" + statMonth + "月）");
                }
                cell.setCellValue(updated);
            }
        }
    }

    /**
     * 将填表人、填表时间/日期写为当前登录用户与<strong>系统当月</strong>（非导出统计年月）。
     */
    static void updateFiller(Sheet sheet, String fillerName)
    {
        java.time.LocalDate today = java.time.LocalDate.now();
        String fillTime = today.getYear() + "年" + today.getMonthValue() + "月";
        DataFormatter formatter = new DataFormatter();
        int last = Math.min(sheet.getLastRowNum(), 4);
        for (int r = 0; r <= last; r++)
        {
            Row row = sheet.getRow(r);
            if (row == null)
            {
                continue;
            }
            short lastCell = row.getLastCellNum();
            if (lastCell < 0)
            {
                continue;
            }
            for (int c = 0; c < lastCell; c++)
            {
                Cell cell = row.getCell(c);
                if (cell == null)
                {
                    continue;
                }
                String text = formatter.formatCellValue(cell);
                if (StringUtils.isEmpty(text) || !isFillerMetaText(text))
                {
                    continue;
                }
                String updated = text;
                if (StringUtils.isNotEmpty(fillerName))
                {
                    updated = updated.replace("登录用户名称", fillerName);
                }
                // 兼容「填表时间」「填表日期」及占位 XXXX年X月 / 已被误替换的 yyyy年X月
                updated = updated.replaceAll("(填表时间|填表日期)：\\s*XXXX年X月", "$1：" + fillTime);
                updated = updated.replaceAll("(填表时间|填表日期)：\\s*\\d{4}年X月", "$1：" + fillTime);
                updated = updated.replaceAll("(填表时间|填表日期)：\\s*\\d{4}年\\d{1,2}月", "$1：" + fillTime);
                if (updated.contains("XXXX年")
                        && (updated.contains("填表时间") || updated.contains("填表日期")))
                {
                    updated = updated.replaceFirst("XXXX年X?月?", fillTime);
                }
                cell.setCellValue(updated);
            }
        }
    }

    private static boolean isFillerMetaText(String text)
    {
        return text.contains("填表人") || text.contains("填表时间") || text.contains("填表日期");
    }

    private static void mergeTotalLabelCells(Sheet sheet, int rowIndex)
    {
        int firstCol = COL_SEQ;
        int lastCol = YakOutboundReportExcelParser.COL_VILLAGE_NAME;
        for (int i = sheet.getNumMergedRegions() - 1; i >= 0; i--)
        {
            CellRangeAddress region = sheet.getMergedRegion(i);
            if (region.getFirstRow() <= rowIndex && region.getLastRow() >= rowIndex
                    && region.getFirstColumn() <= lastCol && region.getLastColumn() >= firstCol)
            {
                sheet.removeMergedRegion(i);
            }
        }
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, firstCol, lastCol));
        Row row = sheet.getRow(rowIndex);
        if (row == null)
        {
            return;
        }
        Cell cell = row.getCell(firstCol);
        if (cell == null)
        {
            cell = row.createCell(firstCol);
            cell.setCellValue("合计");
        }
        CellStyle style = sheet.getWorkbook().createCellStyle();
        if (cell.getCellStyle() != null)
        {
            style.cloneStyleFrom(cell.getCellStyle());
        }
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        cell.setCellStyle(style);
    }

    private static void clearDataCells(Row row)
    {
        short lastCell = row.getLastCellNum();
        if (lastCell < 0)
        {
            return;
        }
        int maxCol = Math.max(lastCell, YakOutboundReportExcelParser.COL_LAST + 1);
        for (int col = 0; col < maxCol; col++)
        {
            Cell cell = row.getCell(col);
            if (cell == null)
            {
                continue;
            }
            cell.setBlank();
        }
    }

    private static Row getOrCreateRow(Sheet sheet, int rowIndex)
    {
        Row row = sheet.getRow(rowIndex);
        if (row == null)
        {
            row = sheet.createRow(rowIndex);
        }
        return row;
    }

    /** 从模板样例数据行捕获各列样式，供数据行与合计行复用（避免第 3 行起/合计行丢边框） */
    private static CellStyle[] captureDataRowStyles(Sheet sheet, int styleSourceRow)
    {
        CellStyle[] styles = new CellStyle[YakOutboundReportExcelParser.COL_LAST + 1];
        Row src = sheet.getRow(styleSourceRow);
        if (src == null)
        {
            return styles;
        }
        for (int col = 0; col < styles.length; col++)
        {
            Cell cell = src.getCell(col);
            if (cell != null)
            {
                styles[col] = cell.getCellStyle();
            }
        }
        return styles;
    }

    private static Float captureRowHeight(Sheet sheet, int styleSourceRow)
    {
        Row src = sheet.getRow(styleSourceRow);
        if (src == null)
        {
            return null;
        }
        return src.getHeightInPoints();
    }

    private static void applyDataRowStyles(Row row, CellStyle[] styles, Float rowHeight)
    {
        if (row == null || styles == null)
        {
            return;
        }
        if (rowHeight != null && rowHeight > 0)
        {
            row.setHeightInPoints(rowHeight);
        }
        for (int col = 0; col < styles.length; col++)
        {
            CellStyle style = styles[col];
            if (style == null)
            {
                continue;
            }
            Cell cell = row.getCell(col);
            if (cell == null)
            {
                cell = row.createCell(col);
            }
            cell.setCellStyle(style);
        }
    }

    private static void fillDataRow(Row row, BizYakOutboundReport report)
    {
        setStringCell(row, YakOutboundReportExcelParser.COL_VILLAGE_NAME, report.getVillageName());
        setIntegerCell(row, YakOutboundReportExcelParser.COL_FARMER_HOUSEHOLD, report.getFarmerHouseholdCount());
        setIntegerCell(row, YakOutboundReportExcelParser.COL_FARMER_POPULATION, report.getFarmerPopulationCount());
        setIntegerCell(row, YakOutboundReportExcelParser.COL_YAK_OUTBOUND, report.getYakOutboundCount());
        setIntegerCell(row, YakOutboundReportExcelParser.COL_CATTLE_OUTBOUND, report.getCattleOutboundCount());
        setIntegerCell(row, YakOutboundReportExcelParser.COL_SHEEP_OUTBOUND, report.getSheepOutboundCount());
        setIntegerCell(row, YakOutboundReportExcelParser.COL_GOAT_OUTBOUND, report.getGoatOutboundCount());
        setIntegerCell(row, YakOutboundReportExcelParser.COL_HORSE_MULE_OUTBOUND, report.getHorseMuleOutboundCount());
        setIntegerCell(row, YakOutboundReportExcelParser.COL_DONKEY_OUTBOUND, report.getDonkeyOutboundCount());
        setIntegerCell(row, YakOutboundReportExcelParser.COL_SELF_CATTLE, report.getSelfConsumptionCattleCount());
        setIntegerCell(row, YakOutboundReportExcelParser.COL_SELF_SHEEP, report.getSelfConsumptionSheepCount());
        setIntegerCell(row, YakOutboundReportExcelParser.COL_SELF_GOAT, report.getSelfConsumptionGoatCount());
        writeRowSubtotals(row, report);
    }

    private static void writeRowSubtotals(Row row, BizYakOutboundReport report)
    {
        int outboundSubtotal = safe(report.getYakOutboundCount()) + safe(report.getCattleOutboundCount())
                + safe(report.getSheepOutboundCount()) + safe(report.getGoatOutboundCount())
                + safe(report.getHorseMuleOutboundCount()) + safe(report.getDonkeyOutboundCount());
        int selfSubtotal = safe(report.getSelfConsumptionCattleCount()) + safe(report.getSelfConsumptionSheepCount())
                + safe(report.getSelfConsumptionGoatCount());
        setIntegerCell(row, YakOutboundReportExcelParser.COL_OUTBOUND_SUBTOTAL, outboundSubtotal);
        setIntegerCell(row, YakOutboundReportExcelParser.COL_SELF_SUBTOTAL, selfSubtotal);
    }

    private static void setStringCell(Row row, int colIndex, String value)
    {
        Cell cell = row.getCell(colIndex);
        if (cell == null)
        {
            cell = row.createCell(colIndex);
        }
        if (StringUtils.isEmpty(value))
        {
            cell.setBlank();
            return;
        }
        cell.setCellValue(value);
    }

    private static void setIntegerCell(Row row, int colIndex, Integer value)
    {
        if (value == null)
        {
            return;
        }
        Cell cell = row.getCell(colIndex);
        if (cell == null)
        {
            cell = row.createCell(colIndex);
        }
        cell.setCellValue(value.doubleValue());
    }

    private static int safe(Integer value)
    {
        return value == null ? 0 : value;
    }

    private static final class Totals
    {
        private int farmerHouseholdCount;

        private int farmerPopulationCount;

        private int yakOutboundCount;

        private int cattleOutboundCount;

        private int sheepOutboundCount;

        private int goatOutboundCount;

        private int horseMuleOutboundCount;

        private int donkeyOutboundCount;

        private int selfConsumptionCattleCount;

        private int selfConsumptionSheepCount;

        private int selfConsumptionGoatCount;

        void add(BizYakOutboundReport report)
        {
            farmerHouseholdCount += safe(report.getFarmerHouseholdCount());
            farmerPopulationCount += safe(report.getFarmerPopulationCount());
            yakOutboundCount += safe(report.getYakOutboundCount());
            cattleOutboundCount += safe(report.getCattleOutboundCount());
            sheepOutboundCount += safe(report.getSheepOutboundCount());
            goatOutboundCount += safe(report.getGoatOutboundCount());
            horseMuleOutboundCount += safe(report.getHorseMuleOutboundCount());
            donkeyOutboundCount += safe(report.getDonkeyOutboundCount());
            selfConsumptionCattleCount += safe(report.getSelfConsumptionCattleCount());
            selfConsumptionSheepCount += safe(report.getSelfConsumptionSheepCount());
            selfConsumptionGoatCount += safe(report.getSelfConsumptionGoatCount());
        }

        void writeToRow(Row row)
        {
            setIntegerCell(row, YakOutboundReportExcelParser.COL_FARMER_HOUSEHOLD, farmerHouseholdCount);
            setIntegerCell(row, YakOutboundReportExcelParser.COL_FARMER_POPULATION, farmerPopulationCount);
            setIntegerCell(row, YakOutboundReportExcelParser.COL_YAK_OUTBOUND, yakOutboundCount);
            setIntegerCell(row, YakOutboundReportExcelParser.COL_CATTLE_OUTBOUND, cattleOutboundCount);
            setIntegerCell(row, YakOutboundReportExcelParser.COL_SHEEP_OUTBOUND, sheepOutboundCount);
            setIntegerCell(row, YakOutboundReportExcelParser.COL_GOAT_OUTBOUND, goatOutboundCount);
            setIntegerCell(row, YakOutboundReportExcelParser.COL_HORSE_MULE_OUTBOUND, horseMuleOutboundCount);
            setIntegerCell(row, YakOutboundReportExcelParser.COL_DONKEY_OUTBOUND, donkeyOutboundCount);
            setIntegerCell(row, YakOutboundReportExcelParser.COL_SELF_CATTLE, selfConsumptionCattleCount);
            setIntegerCell(row, YakOutboundReportExcelParser.COL_SELF_SHEEP, selfConsumptionSheepCount);
            setIntegerCell(row, YakOutboundReportExcelParser.COL_SELF_GOAT, selfConsumptionGoatCount);
            int outboundSubtotal = yakOutboundCount + cattleOutboundCount + sheepOutboundCount + goatOutboundCount
                    + horseMuleOutboundCount + donkeyOutboundCount;
            int selfSubtotal = selfConsumptionCattleCount + selfConsumptionSheepCount + selfConsumptionGoatCount;
            setIntegerCell(row, YakOutboundReportExcelParser.COL_OUTBOUND_SUBTOTAL, outboundSubtotal);
            setIntegerCell(row, YakOutboundReportExcelParser.COL_SELF_SUBTOTAL, selfSubtotal);
        }
    }
}
