package com.lantone.qc.trans.beilun.util.ez;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lantone.qc.pub.util.StringUtil;
import com.lantone.qc.trans.comsis.CommonAnalysisUtil;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description:
 * @author: rengb
 * @time: 2020/9/24 11:28
 */
public class EzXmlAnalysis {

    public static Map<String, String> analysis(String deptName, String xml) throws Exception {
        if (deptName.equals("小儿外科")) {
            return analysisEk(deptName, xml);
        }
        return null;
    }

    public static Map<String, String> analysisEk(String deptName, String xml) throws Exception {
        Map<String, String> map = Maps.newLinkedHashMap();
        Document doc = DocumentHelper.parseText(xml);
        Element rootElement = doc.getRootElement();
        jbxxInsertMap(rootElement, map);
        tgjcInsertMap(rootElement, map);
        fzjcInsertMap(rootElement, map);
        zkjcInsertMap(rootElement, map);
        disInsertMap(rootElement, map);
        otherInsertMap(rootElement, map);
        return map;
    }

    //其他信息
    public static void otherInsertMap(Element rootElement, Map<String, String> map) {
        List<String> titles = Lists.newArrayList(
                "主诉", "现病史", "既往史", "手术史", "输血史", "过敏史", "个人史", "预防接种史", "家族史", "婚育史", "月经史"
        );
        String rootText = elementTxt(rootElement);
        String signTimeStr = findTimeStr(rootText.substring(rootText.length() - 18));
        if (StringUtil.isNotBlank(signTimeStr)) {
            rootText = rootText.substring(0, rootText.lastIndexOf(signTimeStr));
        }
        titles = CommonAnalysisUtil.sortTitlesNoColon(titles, rootText);
        CommonAnalysisUtil.cutByTitlesNoColon(rootText, titles, 0, map);
    }

    public static void disInsertMap(Element rootElement, Map<String, String> map) {
        Node cbzdNode = rootElement.selectSingleNode("section[@name='初步诊断']");
        if (cbzdNode != null) {
            rootElement.remove(cbzdNode);
        }
        Node disNode = rootElement.selectSingleNode("section[@name='诊断']");
        if (disNode != null) {
            String disText = elementTxt(disNode);
            List<String> titles = CommonAnalysisUtil.sortTitlesNoColon(Lists.newArrayList("初步诊断", "补充诊断", "再次补充诊断", "修正诊断", "出院诊断"), disText);
            CommonAnalysisUtil.cutByTitlesNoColon(disText, titles, 0, map);
            titles.forEach(title -> {
                disExt(map, title);
            });
            rootElement.remove(disNode);
        }
    }

    //诊断特殊处理
    public static void disExt(Map<String, String> map, String key) {
        String disMessage = map.get(key);
        String sign = null;
        String signTime = null;
        int signIndex = 0;
        if (StringUtil.isNotBlank(disMessage)) {
            Pattern pattern = Pattern.compile("[0-9]+[年/-][0-9]+[月/-][0-9]+[日]{0,}");
            Matcher matcher = pattern.matcher(disMessage);
            if (matcher.find()) {
                signTime = matcher.group();
                disMessage = disMessage.substring(0, matcher.start());
            }

            signIndex = disMessage.indexOf("医师签名");
            if (signIndex > -1) {
                sign = disMessage.substring(signIndex).replace("医师签名", "").replaceAll("[：:]", "");
                disMessage = disMessage.substring(0, signIndex);
            }
            map.put(key, disMessage);
            if (StringUtil.isNotBlank(sign)) {
                map.put(key + "签名", sign.replaceAll("日期", ""));
            }
            if (StringUtil.isNotBlank(signTime)) {
                map.put(key + "签名日期", signTime);
            }
        }
    }

    //辅助检查
    public static void fzjcInsertMap(Element rootElement, Map<String, String> map) {
        Node fzjcNode = rootElement.selectSingleNode("section[@name='辅助检查']");
        if (fzjcNode != null) {
            map.put("辅助检查", elementTxt(fzjcNode).replaceFirst("辅助检查", ""));
            rootElement.remove(fzjcNode);
        }
    }

    // 专科检查
    public static void zkjcInsertMap(Element rootElement, Map<String, String> map) {
        Node zkjcNode = rootElement.selectSingleNode("section[@name='专科检查']");
        if (zkjcNode != null) {
            map.put("专科检查", elementTxt(zkjcNode).replaceFirst("专科检查", ""));
            rootElement.remove(zkjcNode);
        }
    }

    //基本信息
    public static void jbxxInsertMap(Element rootElement, Map<String, String> map) {
        Node jbxxNode = rootElement.selectSingleNode("section[@name='基本信息']");
        if (jbxxNode != null) {
            ((List<Element>) jbxxNode.selectNodes("fieldelem")).forEach(i -> {
                elementInsertMap(i, map);
            });
            String age = map.get("年龄");
            String ageYear = "";
            String ageMon = "";
            if (StringUtil.isNotBlank(age)) {
                ageYear = age;
                if (age.indexOf("岁") > -1) {
                    ageYear = age;
                } else if (age.indexOf("月") > -1) {
                    ageYear = "";
                    ageMon = age;
                }
            }
            map.put("年龄岁", ageYear);
            map.put("年龄月", ageMon);
            rootElement.remove(jbxxNode);
        }
    }

    //身高体重
    public static void sgtzInsertMap(Element rootElement, Map<String, String> map) {
        Map<String, String> map2 = Maps.newHashMap();
        Node tgjcNode = rootElement.selectSingleNode("section[@name='体格检查']");
        if (tgjcNode != null) {
            Node ybqkNode = tgjcNode.selectSingleNode("section[@name='一般情况']");
            if (ybqkNode != null) {
                if (StringUtil.isBlank(map.get("身高"))) {
                    elementInsertMap((Element) ybqkNode.selectSingleNode("fieldelem[@name='身高']"), map);
                }
                if (StringUtil.isBlank(map.get("体重"))) {
                    elementInsertMap((Element) ybqkNode.selectSingleNode("fieldelem[@name='体重']"), map);
                }

                String ybqkText = elementTxt(ybqkNode);
                List<String> titles = Lists.newArrayList("身高", "体重");
                titles = CommonAnalysisUtil.sortTitlesNoColon(titles, ybqkText);
                CommonAnalysisUtil.cutByTitlesNoColon(ybqkText, titles, 0, map2);
                sgtzxyInsertMap(map2);
            }
        }

        smtzSgtzInsertMap(rootElement, map2);
        if (!map.containsKey("身高")) {
            map.put("身高", map2.get("身高"));

        }
        if (!map.containsKey("体重")) {
            map.put("体重", map2.get("体重"));
        }
        if (!map.containsKey("收缩压")) {
            map.put("收缩压", map2.get("收缩压"));
        }
        if (!map.containsKey("舒张压")) {
            map.put("舒张压", map2.get("舒张压"));
        }
    }

    //生命体征中提取身高体重
    public static void smtzSgtzInsertMap(Element rootElement, Map<String, String> map) {
        Node tgjcNode = rootElement.selectSingleNode("section[@name='体格检查']");
        if (tgjcNode != null) {
            Node smtzNode = tgjcNode.selectSingleNode("section[@name='生命体征']");
            if (smtzNode != null) {
                Map<String, String> map2 = Maps.newHashMap();
                String smtzText = elementTxt(smtzNode);
                List<String> titles = Lists.newArrayList("身高", "体重", "血压", "BP");
                titles = CommonAnalysisUtil.sortTitlesNoColon(titles, smtzText);
                CommonAnalysisUtil.cutByTitlesNoColon(smtzText, titles, 0, map2);
                sgtzxyInsertMap(map2);

                map.put("收缩压", map2.get("收缩压"));
                map.put("舒张压", map2.get("舒张压"));
                if (StringUtil.isBlank(map.get("身高"))) {
                    map.put("身高", map2.get("身高"));
                }
                if (StringUtil.isBlank(map.get("体重"))) {
                    map.put("体重", map2.get("体重"));
                }
            }
        }
    }

    //身高、体重、血压公共处理方法
    private static void sgtzxyInsertMap(Map<String, String> map) {
        Pattern pattern = Pattern.compile("[0-9]+[.]{0,1}[0-9]*");
        if (map.containsKey("身高")) {
            String value = map.get("身高");
            if (StringUtil.isNotBlank(value)) {
                value = StringUtil.removeBlank(value);
                Matcher matcher = pattern.matcher(value);
                if (matcher.find()) {
                    map.put("身高", matcher.group());
                } else {
                    map.put("身高", "");
                }
            }
        }
        if (map.containsKey("体重")) {
            String value = map.get("体重");
            if (StringUtil.isNotBlank(value)) {
                value = StringUtil.removeBlank(value);
                Matcher matcher = pattern.matcher(value);
                if (matcher.find()) {
                    map.put("体重", matcher.group());
                } else {
                    map.put("体重", "");
                }
            }
        }
        pattern = Pattern.compile("[0-9]+[.]{0,1}[0-9]*/[0-9]+[.]{0,1}[0-9]*");
        if (map.containsKey("血压") || map.containsKey("BP")) {
            String value = map.get("血压");
            if (StringUtil.isBlank(value)) {
                value = map.get("BP");
            }
            if (StringUtil.isNotBlank(value)) {
                value = StringUtil.removeBlank(value);
                Matcher matcher = pattern.matcher(value);
                if (matcher.find()) {
                    value = matcher.group();
                    String[] arry = value.split("/");
                    if (arry.length == 2) {
                        map.put("收缩压", arry[0]);
                        map.put("舒张压", arry[1]);
                    }
                }
            }
        }
    }

    //体格检查
    public static void tgjcInsertMap(Element rootElement, Map<String, String> map) {
        Node tgjcNode = rootElement.selectSingleNode("section[@name='体格检查']");
        if (tgjcNode != null) {
            Node smtzNode = tgjcNode.selectSingleNode("section[@name='生命体征']");
            if (smtzNode != null) {
                ((List<Element>) smtzNode.selectNodes("fieldelem")).forEach(i -> {
                    elementInsertMap(i, map);
                });
            }
            ((List<Element>) tgjcNode.selectNodes("section[@name!='生命体征']")).forEach(i -> {
                elementInsertMap(i, map);
            });

            String jzsz = map.get("脊柱四肢");
            String jz = "";
            String sz = "";
            if (StringUtil.isNotBlank(jzsz)) {
                if (jzsz.indexOf("四肢") > -1) {
                    jz = jzsz.substring(0, jzsz.indexOf("四肢"));
                    sz = jzsz.substring(jzsz.indexOf("四肢"));
                } else {
                    jz = jzsz;
                }
            }
            map.put("脊柱", jz);
            map.put("四肢", sz);
            sgtzInsertMap(rootElement, map);
            rootElement.remove(tgjcNode);
        }
    }

    public static String elementTxt(Node node) {
        if (node != null) {
            return StringUtil.removeBlank(node.getStringValue());
        } else {
            return "";
        }
    }

    public static void elementInsertMap(Element element, Map<String, String> map) {
        if (element == null || map == null) {
            return;
        }
        String key = null;
        List<Element> elements = element.elements();
        if (elements.size() > 0 && (key = isKey(elementTxt(elements.get(0)))) != null) {
            element.remove(elements.get(0));
        } else {
            key = element.attributeValue("name");
        }
        if (StringUtil.isNotBlank(key)) {
            map.put(key, elementTxt(element));
        }
    }

    public static String isKey(String key) {
        if (StringUtil.isBlank(key)) {
            return null;
        }
        key = StringUtil.removeBlank(key);
        Pattern pattern = Pattern.compile("[\\u4e00-\\u9fa5]+[:：]");
        if (pattern.matcher(key).matches()) {
            return key.substring(0, key.length() - 1);
        } else {
            return null;
        }
    }

    public static String findTimeStr(String text) {
        String ret = "";
        Pattern pattern = Pattern.compile("[0-9]+[年/-][0-9]+[月/-][0-9]+[日]{0,}");
        Matcher matcher = pattern.matcher(text);
        if (matcher.find()) {
            ret = matcher.group();
        }
        return ret;
    }

}