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 java.util.List;
import java.util.Map;

/**
 * @Description: 疑难、危重病例讨论记录html解析
 * @author: HUJING
 * @time: 2020/9/14 15:41
 */
@Slf4j
public class BeiLunDifficultCaseDiscussHtmlAnalysis implements BeiLunHtmlAnalysis {

    private String modeId = "19";

    @Override
    public Map<String, String> analysis(String... args) {
        Map<String, String> structureMap = Maps.newLinkedHashMap();
        try {
            List<String> titles = Lists.newArrayList("姓名", "性别", "出生日期", "科别", "病区", "床号",
                    "住院号", "年龄", "床号", "住院号", "住址（单位）", "讨论日期", "讨论地点", "主持人", "参加人员", "具体讨论意见",
                    "主持人小结意见", "主持人小结意见/讨论结论", "主持人签名", "记录医生签名");
            String html = args[0];
            String recTitle = args[1];
            String recTypeId = args[2];
            Document doc = Jsoup.parse(html);
            String htmlContent = BeiLunHtmlAnalysisUtil.blockDivToStr(doc.selectFirst("body").child(0), true);
            if (StringUtil.isNotBlank(htmlContent)) {
                htmlContent = htmlContent.replaceAll("[   ]", " ").replace("第一页","");
                CommonAnalysisUtil.html2StructureMap(titles, htmlContent, structureMap);
            }
            CommonAnalysisUtil.extractDateByTitle(structureMap, "告知时间");
            removeLast(structureMap);
            if (structureMap.containsKey("住院号")) {
                String date = CommonAnalysisUtil.extractDate(structureMap.get("住院号"));
                if (StringUtil.isNotBlank(date)) {
                    structureMap.put("时间", date);
                    structureMap.put("住院号", structureMap.get("住院号").replace(date, "").replace("\n", ""));

                }
            }
            BeiLunHtmlAnalysisUtil.insertModuleId(modeId, recTypeId, structureMap);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return structureMap;
    }

    /**
     * 去除value中最后的逗号
     *
     * @param structureMap
     */
    private void removeLast(Map<String, String> structureMap) {
        for (Map.Entry<String, String> entry : structureMap.entrySet()) {
            structureMap.put(entry.getKey(), findLast(entry.getValue()));
        }
    }

    private String findLast(String value) {
        if (StringUtil.isNotBlank(value)) {
            if (value.lastIndexOf("，") != value.length() - 1) {
                return value;
            }
            value = value.substring(0, value.length() - 1);
            findLast(value);
        }
        return value;
    }
}