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.DeathCaseDiscussDoc;

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/23 09:15
 */
@Slf4j
public class DeathCaseDiscussionTran extends TargetTran {

    @Override
    public Map<String, String> convert(String text) {
        DeathCaseDiscussDoc deathCaseDiscussDoc = new DeathCaseDiscussDoc();
        deathCaseDiscussDoc.setText(text);
        inputInfo.setDeathCaseDiscussDoc(deathCaseDiscussDoc);
        Map<String, String> structureMap = cutWord(text);
        Map<String, String> retMap = new HashMap<String, String>();
        deathCaseDiscussContrast(inputInfo.getDeathCaseDiscussDoc(), 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
        );
        //单独处理参加人员(截取依据:护士不会汇报病史，而且汇报病史的人会出现在参加人员中，所以会有一个人的名字出现两次)
        List<String> ftitles = CommonAnalysisUtil.sortTitles(
                Lists.newArrayList("﹙副﹚主任医师","主治医师","医师","护士","汇报病史"),
                text
        );

        CommonAnalysisUtil.cutByTitles(text, titles, 0, sourceMap);
        CommonAnalysisUtil.cutByTitles(text, ftitles, 0, sourceMap);
        if(sourceMap.containsKey("性别")||sourceMap.containsKey("床号")||sourceMap.containsKey("汇报病史")||sourceMap.containsKey("护士")){
            sourceMap.remove("性别");
            sourceMap.remove("床号");
            sourceMap.remove("汇报病史");
        }

        return sourceMap;
    }

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

    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}");
        Matcher matcher = pattern.matcher(top);
        if (matcher.find()) {
            return matcher.group(0);
        }
        return null;
    }

    public void deathCaseDiscussContrast( DeathCaseDiscussDoc deathCaseDiscussDoc, Map<String, String> retMap) {
        if(deathCaseDiscussDoc != null){
            //姓名
            if(StringUtil.isNotEmpty(retMap.get("姓名"))){
                String value= resultHandle(retMap.get("姓名"));
                retMap.put("姓名",value);
            }

            //年龄
         if(StringUtil.isNotEmpty(retMap.get("年龄"))){
             String value= resultHandle(retMap.get("年龄"));
             if (value.contains("岁")) {
                 retMap.put("年龄（岁）",value);
                 retMap.remove("年龄");
             }
             if(value.contains("月")){
                 retMap.put("年龄（月）",value);
                 retMap.remove("年龄");
             }
         }

            //主持人姓名去职称
            List<String>titleStr = Lists.newArrayList("﹙副﹚主任医师","(副)主任医师","副主任医师", "主治医师","主任医师",
                    "住院医师","医师", "护士");
            for (String timeName : titleStr) {
                String dirName = retMap.get("讨论主持人");
                if (StringUtil.isNotEmpty(dirName)) {
                    if (dirName.contains(timeName)) {
                        retMap.put("讨论主持人", dirName.split(timeName)[0]);
                        break;
                    }
                }
            }

            //参加讨论人员名单

         // 去掉最后无法识别的名字，例如 徐金印医师汇报病史    该名会出现在参加人员名单上排除法处理
            // 兼容参加人员无护士-写法抛弃截取换行即可
            List<String> attendNames = new ArrayList<>();
            StringBuffer targetRet = new StringBuffer();
            if(StringUtil.isNotEmpty(retMap.get("参加人员"))){
                String  retData = "";
                String  replace = "";
                String attendName = retMap.get("参加人员");
                    if(StringUtil.isNotEmpty(retMap.get("﹙副﹚主任医师"))) {
                        String rName = retMap.get("﹙副﹚主任医师");
                        transAdd(rName, attendNames);
                        retMap.remove("﹙副﹚主任医师");
                    }
                    if(StringUtil.isNotEmpty(retMap.get("主治医师"))) {
                        String rName = retMap.get("主治医师");
                        transAdd(rName, attendNames);
                    }
                    if(StringUtil.isNotEmpty(retMap.get("医师"))) {
                        String rName = retMap.get("医师");
                        if(StringUtil.isEmpty(retMap.get("护士"))) {
                            rName =  rName.substring(0,rName.lastIndexOf("、") + 3);
                            transAdd(rName, attendNames);
                            String newRname =  retMap.get("医师").substring( retMap.get("医师").lastIndexOf("、") + 3);
                            for (String name : attendNames) {
                               if(newRname.contains(name)){
                                   retMap.put("医师", retMap.get("医师").substring(0,retMap.get("医师").lastIndexOf(name)));
                                    retData =attendName.substring(0, attendName.lastIndexOf(name));
                                    replace = retData;
                               }
                            }
                        }else{
                            transAdd(rName, attendNames);
                        }
                    }

                if(StringUtil.isNotEmpty(retMap.get("护士"))) {
                    String spiltString = attendName.substring(attendName.indexOf("护士")+2, attendName.lastIndexOf("医师"));
                    for (String name : attendNames) {
                        if(spiltString.contains(name)){
                            retData = attendName.substring(0, attendName.lastIndexOf(name));
                            replace = retData;
                        }
                    }
                }

                //职称与姓名空格区分
                if( retData.contains("主治医师：")){
                    retData = retData.substring(0,retData.indexOf("主治医师："));
                    if(StringUtil.isNotEmpty(retData)){
                        targetRet.append(retData+" ");
                    }
                    if(StringUtil.isNotEmpty(retMap.get("主治医师"))){
                        targetRet.append("主治医师："+retMap.get("主治医师")+" ");
                    }
                    if(StringUtil.isNotEmpty(retMap.get("医师"))){
                        targetRet.append("医师："+retMap.get("医师")+" ");
                    }
                    String rec = "";

                    if( replace.contains("护士：")){
                        rec = replace.substring(replace.lastIndexOf("护士："));
                    }
                    if(StringUtil.isNotEmpty(rec)){
                        targetRet.append(rec);
                        retMap.remove("护士");
                    }
                }


                    retMap.remove("主治医师");
                    retMap.remove("医师");
                    retMap.put("参加人员",targetRet.toString());
                }


            //直接死亡原因名称
            if(StringUtil.isNotEmpty(retMap.get("死亡诊断"))){
                String deathDiagnosislName = retMap.get("死亡诊断");
                comatible(deathDiagnosislName,retMap);
            }

            //主持人签名
            if(StringUtil.isNotEmpty(retMap.get("主持人总结"))){
                String directSummary = retMap.get("主持人总结");

                //签名日期时间
                if(directSummary.contains("记录者（签名）")) {
                    String sginTime= lastTime(directSummary);
                    if(StringUtil.isNotEmpty(sginTime)){
                        retMap.put("签名日期时间", sginTime);
                    }

                String trueRet = "";
                if(directSummary.contains("主持人（签名）") && directSummary.contains("记录者（签名）")){
                    trueRet = directSummary.substring( directSummary.indexOf("主持人（签名）")+7, directSummary.indexOf("记录者（签名）")).trim();
                }
                if(directSummary.contains(" 记录者（签名）")){
                    String signTimme = retMap.get("签名日期时间");
                    if(StringUtil.isNotEmpty(signTimme)){
                        String recordRet = directSummary.substring(directSummary.indexOf("记录者（签名）")+7,directSummary.indexOf( signTimme.split("年")[0])).trim();
                        retMap.put("主治医师签名",recordRet);
                    }
                }

                if(StringUtil.isNotEmpty(trueRet)){
                    retMap.put("主任医师签名",trueRet);
                }
                }
            }

            //主持人总结
            if(StringUtil.isNotEmpty(retMap.get("主持人总结"))){
                String directSummary = retMap.get("主持人总结");
                String trueRet = "";
                if(directSummary.contains("主持人（签名）")){
                    trueRet = directSummary.substring(0, directSummary.indexOf("主持人（签名）"));
                }
                retMap.put("主持人总结",trueRet);
            }
        }

    }

    public static void comatible(String deathDiagnosislName,Map<String,String>retMap){
        String trueRet = "";
        if (deathDiagnosislName.contains("2.")) {
            trueRet = deathDiagnosislName.substring(0, deathDiagnosislName.indexOf("2."));
            if (trueRet.contains("1.")) {
                trueRet = trueRet.substring(2);
            }
        }else{
            if (deathDiagnosislName.contains("1.")) {
                trueRet = deathDiagnosislName;
            }else{
                trueRet=  deathDiagnosislName.trim().split(" ")[0];
            }
        }

        if(StringUtil.isNotEmpty(trueRet)){
            retMap.put("直接死亡原因名称", trueRet);
        }
    }


    /**
     * 抽取文本中的最后时间
     *
     * @param top
     * @return
     */
    public static String lastTime(String top) {
        int length = top.trim().length();
        String substring = top.trim().substring(length - 22, length);
        String stringDate = "";
        if( substring.contains("年")){
           String[] time = substring.split("年");
           String timeYear = time[0].trim();
                  timeYear = extractDate(timeYear);
            if( substring.contains("月")){
               String[] timeLater = time[1].split("月");
               String timeMouth = timeLater[0].trim();
               if(substring.contains("日")){
                   String[] timeLast = timeLater[1].split("日");
                   String timeDate = timeLast[0].trim();
                   if(StringUtil.isNotEmpty(timeYear) && StringUtil.isNotEmpty(timeMouth) && StringUtil.isNotEmpty(timeDate)){
                       stringDate = timeYear + "年" + timeMouth + "月" + timeDate + "日" ;
                   }
               }
           }
       }
        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 "";
        }
    }

    private String resultHandle(String value) {
            if (StringUtil.isNotBlank(value)) {
                value = StringUtil.trim(value);
                if (value.endsWith("，") || value.endsWith(",")) {
                    value = value.substring(0, value.length() - 1);
                }
            }
        return value;
    }
    //递归添加到集合
    public void transAdd(String name, List<String> attendName){
          if(name.contains("、") || name.contains(" ")){
              String value = "";
              if(name.contains("、")){
                   value = name.substring(name.lastIndexOf("、")+1);
                   name = name.substring(0,name.lastIndexOf("、"));
              }
              if(name.contains(" ")){
                   value = name.substring(name.lastIndexOf(" ")+1);
                   name = name.substring(0,name.lastIndexOf(" "));
              }
              if(StringUtil.isNotEmpty(value)){
                  if(value.contains("主任")){
                      value = value.substring(0, value.indexOf("主任"));
                  }
                  if(value.contains("主治")) {
                      value = value.substring(0, value.indexOf("主治"));
                  }
                  if(value.contains("医师")){
                      value = value.substring(0,value.indexOf("医师"));
                  }
                  attendName.add(value);
              }
              transAdd(name, attendName);
          }else{
              if(name.contains("主任")){
                  name = name.substring(0, name.indexOf("主任"));
              }
              if(name.contains("主治")) {
                  name = name.substring(0, name.indexOf("主治"));
              }
              if(name.contains("医师")){
                  name = name.substring(0,name.indexOf("医师"));
              }
              attendName.add(name);
          }
    }

}