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.Row;
import org.apache.poi.ss.usermodel.Sheet;
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.BizVaccinationData;

/**
 * 按年月导出疫苗接种数据（基于导入模板填充；不含合计行）。
 */
@Component
public class VaccinationDataExcelExporter
{
    public static final String TEMPLATE_CLASSPATH = VaccinationDataExcelParser.TEMPLATE_CLASSPATH;

    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<BizVaccinationData> 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<BizVaccinationData> reportList, String fillerName)
    {
        try (ByteArrayOutputStream out = new ByteArrayOutputStream())
        {
            Sheet sheet = VaccinationDataExcelParser.resolveSheet(workbook);
            int headerRowIndex = VaccinationDataExcelParser.detectHeaderRow(sheet);
            if (headerRowIndex < 0)
            {
                throw new ServiceException("未识别到表头行（乡镇/村）");
            }
            updateTitleYearMonth(sheet, statYear, statMonth);
            updateFiller(sheet, fillerName);
            // 官方模板：主表头 + 子表头，数据从 header+HEADER_SPAN 起（Excel 约第 5 行）
            int dataStartRow = headerRowIndex + VaccinationDataExcelParser.HEADER_SPAN;
            // 模板样例行带边框；清空/新建单元格会丢样式，需先捕获再回写
            CellStyle[] dataRowStyles = captureDataRowStyles(sheet, dataStartRow);
            Float dataRowHeight = captureRowHeight(sheet, dataStartRow);
            clearTemplateDataRegion(sheet, dataStartRow);
            int rowIndex = dataStartRow;
            int seq = 1;
            if (reportList != null)
            {
                for (BizVaccinationData report : reportList)
                {
                    if (report == null)
                    {
                        continue;
                    }
                    VaccinationDataDerivedSupport.applyDerived(report);
                    Row row = getOrCreateRow(sheet, rowIndex);
                    clearDataCells(row);
                    setIntegerCell(row, VaccinationDataExcelParser.COL_SEQ, seq++);
                    setStringCell(row, VaccinationDataExcelParser.COL_TOWN, report.getTownName());
                    setStringCell(row, VaccinationDataExcelParser.COL_VILLAGE, report.getVillageName());
                    setIntegerCell(row, VaccinationDataExcelParser.COL_SHOULD, report.getShouldVaccinateCount());
                    setIntegerCell(row, VaccinationDataExcelParser.COL_ACTUAL, report.getActualVaccinateCount());
                    setStringCell(row, VaccinationDataExcelParser.COL_RATE,
                            VaccinationDataDerivedSupport.formatImmunityRatePercent(report.getImmunityRate()));
                    applyDataRowStyles(row, dataRowStyles, dataRowHeight);
                    rowIndex++;
                }
            }
            int lastKeepRow = rowIndex > dataStartRow ? rowIndex - 1 : dataStartRow - 1;
            removeRowsAfter(sheet, lastKeepRow);
            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)
    {
        int lastRow = sheet.getLastRowNum();
        for (int i = fromRow; i <= lastRow; i++)
        {
            Row row = sheet.getRow(i);
            if (row != null)
            {
                clearDataCells(row);
            }
        }
    }

    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);
            }
        }
    }

    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;
                }
                String updated = text;
                Matcher yearMatcher = YEAR_IN_TEXT.matcher(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 CellStyle[] captureDataRowStyles(Sheet sheet, int styleSourceRow)
    {
        CellStyle[] styles = new CellStyle[VaccinationDataExcelParser.COL_RATE + 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 Row getOrCreateRow(Sheet sheet, int rowIndex)
    {
        Row row = sheet.getRow(rowIndex);
        return row != null ? row : sheet.createRow(rowIndex);
    }

    private static void clearDataCells(Row row)
    {
        for (int c = 0; c <= VaccinationDataExcelParser.COL_RATE; c++)
        {
            Cell cell = row.getCell(c);
            if (cell != null)
            {
                cell.setBlank();
            }
        }
    }

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

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