package org.jeecg.modules.stm.baosong.controller;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.jeecg.modules.stm.baosong.entity.BaosongTplItem;

import java.io.File;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ImportTplItemDes {
    String filePath = "";
    public ImportTplItemDes(String filePath) {
        this.filePath = filePath;
    }

    public Map<Integer, String> getTplItemDesMap(List<BaosongTplItem> itemList) {
        Map<Integer, String> idToFieldMap = new HashMap<>();
        Map<Integer, String> retMap = new HashMap<>();
        for(BaosongTplItem item:itemList) {
            idToFieldMap.put(item.getId(),item.getTitle());
        }

        try (PDDocument document = PDDocument.load(new File(this.filePath))) {
            PDFTextStripper stripper = new PDFTextStripper();
            String pdfText = stripper.getText(document);
            Map<String, String> contentDesMap = parseContent(pdfText) ;

            for (Map.Entry<Integer, String> entry : idToFieldMap.entrySet()) {
                Integer fieldId = entry.getKey();
                String keyword = entry.getValue();
                if(contentDesMap.get(keyword)==null) {
                    continue;
                }
                retMap.put(fieldId,contentDesMap.get(keyword));
            }


        } catch (Exception e) {
            System.err.println("解析PDF文件出错: " + e.getMessage());
        }
        return  retMap;
    }

    private  Map<String, String> parseContent(String content) {
        Map<String, String> map = new LinkedHashMap<>();

        // Pattern to match 【key】value pairs
        Pattern pattern = Pattern.compile("【([^】]+)】([^【]*)");
        Matcher matcher = pattern.matcher(content);

        while (matcher.find()) {
            String key = matcher.group(1).trim();
            String value = matcher.group(2).trim();

            // Skip empty values
            if (!value.isEmpty()) {
                map.put(key, value);
            }
        }

        return map;
    }

}
