package com.ruoyi.tjfx.util;

import com.ruoyi.tjfx.entity.AnalysisData;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jsoup.Jsoup;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
//import javax.swing.text.Document;
import java.io.*;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.jsoup.nodes.Document;



import java.util.stream.Collectors;




/**
 * Excel工具类
 */
@Slf4j
@Component
public class ExcelUtil {

    /** 检测文件是否为 HTML （简单检查首行） */
    private boolean isHtmlFile(File file) throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String firstLine = reader.readLine();
            return firstLine != null && firstLine.trim().startsWith("<");
        }
    }

    /** 用 Jsoup 解析 HTML 表格 */
    private List<Map<String, Object>> readHtmlTable(File file) throws IOException {
        List<Map<String, Object>> dataList = new ArrayList<>();
        Document doc = Jsoup.parse(file, "UTF-8");
        Element table = doc.selectFirst("table");
        if (table == null) {
            throw new RuntimeException("HTML 中找不到 <table> 元素");
        }

        // 读取表头
        Elements headerCells = table.select("tr").get(0).select("th,td");
        List<String> headers = headerCells.stream()
            .map(Element::text)
            .collect(Collectors.toList());

        // 读取每一行数据
        Elements rows = table.select("tr");
        for (int i = 1; i < rows.size(); i++) {
            Elements cells = rows.get(i).select("td");
            Map<String, Object> rowMap = new HashMap<>();
            for (int j = 0; j < headers.size() && j < cells.size(); j++) {
                rowMap.put(headers.get(j), cells.get(j).text());
            }
            dataList.add(rowMap);
        }
        return dataList;
    }

    /** 根据 Cell 类型取值的通用方法 */
    private Object getCellValue2(Cell cell) {
        if (cell == null) return null;
        switch (cell.getCellType()) {
            case STRING:  return cell.getStringCellValue();
            case NUMERIC: return DateUtil.isCellDateFormatted(cell)
                ? cell.getDateCellValue()
                : cell.getNumericCellValue();
            case BOOLEAN: return cell.getBooleanCellValue();
            case FORMULA: return cell.getCellFormula();
            case BLANK:   return "";
            default:      return cell.toString();
        }
    }


    /**
     * 读取Excel文件
     */
    public List<Map<String, Object>> readExcel(String filePath) {
        File file = new File(filePath);
        List<Map<String, Object>> dataList = new ArrayList<>();

        try {
            // 1. 检测是否为 HTML 文件（第一行以 '<' 开头）
            if (isHtmlFile(file)) {
                return readHtmlTable(file);
            }

            // 2. 如果不是 HTML，就用 POI 自动识别 xls/xlsx
            try (FileInputStream fis = new FileInputStream(file);
                 Workbook workbook = WorkbookFactory.create(fis)) {

                Sheet sheet = workbook.getSheetAt(0);
                Row headerRow = sheet.getRow(0);
                if (headerRow == null) {
                    return dataList;
                }

                // 3. 读取表头
                List<String> headers = new ArrayList<>();
                for (int i = 0; i < headerRow.getLastCellNum(); i++) {
                    Cell cell = headerRow.getCell(i);
                    headers.add(cell != null ? cell.toString() : "");
                }

                // 4. 读取数据行
                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);
                    if (row == null) continue;

                    Map<String, Object> rowData = new HashMap<>();
                    for (int j = 0; j < headers.size(); j++) {
                        Cell cell = row.getCell(j);
                        rowData.put(headers.get(j), getCellValue2(cell));
                    }
                    dataList.add(rowData);
                }
            }

        } catch (Exception e) {
            log.error("读取Excel文件失败: {}", filePath, e);
            throw new RuntimeException("读取Excel失败：" + e.getMessage());
        }

        return dataList;
    }

/*    public List<Map<String, Object>> readExcel(String filePath) {
        List<Map<String, Object>> dataList = new ArrayList<>();

        try (FileInputStream fis = new FileInputStream(filePath);
             Workbook workbook = WorkbookFactory.create(fis)) {  // 自动识别xls或xlsx

            Sheet sheet = workbook.getSheetAt(0);
            Row headerRow = sheet.getRow(0);

            if (headerRow == null) {
                return dataList;
            }

            List<String> headers = new ArrayList<>();
            for (int i = 0; i < headerRow.getLastCellNum(); i++) {
                Cell cell = headerRow.getCell(i);
                headers.add(cell != null ? cell.toString() : "");
            }

            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;

                Map<String, Object> rowData = new HashMap<>();
                for (int j = 0; j < headers.size(); j++) {
                    Cell cell = row.getCell(j);
                    String header = headers.get(j);
                    Object value = getCellValue(cell);
                    rowData.put(header, value);
                }
                dataList.add(rowData);
            }

        } catch (Exception e) {
            log.error("读取Excel文件失败: {}", filePath, e);
        }

        return dataList;
    }*/

    /**
     * 读取FBA Excel文件
     */
    public List<Map<String, Object>> readFbaExcel(String filePath) {
        return readExcel(filePath); // 使用相同的读取方法
    }

    /**
     * 导出分析数据到Excel
     */
    public void exportAnalysisData(HttpServletResponse response, Map<String, List<AnalysisData>> groupedData) {
        try (Workbook workbook = new XSSFWorkbook()) {

            for (Map.Entry<String, List<AnalysisData>> entry : groupedData.entrySet()) {
                String categoryName = entry.getKey();
                List<AnalysisData> dataList = entry.getValue();

                // 清理工作表名称中的非法字符
                String safeSheetName = categoryName.replaceAll("[\\\\/*?:\"<>|]", "_").substring(0, Math.min(31, categoryName.length()));

                Sheet sheet = workbook.createSheet(safeSheetName);

                // 创建表头
                Row headerRow = sheet.createRow(0);
                String[] headers = {
                    "日期", "店铺", "商品编号", "商品名称", "客户", "品牌", "数量", "合计",
                    "来源", "状态", "出库类型", "目的地", "备注", "订单编号", "行号"
                };

                for (int i = 0; i < headers.length; i++) {
                    Cell cell = headerRow.createCell(i);
                    cell.setCellValue(headers[i]);
                }

                // 填充数据
                for (int i = 0; i < dataList.size(); i++) {
                    AnalysisData data = dataList.get(i);
                    Row row = sheet.createRow(i + 1);

                    row.createCell(0).setCellValue(data.getDate().toString());
                    row.createCell(1).setCellValue(data.getShopName());
                    row.createCell(2).setCellValue(data.getProductCode());
                    row.createCell(3).setCellValue(data.getProductName());
                    row.createCell(4).setCellValue(data.getCustomerName());
                    row.createCell(5).setCellValue(data.getBrand());
                    row.createCell(6).setCellValue(data.getQuantity());
                    row.createCell(7).setCellValue(data.getTotalAmount().doubleValue());
                    row.createCell(8).setCellValue(data.getSource());
                    row.createCell(9).setCellValue(getStatusText(data.getStatus()));
                    row.createCell(10).setCellValue(data.getDeliveryType());
                    row.createCell(11).setCellValue(data.getDestination());
                    row.createCell(12).setCellValue(data.getRemarks());
                    row.createCell(13).setCellValue(data.getOrderNumber());
                    row.createCell(14).setCellValue(data.getRowNumber());
                }

                // 自动调整列宽
                for (int i = 0; i < headers.length; i++) {
                    sheet.autoSizeColumn(i);
                }
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=sales_analysis_data.xlsx");

            // 写入响应流
            workbook.write(response.getOutputStream());

        } catch (IOException e) {
            log.error("导出Excel失败", e);
            throw new RuntimeException("导出Excel失败");
        }
    }

    /**
     * 处理Excel日期
     */
    public LocalDate processExcelDate(Object dateValue) {
        if (dateValue == null) {
            return null;
        }

        try {
            if (dateValue instanceof Date) {
                return ((Date) dateValue).toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDate();
            } else if (dateValue instanceof String) {
                String dateStr = (String) dateValue;
                // 尝试多种日期格式
                String[] formats = {"yyyy-MM-dd", "yyyy/MM/dd", "yyyy.MM.dd","yyyy/M/d", "yyyy年MM月dd日"};
                for (String format : formats) {
                    try {
                        return LocalDate.parse(dateStr, DateTimeFormatter.ofPattern(format));
                    } catch (Exception ignored) {
                        // 继续尝试下一个格式
                    }
                }
            } else if (dateValue instanceof Number) {
                // Excel日期数字格式
                double excelDate = ((Number) dateValue).doubleValue();
                return DateUtil.getJavaDate(excelDate).toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDate();
            }
        } catch (Exception e) {
            log.error("日期处理失败: {}", dateValue, e);
        }

        return null;
    }

    /**
     * 处理FBA日期
     */
    public LocalDate processFbaDate(Object dateValue) {
        if (dateValue == null) {
            return null;
        }

        try {
            if (dateValue instanceof String) {
                String dateStr = (String) dateValue;
                // 处理ISO格式日期
                if (dateStr.contains("T")) {
                    return LocalDate.parse(dateStr.substring(0, 10));
                }
            }

            // 使用通用的Excel日期处理
            return processExcelDate(dateValue);

        } catch (Exception e) {
            log.error("FBA日期处理失败: {}", dateValue, e);
        }

        return null;
    }

    /**
     * 处理FBA SKU
     */
    public String processFbaSku(String sku) {
        if (sku == null || sku.trim().isEmpty()) {
            return "";
        }

        String trimmedSku = sku.trim();

        // 具体的后缀模式
        String[] specificSuffixes = {"-F", "-SLP", "-SF", "-F1", "-2K", "-5F", "-D", "-E"};

        // 首先尝试匹配具体的后缀
        for (String suffix : specificSuffixes) {
            if (trimmedSku.endsWith(suffix)) {
                return trimmedSku.substring(0, trimmedSku.length() - suffix.length());
            }
        }

        // 如果没有匹配到具体后缀，尝试通用模式
        String result = trimmedSku.replaceAll("^(.+?)[-_][A-Z]{1,4}$", "$1");
        return result.equals(trimmedSku) ? trimmedSku : result;
    }

    /**
     * 获取单元格值
     */
    private Object getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue();
                } else {
                    return cell.getNumericCellValue();
                }
            case BOOLEAN:
                return cell.getBooleanCellValue();
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }

    /**
     * 获取状态文本
     */
    private String getStatusText(Integer status) {
        if (status == null) return "";
        switch (status) {
            case 1: return "正常";
            case 2: return "客户名称未匹配";
            case 3: return "分类规格未匹配";
            default: return "未知";
        }
    }
}
