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.BizFamilyRanch;

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

    private static final int COL_SEQ = FamilyRanchExcelParser.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<BizFamilyRanch> 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<BizFamilyRanch> reportList,
            String fillerName)
    {
        try (ByteArrayOutputStream out = new ByteArrayOutputStream())
        {
            Sheet sheet = FamilyRanchExcelParser.resolveSheet(workbook);
            int headerRowIndex = FamilyRanchExcelParser.detectHeaderRow(sheet);
            if (headerRowIndex < 0)
            {
                throw new ServiceException("未识别到表头行（乡镇名称/村居名称）");
            }
            updateTitleYearMonth(sheet, statYear, statMonth);
            updateFiller(sheet, fillerName);
            int dataStartRow = headerRowIndex + FamilyRanchExcelParser.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 (BizFamilyRanch 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(FamilyRanchExcelParser.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, FamilyRanchExcelParser.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[FamilyRanchExcelParser.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, BizFamilyRanch report)
    {
        FamilyRanchDerivedSupport.applyDerived(report);
        setStringCell(row, FamilyRanchExcelParser.COL_TOWN, report.getTownName());
        setStringCell(row, FamilyRanchExcelParser.COL_VILLAGE, report.getVillageName());
        setStringCell(row, FamilyRanchExcelParser.COL_ENTERPRISE_NAME, report.getEnterpriseName());
        setStringCell(row, FamilyRanchExcelParser.COL_LEGAL_REP, report.getLegalRepresentative());
        setStringCell(row, FamilyRanchExcelParser.COL_ENTERPRISE_TYPE, report.getEnterpriseType());
        setDecimalCell(row, FamilyRanchExcelParser.COL_REGISTERED_CAPITAL, report.getRegisteredCapital());
        setStringCell(row, FamilyRanchExcelParser.COL_ESTABLISH_DATE, report.getEstablishDate());
        setIntegerCell(row, FamilyRanchExcelParser.COL_LIVESTOCK_LABOR, report.getLivestockLaborCount());
        setIntegerCell(row, FamilyRanchExcelParser.COL_STOCK_SUBTOTAL, report.getStockSubtotal());
        setIntegerCell(row, FamilyRanchExcelParser.COL_CATTLE_YEAR_END, report.getCattleYearEndStock());
        setIntegerCell(row, FamilyRanchExcelParser.COL_CATTLE_BREEDING, report.getCattleBreedingFemaleStock());
        setIntegerCell(row, FamilyRanchExcelParser.COL_SHEEP_YEAR_END, report.getSheepYearEndStock());
        setIntegerCell(row, FamilyRanchExcelParser.COL_SHEEP_BREEDING, report.getSheepBreedingFemaleStock());
        setIntegerCell(row, FamilyRanchExcelParser.COL_CATTLE_OUTBOUND, report.getCattleOutbound());
        setIntegerCell(row, FamilyRanchExcelParser.COL_SHEEP_OUTBOUND, report.getSheepOutbound());
        setDecimalCell(row, FamilyRanchExcelParser.COL_GRASSLAND_SUBTOTAL, report.getGrasslandAreaSubtotal());
        setDecimalCell(row, FamilyRanchExcelParser.COL_GRASS_BALANCE_AREA, report.getGrassBalanceArea());
        setDecimalCell(row, FamilyRanchExcelParser.COL_TRANSFER_GRASS_AREA, report.getTransferGrassArea());
        setDecimalCell(row, FamilyRanchExcelParser.COL_APPROVED_CAPACITY, report.getApprovedCarryingCapacity());
        setDecimalCell(row, FamilyRanchExcelParser.COL_STOCK_SHEEP_UNIT, report.getYearEndStockSheepUnit());
        setStringCell(row, FamilyRanchExcelParser.COL_IS_GRASS_BALANCED, report.getIsGrassBalanced());
        setDecimalCell(row, FamilyRanchExcelParser.COL_INCOME, report.getIncome());
        setDecimalCell(row, FamilyRanchExcelParser.COL_EXPENSE, report.getExpense());
        setDecimalCell(row, FamilyRanchExcelParser.COL_PROFIT, report.getProfit());
        setIntegerCell(row, FamilyRanchExcelParser.COL_SUBSIDY_YEAR, report.getSubsidyYear());
        setStringCell(row, FamilyRanchExcelParser.COL_HAS_SUBSIDY, report.getHasSubsidy());
        setDecimalCell(row, FamilyRanchExcelParser.COL_SUBSIDY_AMOUNT, report.getSubsidyAmount());
        setStringCell(row, FamilyRanchExcelParser.COL_HAS_TRADEMARK, report.getHasTrademark());
        setStringCell(row, FamilyRanchExcelParser.COL_HAS_QUALITY_CERT, report.getHasQualityCert());
        setStringCell(row, FamilyRanchExcelParser.COL_SALES_CHANNEL, report.getSalesChannel());
        setIntegerCell(row, FamilyRanchExcelParser.COL_DRIVEN_POPULATION, report.getDrivenPopulation());
        setDecimalCell(row, FamilyRanchExcelParser.COL_WAGE_PAID, report.getWagePaid());
    }

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