package com.lantone.qc.trans.comsis;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lantone.qc.pub.util.ListUtil;
import com.lantone.qc.pub.util.StringUtil;

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;

import static java.util.Map.Entry.comparingByValue;
import static java.util.stream.Collectors.toMap;

/**
 * 字符串切map工具
 *
 * @Description:
 * @author: rengb
 * @time: 2020/3/5 15:56
 */
public class Preproc {

    /**
     * 将需处理字符串根据key集合，切成map，分病程模块处理和非病程模块处理
     *
     * @param isProgress 是否病程模块
     * @param title      key集合
     * @param line       需处理字符串
     * @return
     */
    public static Map<String, String> extract_doc_pub(boolean isProgress, List<String> title, String line) {
        //        line = line.replaceAll("[　*| *| *]*", "");
        int pos = 0;
        int ln_pos = 0;
        String item = "";
        String newline = "\n";
        String tab = "\t";
        int pos_newln, pos_tab;
        Map<String, String> sections = new HashMap<>();
        Map<String, Integer> sorted = new HashMap<>();

        for (String key : title) {
            Pattern pattern = Pattern.compile(key);
            Matcher matcher = pattern.matcher(line);
            while (matcher.find()) {
                key = matcher.group(0);
            }

            pos = 0;
            while (line.indexOf(key, pos) >= 0 && null == sorted.get(key)) {
                pos = line.indexOf(key, pos);

                if (isProgress) {
                    pos += key.length();
                    if (null == sorted.get(key)) {
                        sorted.put(key, pos);
                    }
                } else {
                    pos_newln = line.substring(0, pos).lastIndexOf(newline);
                    pos_tab = line.substring(0, pos).lastIndexOf(tab);
                    ln_pos = (pos_newln < pos_tab) ? pos_tab : pos_newln;

                    if (ln_pos == -1 || line.substring(ln_pos + tab.length(), pos).trim().length() == 0) {
                        pos += key.length();
                        sorted.put(key, pos);
                    } else {
                        pos += 1;
                    }
                }
            }
        }

        sorted = sorted
                .entrySet()
                .stream()
                .sorted(comparingByValue())
                .collect(
                        toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
                                LinkedHashMap::new));

        String lbl = "";
        for (String key : sorted.keySet()) {
            if (lbl.length() > 0 && pos <= sorted.get(key) - key.length()) {
                item = line.substring(pos, sorted.get(key) - key.length());
                if (item.indexOf(":") == 0 || item.indexOf("：") == 0) {
                    item = item.substring(1);
                }

                sections.put(lbl, item);
            }
            lbl = key;
            pos = sorted.get(key);
        }

        item = line.substring(pos);
        if (item.indexOf(":") == 0 || item.indexOf("：") == 0) {
            item = item.substring(1);
        }
        sections.put(lbl, item);

        Map<String, String> sectionsNew = Maps.newHashMap();
        sections.keySet().forEach(key -> {
            if (StringUtil.isNotBlank(key)) {
                sectionsNew.put(key.replaceAll("[\\s\\p{Zs}]", ""), sections.get(key));
            }
        });

        return sectionsNew;
    }

    /**
     * key特殊处理然后切词，除了首次病程，其他模块可用
     *
     * @param isProgress
     * @param content
     * @param sourceTitles
     * @return
     */
    public static Map<String, String> getCutWordMap(boolean isProgress, List<String> sourceTitles, String content) {
        if (StringUtil.isBlank(content)) {
            return Maps.newHashMap();
        }
        List<String> targetTitles = Lists.newArrayList();
        sourceTitles.forEach(sourceTitle -> {
            String targetTitle = "";
            for (int index = 0; index < sourceTitle.length(); index++) {
                if (index == sourceTitle.length() - 1) {
                    targetTitle += sourceTitle.substring(index, index + 1);
                } else {
                    targetTitle += sourceTitle.substring(index, index + 1) + "[\\s\\p{Zs}]*";
                }
            }
            targetTitles.add(targetTitle);
        });
        if (ListUtil.isEmpty(targetTitles)) {
            return Maps.newHashMap();
        }
        return extract_doc_pub(isProgress, targetTitles, content);
    }

}