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

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
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.BizFarmerHousehold;

/**
 * 按年月导出农牧户数据（基于导入模板填充；不含合计行）
 */
@Component
public class FarmerHouseholdExcelExporter
{
    public static final String TEMPLATE_CLASSPATH = FarmerHouseholdExcelParser.TEMPLATE_CLASSPATH;

    private static final int COL_SEQ = FarmerHouseholdExcelParser.COL_SEQ;

    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<BizFarmerHousehold> 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<BizFarmerHousehold> reportList,
            String fillerName)
    {
        try (ByteArrayOutputStream out = new ByteArrayOutputStream())
        {
            Sheet sheet = FarmerHouseholdExcelParser.resolveSheet(workbook);
            int headerRowIndex = FarmerHouseholdExcelParser.detectHeaderRow(sheet);
            if (headerRowIndex < 0)
            {
                throw new ServiceException("未识别到表头行（乡镇名称/村）");
            }
            updateTitleYearMonth(sheet, statYear, statMonth);
            updateFiller(sheet, fillerName);
            int dataStartRow = headerRowIndex + FarmerHouseholdExcelParser.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 (BizFarmerHousehold report : reportList)
                {
                    if (report == null)
                    {
                        continue;
                    }
                    Row row = getOrCreateRow(sheet, rowIndex);
                    clearDataCells(row);
                    setIntegerCell(row, COL_SEQ, seq++);
                    fillDataRow(row, report);
                    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)
            {
                continue;
            }
            clearDataCells(row);
            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(FarmerHouseholdExcelParser.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 clearDataCells(Row row)
    {
        short lastCell = row.getLastCellNum();
        if (lastCell < 0)
        {
            return;
        }
        int maxCol = Math.max(lastCell, FarmerHouseholdExcelParser.COL_LAST + 1);
        for (int col = 0; col < maxCol; col++)
        {
            Cell cell = row.getCell(col);
            if (cell == null)
            {
                continue;
            }
            cell.setBlank();
        }
    }

    private static CellStyle[] captureDataRowStyles(Sheet sheet, int styleSourceRow)
    {
        CellStyle[] styles = new CellStyle[FarmerHouseholdExcelParser.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 Row getOrCreateRow(Sheet sheet, int rowIndex)
    {
        Row row = sheet.getRow(rowIndex);
        if (row == null)
        {
            row = sheet.createRow(rowIndex);
        }
        return row;
    }

    private static void fillDataRow(Row row, BizFarmerHousehold report)
    {
        FarmerHouseholdDerivedSupport.applyDerived(report);
        setStringCell(row, FarmerHouseholdExcelParser.COL_TOWN, report.getTownName());
        setStringCell(row, FarmerHouseholdExcelParser.COL_VILLAGE, report.getVillageName());
        setIntegerCell(row, FarmerHouseholdExcelParser.COL_HOUSEHOLD, report.getHouseholdCount());
        setIntegerCell(row, FarmerHouseholdExcelParser.COL_POPULATION, report.getPopulationCount());
        setDecimalCell(row, FarmerHouseholdExcelParser.COL_PASTURE_TOTAL, report.getPastureContractArea());
        setDecimalCell(row, FarmerHouseholdExcelParser.COL_GRAZING_BAN_AREA, report.getGrazingBanArea());
        setDecimalCell(row, FarmerHouseholdExcelParser.COL_GRASS_BALANCE_AREA, report.getGrassBalanceArea());
        setDecimalCell(row, FarmerHouseholdExcelParser.COL_APPROVED_CAPACITY, report.getApprovedCarryingCapacity());
        setDecimalCell(row, FarmerHouseholdExcelParser.COL_YEAR_END_STOCK, report.getYearEndStockSheepUnit());
        setStringCell(row, FarmerHouseholdExcelParser.COL_IS_PURE_HERDER, report.getIsPureHerder());
        setStringCell(row, FarmerHouseholdExcelParser.COL_IS_NO_LIVESTOCK, report.getIsNoLivestock());
        setStringCell(row, FarmerHouseholdExcelParser.COL_IS_EXTINCT, report.getIsExtinctHousehold());
        setStringCell(row, FarmerHouseholdExcelParser.COL_IS_OVERLOAD, report.getIsOverloadHerder());
        setStringCell(row, FarmerHouseholdExcelParser.COL_NEED_CAP, report.getNeedCap());
        setStringCell(row, FarmerHouseholdExcelParser.COL_NEED_FLOOR, report.getNeedFloor());
        setDecimalCell(row, FarmerHouseholdExcelParser.COL_GRAZING_BAN_SUBSIDY, report.getGrazingBanSubsidy());
        setDecimalCell(row, FarmerHouseholdExcelParser.COL_GRASS_BALANCE_REWARD, report.getGrassBalanceReward());
        setDecimalCell(row, FarmerHouseholdExcelParser.COL_SUBSIDY_SUBTOTAL, report.getSubsidyRewardSubtotal());
        setDecimalCell(row, FarmerHouseholdExcelParser.COL_AFTER_CAP_FLOOR, report.getAfterCapFloorSubsidy());
        setDecimalCell(row, FarmerHouseholdExcelParser.COL_VILLAGE_SUPERVISOR, report.getVillageSupervisorSubsidy());
        setDecimalCell(row, FarmerHouseholdExcelParser.COL_SUBSIDY_TOTAL, report.getSubsidyTotal());
    }

    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 void setDecimalCell(Row row, int colIndex, BigDecimal value)
    {
        if (value == null)
        {
            return;
        }
        Cell cell = row.getCell(colIndex);
        if (cell == null)
        {
            cell = row.createCell(colIndex);
        }
        cell.setCellValue(value.doubleValue());
    }
}
