package com.lantone.structure.facade.tran;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lantone.common.util.StringUtil;
import com.lantone.structure.facade.tran.util.CommonAnalysisUtil;
import com.lantone.structure.model.doc.FirstCourseRecordDoc;
import com.lantone.structure.util.MapUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;

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


/**
 * @Description:首次病程记录
 * @author: cy
 * @time: 2021/2/24 09:33
 */
@Slf4j
public class FirstCourseRecordTran extends TargetTran {

    @Override
    public Map<String, String> convert(String text) {
        FirstCourseRecordDoc firstCourseRecordDoc = new FirstCourseRecordDoc();
        firstCourseRecordDoc.setText(text);
        inputInfo.setFirstCourseRecordDoc(firstCourseRecordDoc);
        Map<String, String> structureMap = cutWord(text);
        Map<String, String> retMap = new HashMap<String, String>();
        firstCourseContrast(inputInfo.getFirstCourseRecordDoc(), 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);

        CommonAnalysisUtil.cutByTitles(text, titles, 0, sourceMap);
        return sourceMap;
    }


    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 lastTime(String top) {
        int length = top.trim().length();
        String stringDate = top.trim().substring(length - 11, length);
        Date date = null;
        try {
             date = DateUtils.parseDate(stringDate, StringUtil.dateFormats);
        } catch (Exception e) {
           log.error(e.getMessage(),e);
        }
        if(date!= null){
            return stringDate;
        }else{
            return "";
        }
    }


    public void firstCourseContrast( FirstCourseRecordDoc firstCourseRecordDoc, Map<String, String> retMap) {
        if(firstCourseRecordDoc != null) {
            String text = firstCourseRecordDoc.getText();
         if(text.contains("病例特点：")){
             String str = text.substring(0, text.indexOf("病例特点："));
             str = extractDate(str);
             if(StringUtil.isNotEmpty(str)){
                 retMap.put("记录日期时间",str);
             }
         }
            if(StringUtil.isNotEmpty(retMap.get("病例特点"))) {
                String specical = retMap.get("病例特点");
                String flagName = "因“";
                if (specical.contains(flagName)) {
                    specical = specical.substring(specical.indexOf(flagName));
                }
                String retStr = "";
                if (specical.contains("“")) {
                    String[] split = specical.split("“");
                    if (split.length > 1) {
                        retStr = split[1];
                    }
                if (retStr.contains("”")) {
                    String[] splits = retStr.split("”");
                    if (splits.length > 1) {
                        retStr = splits[0];
                    }
                }
                if(StringUtil.isNotEmpty(retStr)){
                    retMap.put("主诉",retStr);
                }

                }
            }

         if(text.contains("诊疗计划：")){
             String plan = retMap.get("诊疗计划");
             plan = text.substring(text.lastIndexOf("诊疗计划：") + "诊疗计划：".length());
            String str = text.substring(text.lastIndexOf("诊疗计划：") + "诊疗计划：".length());
            String flagName = "";
             if(str.contains("\n")){
                 String[] split = str.split("\n");
                 for (int i = 0; i < split.length; i++) {
                     if(split[i].contains("/") && split[i].length()<=15){
                         flagName = split[i];
                     }else{
                         String date = extractDate(split[i]);
                         if(StringUtil.isNotEmpty(date)){
                             flagName = split[i];
                         }else{
                             if(split[i].contains("年") && split[i].contains("月")&& split[i].contains("日")){
                                 flagName = split[i];
                             }
                         }
                     }
                     if(StringUtil.isNotEmpty(flagName) && plan.contains(flagName)){
                          plan = plan.substring(0, plan.lastIndexOf(flagName));
                         retMap.put("诊疗计划",plan);
                     }
                 }
             }
         }

         StringBuffer sb = new StringBuffer();
            if(StringUtil.isEmpty(retMap.get("入院诊断")) && text.contains("鉴别诊断：")){
                String str = text.substring(text.lastIndexOf("鉴别诊断：") + "鉴别诊断：".length());
                if(str.contains("问题小结：")){
                    str = str.split("问题小结：")[0];
                }
                if(str.contains("康复目标：")){
                    str = str.split("康复目标：")[0];
                }
                if(str.contains("诊疗计划：")){
                    str = str.split("诊疗计划：")[0];
                }
                 Boolean flag = true;
                if(str.contains("\n")){
                    String[] split = str.split("\n");
                    for (int i = 0; i < split.length; i++) {
                        if(split[i].contains("：")){
                            String[] splits = split[i].split("：");
                            sb.append(splits[0]);
                            flag = false;
                        }else if(split[i].contains(":")){
                            String[] splits = split[i].split(":");
                            sb.append(splits[0]);
                            flag = false;
                        }
                    }
                }
                if(StringUtil.isNotEmpty(sb.toString())){
                    retMap.put("鉴别诊断-西医诊断名称",sb.toString());
                }

                if(flag){
                    String firStr = retMap.get("鉴别诊断");
                    retMap.put("鉴别诊断-西医诊断名称",firStr);
                }
            }
        }
    }

    // 取/前
    public static String parseStr(String text){
        if(text.contains("/")){
            text = text.substring(0,text.lastIndexOf("/"));
            text= parseStr(text);
        }
        return text;
    }

    /**
     * 抽取文本中的第一个时间
     *
     * @param top
     * @return
     */
    public static String extractDate(String top) {
        Pattern pattern = Pattern.compile("[0-9]{4}[-][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]+日");
            Matcher m1 = p1.matcher(top);
            if (m1.find()) {
                return m1.group(0);
            }
        }
        return null;
    }
}