package com.lantone.qc.trans.ninghaiyiyi.util;

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 lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @author: rengb
 * @time: 2020/9/15 16:28
 */
@Slf4j
public class NingHaiYiYiBeHospitalizedHtmlAnalysis implements NingHaiYiYiHtmlAnalysis {

    private String modeId = "1";

    @Override
    public Map<String, String> analysis(String... args) {
        Map<String, String> map = Maps.newLinkedHashMap();
        try {
            String html = args[0];
            String recTitle = args[1];
            String recTypeId = args[2];
            Document doc = Jsoup.parse(html);

            if (recTitle.contains("24")) {
                analysis24h(doc, map);
            } else if (recTitle.contains("日间病历")) {
                analysisDay(doc, map);
            } else {
//                analysisGeneral(doc, recTitle, map);
                analysisBeHospitalized(doc, map);
            }
            NingHaiYiYiHtmlAnalysisUtil.insertModuleId(modeId, recTypeId, map);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return map;
    }

    //宁海第一人民医院
    private void analysisBeHospitalized(Document doc, Map<String, String> map) {
        NingHaiYiYiHtmlAnalysisUtil.tableStyle1InsertMap(doc.getElementById("header"), map);
        map.forEach((key, value) -> map.put(key, value.replace("\n", "")));
        List<String> titles = Lists.newArrayList("姓 名", "入院时间", "出生日期", "性 别", "性别", "记录时间","年 龄", "出 生 地", "职 业", "职业", "入院时间", "民 族", "民族",
                "联系地址", "婚 姻", "婚姻", "病史陈述者", "病史可靠度", "家长姓名","住 址","联系电话", "主诉", "主 诉", "现 病 史","现病史", "既 往 史", "个 人 史", "母 孕 史", "出 生 史", "喂 养 史",
                "既往史", "个人史", "母孕史", "出生史", "喂养史","婚育史","家族史","年龄","姓名","出生地","住址",
                "末次月经","身份证号","户籍地址","联 系 人","孕/产 次","预 产 期","产前检查","籍贯","",
                "生长发育史", "预防接种史", "生活习惯史", "婚 育 史", "月经婚育史", "家 族 史", "辅助检查", "记录医生", "初步诊断", "补充诊断");
        String htmlContent = NingHaiYiYiHtmlAnalysisUtil.blockDivToStr(doc.selectFirst("body").child(0).getElementById("main"), true);
        if (StringUtil.isNotBlank(htmlContent)) {
            htmlContent = htmlContent.replaceAll("[   ]", " ").replace("第 ( ) 页", "");
            CommonAnalysisUtil.html2StructureMap(titles, htmlContent, map);
            disDiagnose(map, Lists.newArrayList("初步诊断"), "医师签名:");
            disDiagnose(map, Lists.newArrayList("初步诊断医师签名:"), "时 间:");
            //入院记录 体格检查、补充及专科情况里获取辅助检查提取
            getAuxiliary(map,Lists.newArrayList("体格检查","补充及专科情况","补充及专科情况"),htmlContent);
            //婚育史特殊符号处理
//            removeSymbol(map,"□","婚育史");
        }
    }

    private void getAuxiliary(Map<String, String> map, ArrayList<String> newArrayList,String htmlContent) {
        CommonAnalysisUtil.html2StructureMapNoColon(newArrayList, htmlContent, map);
        //家族史其他内容清理
        if(map.keySet().contains("家族史"))
        {
            String fimaly = map.get("家族史");
            if(map.keySet().contains("体格检查"))
            {
                removeMapVal(map,fimaly,"体格检查","家族史");
                if(map.keySet().contains("补充及专科情况")&&StringUtil.isBlank(map.get("辅助检查")))
                {
                    String auxiliary = map.get("补充及专科情况");
                    CommonAnalysisUtil.html2StructureMapNoColon(
                            Lists.newArrayList("辅助检查"),auxiliary, map);
                    if(map.get("辅助检查").contains("初步诊断")&&StringUtil.isNotBlank(map.get("初步诊断"))
                            &&map.get("辅助检查").contains(map.get("初步诊断")))
                    {
                        String val = map.get("辅助检查");
                        if(val.contains(map.get("初步诊断")))
                        {
                            val = val.split("初步诊断")[0].replaceAll("初步诊断","")
                                    .replaceAll(":","").trim();
                            map.put("辅助检查",val);

                        }
                    }
                }
            }

        }
    }

    private void removeMapVal(Map<String, String> map, String val,String mapkey,String changeKey) {
        if(val.contains(map.get(mapkey)))
        {
            val = val.split(map.get(mapkey))[0].replaceAll(mapkey,"").trim();
            map.put(changeKey,val);
        }
    }

    /**
     * @Author songxl
     * @Description map中特殊符号处理
     * @Date  2021/4/8
     * @Param [map,symbol,key]
     * @Return void
     * @MethodName removeSymbol
     */
    private void removeSymbol(Map<String, String> map,String symbol,String key) {
        if(map.keySet().contains(key))
        {
            map.put(key,map.get(key).replaceAll(symbol,"").trim());
        }
    }

    /**
     * 处理诊断
     */
    private void disDiagnose(Map<String, String> map, List<String> lists, String str) {
        for (String key : lists) {
            String value = map.get(key);
            if (StringUtil.isNotBlank(value) && value.contains(str)) {
                map.put(key, value.substring(0, value.indexOf(str)));
                map.put(key + str, value.substring(value.indexOf(str) + str.length()));
            }
        }
    }

    //一般模板
    private void analysisGeneral(Document doc, String recTitle, Map<String, String> map) {
        //个人基础信息table解析
        NingHaiYiYiHtmlAnalysisUtil.tableStyle1InsertMap(doc.getElementById("table1"), map);
        //主诉、现病史等table解析
        NingHaiYiYiHtmlAnalysisUtil.tableStyle2InsertMap(doc.getElementById("table6"), map);
        if (StringUtil.isNotBlank(map.get("婚育史月经史")) && map.get("婚育史月经史").contains("经期")) {
            map.put("婚育史", map.get("婚育史月经史").substring(0, map.get("婚育史月经史").indexOf("经期")));
        }
        //体 格 检 查 表（一） table解析
        Element tgjcTableElement = doc.getElementById("table3");
        NingHaiYiYiHtmlAnalysisUtil.tableStyle2InsertMap(tgjcTableElement, map);

        //诊断 table解析
        String disTableElementId = null;
        Element disTableElement = null;
        String[] disTableElementIds = {"table7_2_0_0_1_1_2_0_1_4_5_6_7_0_1_37", "table7_2_0_0_1_1_2_0_1_4_5_6_7_0_1", "table7_2_0_0_1_1_2_0_1_4_5_6_7", "table7_2_0_0_1_1_2_0_1_4_5_6_7_0_1_5_2_3_1_2", "table7_2_0_0_1_1_2_0_1_4_5_6_7_0_1_5_2_3", "table7_2_0_0_1_1_2_0_1_4_5_6_7_0_1_5_2_3_1_2_27", "table7_2_0_0_1_1_2_0_1_4_5_6_7_0_1_5_2_3_1"};
        for (String eid : disTableElementIds) {
            disTableElement = doc.getElementById(eid);
            if (disTableElement != null) {
                disTableElementId = eid;
                break;
            }
        }

        NingHaiYiYiHtmlAnalysisUtil.tableStyle1InsertMap(disTableElement, map);
        disHandleExt(map);

        //医生签名、医生签名时间
        Element docSignElement = null, docSignTimeElement = null;
        if (disTableElement != null) {
            for (Element disTableElementNt : disTableElement.nextElementSiblings()) {
                docSignElement = disTableElementNt.selectFirst("image,img");
                if (docSignElement != null) {
                    docSignTimeElement = disTableElementNt.nextElementSibling();
                    break;
                }
            }
        }
        if (docSignElement != null) {
//            map.put("医生签名", docSignElement.outerHtml());
            map.put("医生签名", "暂无");
        }
        if (docSignTimeElement != null) {
            map.put("医生签名时间", NingHaiYiYiHtmlAnalysisUtil.elementLayer1ToStr(docSignTimeElement, false).trim());
        }

        //专科检查、辅助检查
        Element yuElement = new Element("div");
        if (tgjcTableElement != null) {
            for (Element tgjcTableElementNt : tgjcTableElement.nextElementSiblings()) {
                if (StringUtil.isNotBlank(disTableElementId) && tgjcTableElementNt.id().contains(disTableElementId)) {
                    break;
                }
                if (tgjcTableElementNt.tagName().equals("table")) {
                    continue;
                }
                tgjcTableElementNt.appendTo(yuElement);
            }
        }
        String yuText = NingHaiYiYiHtmlAnalysisUtil.blockDivToStr(yuElement, true)
                .replace("体  格  检  查  表 （二）", "")
                .replace("（补充及专科情况）", "")
                .replace("辅  助  检  查", "辅助检查：")
                .replace("诊断：", "")
                .replace("补充专科情况", "补充专科情况：")
                .trim();
        CommonAnalysisUtil.cutByTitles(yuText, Lists.newArrayList("专科检查", "辅助检查"), 0, map);

    }

    //24小时出入院记录、24小时出入院记录（全院）、24小时入出院记录(全院通用)、24小时内入院死亡记录(全院通用)
    private void analysis24h(Document doc, Map<String, String> map) {
        String text = NingHaiYiYiHtmlAnalysisUtil.blockDivToStr(doc.selectFirst("body").child(0).getElementById("main"), false);
        text = text.substring(text.lastIndexOf("24小时入出院记录姓    名")).replaceFirst("第1页", "");
        List<String> titles = Lists.newArrayList("姓    名", "家庭住址", "性    别", "工作单位", "年    龄", "身份证号码", "民    族",
                "联系人(关系)", "职    业", "入院时间", "婚    姻", "死亡时间", "记录时间", "出 生 地", "病史陈述者", "主    诉", "入院情况", "心理评估",
                "疼痛评估", "营养评估", "功能评估", "入院诊断", "诊疗经过", "死亡原因", "死亡诊断", "出院情况", "出院诊断", "出院计划", "出院医嘱",
                "出院去向", "医师签名", "书写时间");

        CommonAnalysisUtil.cutByTitles(text, titles, 0, map);
        CommonAnalysisUtil.processType(map, "出院去向");
    }

    //原-日间病历入出院记录、日间病历-性早熟
    private void analysisDay(Document doc, Map<String, String> map) {
        //个人基础信息table解析
        NingHaiYiYiHtmlAnalysisUtil.tableStyle1InsertMap(doc.getElementById("table1"), map);
        //主诉、入院情况等table解析
        NingHaiYiYiHtmlAnalysisUtil.tableStyle2InsertMap(doc.getElementById("table6"), map);
        //医生签名、医生签名时间
        Element docSignElement = null, docSignTimeElement = null;
        for (Element table6ElementNt : doc.getElementById("table6").parent().nextElementSiblings()) {
            docSignElement = table6ElementNt.selectFirst("image,img");
            if (docSignElement != null) {
                docSignTimeElement = table6ElementNt.nextElementSibling();
                break;
            }
        }
        if (docSignElement != null) {
//            map.put("医生签名", docSignElement.outerHtml());
            map.put("医生签名", "暂无");
        }
        if (docSignTimeElement != null) {
            map.put("医生签名时间", NingHaiYiYiHtmlAnalysisUtil.elementLayer1ToStr(docSignTimeElement, false).trim());
        }
    }

    private void disHandleExt(Map<String, String> map) {
        String[] keys = {"补充诊断", "修正诊断"};
        String value = null;
        int index = 0;
        for (String key : keys) {
            value = map.get(key);
            if (StringUtil.isNotBlank(value)) {
                for (String key_ : keys) {
                    index = value.indexOf(key_);
                    if (index > 0) {
                        map.put(key_, value.substring(index + 5));
                        map.put(key, value.substring(0, index));
                    }
                }
            }
        }
    }
}