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

/**
 * 按年月导出有无畜户数据（基于导入模板填充）。
 */
@Component
public class LivestockOwnershipHouseholdExcelExporter
{
    public static final String TEMPLATE_CLASSPATH = LivestockOwnershipHouseholdExcelParser.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<BizLivestockOwnershipHousehold> 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<BizLivestockOwnershipHousehold> reportList, String fillerName)
    {
        try (ByteArrayOutputStream out = new ByteArrayOutputStream())
        {
            Sheet sheet = LivestockOwnershipHouseholdExcelParser.resolveSheet(workbook);
            int headerRowIndex = LivestockOwnershipHouseholdExcelParser.detectHeaderRow(sheet);
            if (headerRowIndex < 0)
            {
                throw new ServiceException("未识别到表头行（乡镇/村居/有畜户）");
            }
            updateTitleYearMonth(sheet, statYear, statMonth);
            updateFiller(sheet, fillerName);
            int dataStartRow = headerRowIndex + 2;
            clearTemplateDataRegion(sheet, dataStartRow);
            Totals totals = new Totals();
            int rowIndex = dataStartRow;
            int seq = 1;
            if (reportList != null)
            {
                for (BizLivestockOwnershipHousehold report : reportList)
                {
                    if (report == null)
                    {
                        continue;
                    }
                    Row row = getOrCreateRow(sheet, rowIndex);
                    clearDataCells(row);
                    setIntegerCell(row, LivestockOwnershipHouseholdExcelParser.COL_SEQ, seq++);
                    setStringCell(row, LivestockOwnershipHouseholdExcelParser.COL_TOWN, report.getTownName());
                    fillDataRow(row, report);
                    totals.add(report);
                    rowIndex++;
                }
            }
            Row totalRow = getOrCreateRow(sheet, rowIndex);
            clearDataCells(totalRow);
            setStringCell(totalRow, LivestockOwnershipHouseholdExcelParser.COL_SEQ, "合计");
            mergeTotalLabelCells(sheet, rowIndex);
            totals.writeToRow(totalRow);
            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)
    {
        int lastRow = sheet.getLastRowNum();
        for (int i = fromRow; i <= lastRow; i++)
        {
            Row row = sheet.getRow(i);
            if (row == null)
            {
                continue;
            }
            clearDataCells(row);
            setStringCell(row, LivestockOwnershipHouseholdExcelParser.COL_TOWN, null);
            setStringCell(row, LivestockOwnershipHouseholdExcelParser.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(LivestockOwnershipHouseholdExcelParser.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);
                if (StringUtils.isEmpty(text) || !text.contains("年"))
                {
                    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);
            }
        }
    }

    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) || (!text.contains("填表人") && !text.contains("填表时间")))
                {
                    continue;
                }
                String updated = text;
                if (StringUtils.isNotEmpty(fillerName))
                {
                    updated = updated.replace("登录用户名称", fillerName);
                }
                updated = updated.replaceAll("填表时间：\\s*XXXX年X月", "填表时间：" + fillTime);
                updated = updated.replaceAll("填表时间：\\s*\\d{4}年\\d{1,2}月", "填表时间：" + fillTime);
                if (updated.contains("XXXX年") && updated.contains("填表时间"))
                {
                    updated = updated.replaceFirst("XXXX年X?月?", fillTime);
                }
                cell.setCellValue(updated);
            }
        }
    }

    private static void mergeTotalLabelCells(Sheet sheet, int rowIndex)
    {
        int firstCol = LivestockOwnershipHouseholdExcelParser.COL_SEQ;
        int lastCol = LivestockOwnershipHouseholdExcelParser.COL_VILLAGE;
        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, LivestockOwnershipHouseholdExcelParser.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;
    }

    private static void fillDataRow(Row row, BizLivestockOwnershipHousehold report)
    {
        setStringCell(row, LivestockOwnershipHouseholdExcelParser.COL_VILLAGE, report.getVillageName());
        setIntegerCell(row, LivestockOwnershipHouseholdExcelParser.COL_WITH_HOUSEHOLD,
                report.getWithLivestockHouseholdCount());
        setIntegerCell(row, LivestockOwnershipHouseholdExcelParser.COL_WITH_POPULATION,
                report.getWithLivestockPopulationCount());
        setIntegerCell(row, LivestockOwnershipHouseholdExcelParser.COL_WITH_LABOR,
                report.getWithLivestockLaborCount());
        setIntegerCell(row, LivestockOwnershipHouseholdExcelParser.COL_WITH_ANIMAL,
                report.getWithLivestockAnimalCount());
        setIntegerCell(row, LivestockOwnershipHouseholdExcelParser.COL_WITHOUT_HOUSEHOLD,
                report.getWithoutLivestockHouseholdCount());
        setIntegerCell(row, LivestockOwnershipHouseholdExcelParser.COL_WITHOUT_POPULATION,
                report.getWithoutLivestockPopulationCount());
        setIntegerCell(row, LivestockOwnershipHouseholdExcelParser.COL_WITHOUT_LABOR,
                report.getWithoutLivestockLaborCount());
    }

    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 withHousehold;

        private int withPopulation;

        private int withLabor;

        private int withAnimal;

        private int withoutHousehold;

        private int withoutPopulation;

        private int withoutLabor;

        void add(BizLivestockOwnershipHousehold report)
        {
            withHousehold += safe(report.getWithLivestockHouseholdCount());
            withPopulation += safe(report.getWithLivestockPopulationCount());
            withLabor += safe(report.getWithLivestockLaborCount());
            withAnimal += safe(report.getWithLivestockAnimalCount());
            withoutHousehold += safe(report.getWithoutLivestockHouseholdCount());
            withoutPopulation += safe(report.getWithoutLivestockPopulationCount());
            withoutLabor += safe(report.getWithoutLivestockLaborCount());
        }

        void writeToRow(Row row)
        {
            setIntegerCell(row, LivestockOwnershipHouseholdExcelParser.COL_WITH_HOUSEHOLD, withHousehold);
            setIntegerCell(row, LivestockOwnershipHouseholdExcelParser.COL_WITH_POPULATION, withPopulation);
            setIntegerCell(row, LivestockOwnershipHouseholdExcelParser.COL_WITH_LABOR, withLabor);
            setIntegerCell(row, LivestockOwnershipHouseholdExcelParser.COL_WITH_ANIMAL, withAnimal);
            setIntegerCell(row, LivestockOwnershipHouseholdExcelParser.COL_WITHOUT_HOUSEHOLD, withoutHousehold);
            setIntegerCell(row, LivestockOwnershipHouseholdExcelParser.COL_WITHOUT_POPULATION, withoutPopulation);
            setIntegerCell(row, LivestockOwnershipHouseholdExcelParser.COL_WITHOUT_LABOR, withoutLabor);
        }
    }
}
