package com.lantone.structure.facade.tran.util;

import com.google.common.collect.Lists;
import com.lantone.common.util.StringUtil;
import com.lantone.structure.util.MapUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description :
 * @Author : HUJING
 * @Date: 2020/9/10 13:48
 */
@Slf4j
public class CommonAnalysisUtil {


    public static void html2StructureMap(List<String> titles, String htmlText, Map<String, String> structureMap) {
        List<String> sortTitles = sortTitles(titles, htmlText);
        cutByTitles(htmlText, sortTitles, 0, structureMap);
    }


    /**
     * 将list中html内容转换成structureMap
     *
     * @param titles       文书各标题
     * @param htmlText     html内容以行的形式存储list
     * @param structureMap
     * @return
     */
    public void html2StructureMap(List<String> titles, List<String> htmlText, Map<String, String> structureMap) {
        StringBuffer sb = new StringBuffer();
        for (String line : htmlText) {
            String text = line.replaceAll("[   ]", " ");
            if (text.length() == 0) {
                continue;
            }
            sb.append(text).append("\n");
        }
        html2StructureMap(titles, sb.toString(), structureMap);
    }

    /**
     * 根据文书各标题截取相应文本，存入structmap中
     *
     * @param line         原始文本
     * @param titles       文书各标题
     * @param depth        递归深度，也就是titles取值时的下标值
     * @param structureMap 存储结构化数据
     */
    public static void cutByTitles(String line, List<String> titles, int depth, Map<String, String> structureMap) {
        if (depth > titles.size() || titles.size() == 0) {
            return;
        }
        String beforeTitle = null, title = null, newTitle = null, value = null;
        beforeTitle = StringUtil.removeBlank(titles.get(Math.max(depth - 1, 0)));
        title = titles.get(Math.min(depth, titles.size() - 1));
        if (depth == titles.size()) {
            /*if (line.contains("\n")) {
                line = line.split("\n")[0];
            }
            */
            value = line.replace("\n", "");
            if (StringUtil.isBlank(structureMap.get(beforeTitle))) {
                structureMap.put(beforeTitle, StringUtil.trim(value));
            }
            return;
        }
        if (line.contains(title + "：") || line.contains(title + ":")) {
            if (line.contains(title + "：")) {
                newTitle = title + "：";
            } else {
                newTitle = title + ":";
            }
            if (depth > 0) {
                value = line.substring(0, line.indexOf(newTitle));
                if (StringUtil.isBlank(structureMap.get(beforeTitle))) {
                    structureMap.put(beforeTitle, StringUtil.trim(value).replace("\n", ""));
                }
            }
            line = line.substring(line.indexOf(newTitle) + newTitle.length());
            depth++;
        } else {
            titles.remove(depth);
        }
        cutByTitles(line, titles, depth, structureMap);
    }

    /**
     * 将title根据在文本中的位置排序
     *
     * @param titles
     * @param content
     * @return
     */
    public static List<String> sortTitles(List<String> titles, String content) {
        Map<Integer, String> titleIndex = new TreeMap<>();
        int index, index_1, index_2;
        for (String title : titles) {
            index_1 = content.indexOf(title + "：");
            index_2 = content.indexOf(title + ":");
            index = Math.max(index_1, index_2);
            if (index != -1) {
                titleIndex.put(index, title);
                StringBuffer sb = new StringBuffer(title.length());
                for (int i = 0; i < title.length(); i++) {
                    sb.append('*');
                }
                content = content.substring(0, index) + sb.toString() + content.substring(index + title.length() + 1);
                //                content = content.substring(0, index) + content.substring(index + title.length() + 1);
            }
        }
        titles = Lists.newArrayList(titleIndex.values());
        return titles;
    }

    /**
     * 标题没有冒号版本
     */
    public static void html2StructureMapNoColon(List<String> titles, String htmlText, Map<String, String> structureMap) {
        List<String> sortTitlesNoColon = sortTitlesNoColon(titles, htmlText);
        cutByTitlesNoColon(htmlText, sortTitlesNoColon, 0, structureMap);
    }

    /**
     * 标题没有冒号版本
     */
    public static void cutByTitlesNoColon(String line, List<String> titles, int depth, Map<String, String> structureMap) {
        if (depth > titles.size() || titles.size() == 0) {
            return;
        }
        String beforeTitle = null, title = null, newTitle = null, value = null;
        beforeTitle = StringUtil.removeBlank(titles.get(Math.max(depth - 1, 0)));
        title = titles.get(Math.min(depth, titles.size() - 1));
        if (depth == titles.size()) {
            value = line;
            value = value.trim();
            if (value.startsWith(":") || value.startsWith("：")) {
                value = value.replaceFirst("[:：]", "");
            }
            if (StringUtil.isBlank(structureMap.get(beforeTitle))) {
                structureMap.put(beforeTitle, StringUtil.trim(value).replace("\n", ""));
            }
            return;
        }
        if (line.contains(title)) {
            newTitle = title;
            if (depth > 0) {
                value = line.substring(0, line.indexOf(newTitle));
                value = value.trim();
                if (value.startsWith(":") || value.startsWith("：")) {
                    value = value.replaceFirst("[:：]", "");
                }
                if (StringUtil.isBlank(structureMap.get(beforeTitle))) {
                    structureMap.put(beforeTitle, StringUtil.trim(value).replace("\n", ""));
                }
            }
            line = line.substring(line.indexOf(newTitle) + newTitle.length());
            depth++;
        } else {
            titles.remove(depth);
        }
        cutByTitlesNoColon(line, titles, depth, structureMap);
    }

    /**
     * 标题没有冒号版本
     */
    public static List<String> sortTitlesNoColon(List<String> titles, String content) {
        Map<Integer, String> titleIndex = new TreeMap<>();
        int index;
        for (String title : titles) {
            index = content.indexOf(title);
            if (index != -1) {
                titleIndex.put(index, title);
                content = content.replace(title, "");
            }
        }
        titles = Lists.newArrayList(titleIndex.values());
        return titles;
    }

    /**
     * 抽取文本中的第一个时间
     *
     * @param top
     * @return
     */
    public static String extractDate(String top) {
        Pattern pattern = Pattern.compile("[0-9]{4}[-][0-9]{1,2}[-][0-9]{1,2}([ ][0-9]{1,2}[:][0-9]{1,2}([:][0-9]{1,2})?)?");
        Matcher matcher = pattern.matcher(top);
        if (matcher.find()) {
            return matcher.group(0);
        } else {
            Pattern p1 = Pattern.compile("[0-9]{4}年[0-9]+月[0-9]+日[0-9]+时[0-9]+分");
            Matcher m1 = p1.matcher(top);
            if (m1.find()) {
                return m1.group(0);
            }
        }
        return null;
    }


    /**
     * 若内容中是包含选择框（会诊类型：     急会诊       普通会诊         请院外会诊），特殊处理
     *
     * @param structureMap
     */
    public static void processType(Map<String, String> structureMap, String title) {
        if (structureMap.containsKey(title)) {
            String type = structureMap.get(title);
            String[] types = type.split(" ");
            for (String t : types) {
                if (t.contains("\uF0FE")) {
                    structureMap.put(title, t.replace("\uF0FE", ""));
                    break;
                }
            }
        }
    }

    /**
     * 若list中其中一个元素包含之后第二个、第三个元素的文本，则把这个元素删除
     *
     * @param htmlList
     */
    public static void removeRepeat(List<String> htmlList) {
        List<Integer> index = Lists.newArrayList();
        if (htmlList.size() < 3) {
            return;
        }
        String str1 = null, str2 = null, str3 = null;
        for (int i = 0; i < htmlList.size() - 2; i++) {
            str1 = htmlList.get(i);
            str2 = htmlList.get(i + 1);
            str3 = htmlList.get(i + 2);
            if (str1.contains(str2) && str1.contains(str3)) {
                index.add(i);
            }
        }

        for (int i = 0; i < index.size(); i++) {
            htmlList.remove(index.get(i) - i);
        }
    }

    public static void makeEmpty(Map<String, String> structureMap, String... key) {
        for (String k : key) {
            if (structureMap.containsKey(k)) {
                structureMap.put(k, "");
            }
        }
    }


    public static void removeKey(Map<String, String> sourceMap, String... args) {
        for (String dateStr : args) {
            if (sourceMap.containsKey(dateStr)) {
                sourceMap.remove(dateStr);
            }
        }
    }

    public static void mapKeyContrastCommon(Map sourceMap, List<String> keyContrasts, Map<String, String> retMap) {
        Map<String, String> sourceMap_ = MapUtil.copyMap(sourceMap);
        String[] arry = null;
        String sourceKey = null, targetKey;
        Set<String> removeKey = new HashSet<>();
        for (String keyContrast : keyContrasts) {
            arry = keyContrast.split("=");
            sourceKey = arry[0];
            if (arry.length == 1) {
                targetKey = arry[0];
            } else {
                targetKey = arry[1];
            }
            if (sourceMap_.get(sourceKey) != null
                    && (!retMap.containsKey(targetKey) || StringUtil.isBlank(retMap.get(targetKey)))) {
                retMap.put(targetKey, sourceMap_.get(sourceKey));
            }
            removeKey.add(sourceKey);
        }
        Set<String> keySet = retMap.keySet();
        for (String key : sourceMap_.keySet()) {
            if (!keySet.contains(key) && !removeKey.contains(key)) { // 如果之前已放过key就不用放了
                retMap.put(key, sourceMap_.get(key));
            }
        }
    }
}
