package com.ruoyi.common;

import cn.hutool.core.convert.NumberChineseFormatter;
import com.ruoyi.common.utils.FindUtil;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.web.multipart.MultipartFile;
import technology.tabula.*;
import technology.tabula.extractors.SpreadsheetExtractionAlgorithm;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.util.stream.Collectors;

public class PdfParse2Util {
    public static Map<String, Object> extractPdfContent(MultipartFile multipartFile) throws Exception {
        // 1. 转换MultipartFile为临时File
        File pdfFile = convertMultipartToFile(multipartFile);

        // 2. 执行提取
        try (PDDocument document = PDDocument.load(pdfFile)) {
            Map<String, Object> result = new LinkedHashMap<>();

            // 提取第一页表单数据
            Map<String, String> formData =  extractFormData(document);
            Map<String, String> tableData = new LinkedHashMap<>();
            // 提取第二页表格数据（如果存在）
            if (document.getNumberOfPages() >= 2) {
//                tableData =  extractTableData(document, 2);
                tableData =  extractFormDataTwo(document);
            }


            // 合并
            result.putAll(formData);
            if (tableData.get("animalEartags").length() >5){
                result.putAll(tableData);
            }

            return result;
        } finally {
            // 3. 删除临时文件
            Files.deleteIfExists(pdfFile.toPath());
        }
    }
    private static File convertMultipartToFile(MultipartFile multipartFile) throws IOException {
        File tempFile = Files.createTempFile("pdf-", ".pdf").toFile();
        try (InputStream inputStream = multipartFile.getInputStream()) {
            Files.copy(inputStream, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        }
        return tempFile;
    }

    private static Map<String, String> extractFormDataTwo(PDDocument document) throws Exception {
        PDFTextStripper stripper = new PDFTextStripper();
        stripper.setStartPage(2);
        stripper.setEndPage(2);

        stripper.setSortByPosition(true);
        String fullText = stripper.getText(document);
        System.out.println("全文内容：\n" + fullText);

        Map<String, String> tableMap = new LinkedHashMap<>();

        tableMap.put("animalEartags", expandNumberRangesSafe(fullText.replaceAll("[\\n\\r]","")));
        return tableMap;
    }

    private static String expandNumberRangesSafe(String input) throws Exception {
        if (input == null || input.trim().isEmpty()) {
            return "";
        }
        List<String> allNumbers = new ArrayList<>();
        String[] ranges = input.split(" ");

        for (String range : ranges) {
            if (range.contains("-")) {
                String[] parts = range.split("-");
                if (parts.length == 2) {
                    try {
                        String prefix = parts[0];
                        String endSuffix = parts[1];
                        int suffixLength = endSuffix.length();

                        // 获取基础前缀（去掉最后suffixLength位）
                        String base = prefix.substring(0, prefix.length() - suffixLength);
                        // 获取起始后缀（最后suffixLength位）
                        String startSuffix = prefix.substring(prefix.length() - suffixLength);

                        long start = Long.parseLong(startSuffix);
                        long end = Long.parseLong(endSuffix);
                        // 添加安全检查，防止范围过大
                        if (end - start > 1000) {
                            throw new Exception("耳标号区间范围过大");
                        }
                        // 展开数字范围
                        for (long i = start; i <= end; i++) {
                            // 保持后缀位数一致，不足补零
                            String formattedSuffix = String.format("%0" + suffixLength + "d", i);
                            allNumbers.add(base + formattedSuffix);
                        }
                    } catch (NumberFormatException e) {
                        throw new Exception("无效的数字格式: " + range);
                    }
                }
            }else {
                allNumbers.add(range);
            }
        }

        return String.join(",", allNumbers);
    }
    private static Map<String, String> extractFormData(PDDocument document) throws Exception {
        PDFTextStripper stripper = new PDFTextStripper();
        stripper.setStartPage(1);
        stripper.setEndPage(1);
//        stripper.setSortByPosition(true);
        String text = stripper.getText(document);
        return parseFormText(text);
    }


    private static Map<String, String> parseFormText(String text) throws Exception {
        System.out.println(text);
        Map<String, String> formData = new LinkedHashMap<>();
        text = text.replaceAll("\r\n|\n", "\n"); //windows识别是\r\n分割的，linux识别是\n分割 统一替换兼容使用 \n
        String[] lines = text.split("\n");
        if (lines.length < 11) {
            return formData;//少于这个长度说明PDF解析内容不够
        }

        formData.put("animalCertNo",lines[0].replaceAll("No.", ""));//备用动物检疫证号
        formData.put("cargoOwner",lines[1]);//货主
        formData.put("companyNo",lines[2]);//主体识别号
        formData.put("cargoOwnerPhone",lines[3]);//货主联系方式
        formData.put("animalCategory",lines[4]);//动物种类
        try {
            formData.put("amount", String.valueOf(lines[5].isEmpty() ?0: NumberChineseFormatter.chineseToNumber(lines[5].substring(0,lines[5].length() - 1))));//数量
            formData.put("units", lines[5].isEmpty() ?"":lines[5].substring(lines[5].length() - 1));//单位
        }catch (Exception e){
            throw new Exception("数量及头数解析失败");
        }

        //第二步
        String[] newLines = Arrays.copyOfRange(lines, 6, lines.length);
        if (newLines.length == 0) {
            return formData;
        }
        int index = FindUtil.findFirstPhoneNumberIndex(newLines);//根据第二个手机号码的位置为参照点
        if (index == -1) {
            return formData;
        }

        formData.put("carrierPhone",index>0 ? newLines[index] : "");//承运人联系方式
        formData.put("transportVehicle",newLines[index-1]);//牌号
        formData.put("carrier",index-2>0 ? newLines[index-2] : "");//承运人

        formData.put("useto",index-1>0 ? newLines[index-3] : "");//用途
        StringBuilder animalEartags = new StringBuilder();//备用耳标号
        try {
            for(int i = index+1;i<newLines.length-8;i++) {
                //从第二个手机号码的位置往后读取
//            if(newLines[i] != null && newLines[i].matches("^[0-9]+( [0-9]+)*$")){
//                animalEartags.append(newLines[i]);
//            }
                if(newLines[i] != null && Character.isDigit(newLines[i].charAt(0)) || newLines[i].charAt(0) == '-'){
                    animalEartags.append(newLines[i]);
                }

            }
        }catch (Exception e){
            throw new Exception("耳标号解析失败");
        }

        formData.put("animalEartags", expandNumberRangesSafe(animalEartags.toString().replaceAll("[\\n\\r]",""))  );//备用耳标号,防止没有第二页的情况读不到耳标号，比如头数很少的情况

        //formData.put("remark",newLines.length>index+2?newLines[index+2] : "");//备注  备注经常没有，不容易获取
        //第三步,启运地址和到达地址
        String[] newAddrLines = Arrays.copyOfRange(newLines, 0, index-3);
        if (newAddrLines.length == 0) {
            return formData;
        }
        List<String> addrArr = FindUtil.extractAddresses2(newAddrLines);
        formData.put("fromPlace",addrArr.size()==2 ? addrArr.get(0) : "");//启运地点
        formData.put("toPlace",addrArr.size()==2 ? addrArr.get(1) : "");//到达地点
        return formData;
    }

}
