package com.lantone.qc.trans.beilun.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 org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

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

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

    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);
            }
            BeiLunHtmlAnalysisUtil.insertModuleId(modeId, recTypeId, map);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return map;
    }

    //一般模板
    private void analysisGeneral(Document doc, String recTitle, Map<String, String> map) {
        //个人基础信息table解析
        BeiLunHtmlAnalysisUtil.tableStyle1InsertMap(doc.getElementById("table1"), map);
        //主诉、现病史等table解析
        BeiLunHtmlAnalysisUtil.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");
        BeiLunHtmlAnalysisUtil.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;
            }
        }

        BeiLunHtmlAnalysisUtil.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("医生签名时间", BeiLunHtmlAnalysisUtil.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 = BeiLunHtmlAnalysisUtil.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 = BeiLunHtmlAnalysisUtil.blockDivToStr(doc.selectFirst("body").child(0), 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解析
        BeiLunHtmlAnalysisUtil.tableStyle1InsertMap(doc.getElementById("table1"), map);
        //主诉、入院情况等table解析
        BeiLunHtmlAnalysisUtil.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("医生签名时间", BeiLunHtmlAnalysisUtil.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));
                    }
                }
            }
        }
    }

}