package com.lantone.structure.facade.tran;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lantone.common.util.ListUtil;
import com.lantone.common.util.StringUtil;
import com.lantone.structure.facade.tran.util.CommonAnalysisUtil;
import com.lantone.structure.model.doc.StagesSummaryDoc;
import com.lantone.structure.model.entity.AuxiliaryExamination;
import com.lantone.structure.model.entity.Drug;
import com.lantone.structure.model.entity.Laboratory;
import com.lantone.structure.model.entity.Surgery;
import com.lantone.structure.model.label.StagesSummaryLabel;
import com.lantone.structure.util.MapUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

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

/**
 * @Description:
 * @author: rengb
 * @time: 2021/2/2 14:15
 */
@Slf4j
public class StagesSummaryTran extends TargetTran {

    @Override
    public Map<String, String> convert(String text) {
        List<StagesSummaryDoc> stagesSummaryDocList = new ArrayList<>();
        StagesSummaryDoc stagesSummaryDoc = new StagesSummaryDoc();
        stagesSummaryDoc.setText(text);
        stagesSummaryDocList.add(stagesSummaryDoc);
        inputInfo.setStagesSummaryDocs(stagesSummaryDocList);
        aiProcess();
        Map<String, String> structureMap = cutWord(text);
        Map<String, String> retMap = new HashMap<String, String>();
        stagesContrast(inputInfo.getStagesSummaryDocs(), structureMap);
        mapKeyContrastCommon(structureMap,stagesContrasts,retMap);
        return retMap;
    }

    private List<String> stagesContrasts = Lists.newArrayList(
            "诊疗经过=诊疗过程描述",
            "诊疗计划=今后治疗方案"
    );
    private Map<String, String> cutWord(String text) {
        Map<String, String> sourceMap = Maps.newHashMap();
        List<String> titles = CommonAnalysisUtil.sortTitles(
                Lists.newArrayList("入院情况","入院诊断","辅助检查", "诊疗经过", "目前情况","目前诊断", "诊疗计划"),
                text
        );
        String retStr = parseBook(text);
        sourceMap.put("主诉",retStr);
        String stringDate =extractDate(text) ;
        if(StringUtils.isNotEmpty(stringDate)){
            sourceMap.put("小结日期时间",stringDate);
        }
        CommonAnalysisUtil.cutByTitles(text, titles, 0, sourceMap);
        if(sourceMap.containsKey("辅助检查")||sourceMap.containsKey("目前诊断")||sourceMap.containsKey("入院诊断")){
            sourceMap.remove("入院诊断");
            sourceMap.remove("辅助检查");
            sourceMap.remove("目前诊断");
        }
        if(sourceMap.containsKey("诊疗计划")&&StringUtil.isNotEmpty(sourceMap.get("诊疗计划"))){
            String retString = sourceMap.get("诊疗计划");
            String Data = parseString(retString);
            sourceMap.put("诊疗计划",Data);

        }
        return sourceMap;
    }

    // 取/前
    public static String parseString(String text){
        if(text.contains("/")){
            text = text.substring(0,text.lastIndexOf("/"));
            text= parseString(text);
        }
        return text;
    }
    public static String parseBook(String text){
        String[] sourceStr = text.split("因");
        String[] targetStr = {""};
        String retStr = "";
        if(sourceStr!=null&&sourceStr.length>1){
                 retStr = sourceStr[1].substring( sourceStr[1].indexOf("”")+1);
              if(retStr.contains("”")){
                   retStr = retStr.substring(0, retStr.indexOf("”"));
                   return retStr;
              }else{
                  retStr = "";
              }
              if(StringUtil.isEmpty(retStr)){
                  targetStr = sourceStr[1].split("于");
              }
        }
        if(targetStr!=null&&targetStr.length>1){
             retStr = targetStr[0];
        }
        return retStr;
    };

    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 (StringUtil.isNotBlank(sourceMap_.get(sourceKey))
                    && (!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));
            }
        }
    }


    /**
     * 抽取文本中的第一个时间
     *
     * @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;
    }

    public void stagesContrast( List<StagesSummaryDoc> stagesSummaryDocs, Map<String, String> retMap) {
        if(ListUtil.isNotEmpty(stagesSummaryDocs)){
            stagesSummaryDocs.forEach(stagesSummaryDoc -> {
                int auxCount = 1;
                int laboratoryCount = 1;
                int surgerysCount = 1;
                int drugsCount = 1;
                StringBuffer adviceString = new StringBuffer();
                StagesSummaryLabel stagesSummaryLabe = stagesSummaryDoc.getStagesSummaryLabel();
                if (ListUtil.isNotEmpty(stagesSummaryLabe.getAuxiliaryExaminations())) {
                        if (ListUtil.isNotEmpty(stagesSummaryLabe.getAuxiliaryExaminations())) {
                            adviceString.append( "辅助检查" + ":");
                            for (AuxiliaryExamination auxiliaryExaminations : stagesSummaryLabe.getAuxiliaryExaminations()) {
                                if(StringUtils.isNotEmpty( auxiliaryExaminations.getName())){
                                    if(stagesSummaryLabe.getAuxiliaryExaminations().size()>1){
                                        adviceString.append((auxCount++) + ".");
                                    }
                                    adviceString.append(auxiliaryExaminations.getName());
                                }
                            }
                            adviceString.append(";");
                        }

                }

                if (ListUtil.isNotEmpty(stagesSummaryLabe.getLaboratory())) {
                        if (ListUtil.isNotEmpty(stagesSummaryLabe.getLaboratory())) {
                            adviceString.append( "实验室检查"+ ":");
                            for (Laboratory laboratory : stagesSummaryLabe.getLaboratory()) {
                                if(StringUtils.isNotEmpty( laboratory.getName())){
                                    if(stagesSummaryLabe.getLaboratory().size()>1){
                                        adviceString.append((laboratoryCount++)+ ".");
                                    }
                                    adviceString.append(laboratory.getName());
                                }

                            }
                            adviceString.append(";");
                        }

                }

                if (ListUtil.isNotEmpty(stagesSummaryLabe.getSurgerys())) {
                        if (ListUtil.isNotEmpty(stagesSummaryLabe.getSurgerys())) {
                            adviceString.append("手术名称" + ":");
                            for (Surgery surgerys : stagesSummaryLabe.getSurgerys()) {
                                if(StringUtils.isNotEmpty( surgerys.getName())){
                                    if(stagesSummaryLabe.getSurgerys().size()>1){
                                        adviceString.append((surgerysCount++)+ ".");
                                    }
                                    adviceString.append(surgerys.getName());
                                }

                            }
                            adviceString.append(";");
                        }

                }
                if (ListUtil.isNotEmpty(stagesSummaryLabe.getDrugs())) {
                    if (ListUtil.isNotEmpty(stagesSummaryLabe.getDrugs())) {
                        adviceString.append( "抢救药品"+ ":");
                        for (Drug drugs : stagesSummaryLabe.getDrugs()) {
                            if(StringUtils.isNotEmpty( drugs.getName())){
                                if(stagesSummaryLabe.getDrugs().size()>1){
                                    adviceString.append((drugsCount++)+ ".");
                                }
                                adviceString.append(drugs.getName());
                            }

                        }
                        adviceString.append(";");
                    }

            }
                String adviceStr = adviceString.toString();
                if(adviceStr.endsWith(";")){
                    adviceStr = adviceStr.substring(0, adviceStr.lastIndexOf(";"));
                }
                retMap.put("医嘱内容",adviceStr);
            });
        }
    }


}