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.RescueDoc;
import com.lantone.structure.model.entity.*;
import com.lantone.structure.model.label.RescueLabel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

    @Override
    public Map<String, String> convert(String text) {
        List<RescueDoc> rescueDocList = new ArrayList<>();
        RescueDoc rescueDoc = new RescueDoc();
        rescueDoc.setText(text);
        rescueDocList.add(rescueDoc);
        inputInfo.setRescueDocs(rescueDocList);
        aiProcess();
        Map<String, String> structureMap = cutWord(text);
        rescueContrast(text,inputInfo.getRescueDocs(), structureMap);
        return structureMap;
    }

    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);
//        if(sourceMap.containsKey("参与现场抢救的医务人员")){
//            sourceMap.remove("参与现场抢救的医务人员");
//        }
        return sourceMap;
    }


    public void rescueContrast(String text, List<RescueDoc> rescueDocs,Map<String, String> retMap) {
        if(ListUtil.isNotEmpty(rescueDocs)){
            List<String> str= Arrays.asList("修正诊断", "补充诊断","入院后辅助检查补充","辅助检查补充","抢救情况","。",".","/");
            if(StringUtils.isNotEmpty(retMap.get("参与现场抢救的医务人员"))){
                String rescuePersons = retMap.get("参与现场抢救的医务人员");
                for (String s : str) {
                    if(rescuePersons.contains(s)){
                        rescuePersons = rescuePersons.split(s)[0];
                    }
                }
                retMap.put("参与现场抢救的医务人员",rescuePersons);
            }

            rescueDocs.forEach(rescueDoc -> {
                int auxiliaryCount = 1;
                int auxiliaryResultCount = 1;
                int operationsCount = 1;
                int operationLocationCount = 1;
                int methodsCount = 1;
                int count = 1;
                int interventionCount = 1;
                int conditionsCount = 1;
                int diagnosisCount = 1;
                int drugsCount = 1;
                StringBuffer auxiliaryTestString = new StringBuffer();
                StringBuffer auxiliaryResultString  = new StringBuffer();
                StringBuffer operationsString = new StringBuffer();
                StringBuffer operationLocationString = new StringBuffer();
                StringBuffer methodsString = new StringBuffer();
                StringBuffer countString = new StringBuffer();
                StringBuffer conditionsString = new StringBuffer();
                StringBuffer diagnosisString = new StringBuffer();
                StringBuffer interventionString = new StringBuffer();
                StringBuffer drugsString = new StringBuffer();
                StringBuffer resMedString = new StringBuffer();

                RescueLabel rescueLabel = rescueDoc.getRescueLabel();
                    if(ListUtil.isNotEmpty( rescueLabel.getAuxiliaryTest())){
                        for (AuxiliaryTest auxiliaryTest : rescueLabel.getAuxiliaryTest()) {
                                for (AuxiliaryResult auxiliaryResult : auxiliaryTest.getAuxiliaryResult()) {
                                    if(StringUtils.isNotEmpty( auxiliaryResult.getName())){
                                        if(auxiliaryTest.getAuxiliaryResult().size()>1){
                                            auxiliaryResultString.append(" "+(auxiliaryResultCount++) + ".");
                                        }
                                        auxiliaryResultString.append(auxiliaryResult.getName());
                                    }
                                }

                            if(StringUtils.isNotEmpty(auxiliaryTest.getName())){
                                if(rescueLabel.getAuxiliaryTest().size()>1) {
                                    auxiliaryTestString.append((auxiliaryCount++) + ".");
                                }
                                auxiliaryTestString.append(auxiliaryTest.getName());
                            }

                        }
                        if(StringUtil.isNotEmpty(auxiliaryTestString.toString())){
                            retMap.put("检查/检验项目名称", auxiliaryTestString.toString());
                        }

                        if(StringUtil.isNotEmpty(auxiliaryResultString.toString())){
                            retMap.put("检查/检验结果", auxiliaryResultString.toString());
                        }
                       }

                    if(ListUtil.isNotEmpty( rescueLabel.getOperations())){
                        for (Operation operations : rescueLabel.getOperations()) {
                            if(operations.getOperationLocation()!=null && StringUtils.isNotEmpty( operations.getOperationLocation().getName())){
                                if(rescueLabel.getOperations().size()>1){
                                    operationLocationString.append((operationLocationCount++) + ".");
                                }
                                operationLocationString.append(operations.getOperationLocation().getName());
                            }
                            if(StringUtils.isNotEmpty(operations.getName())){
                                if(rescueLabel.getOperations().size()>1){
                                    operationsString.append((operationsCount++) + ".");
                                }
                                operationsString.append( operations.getName());
                            }

                        }
                        if(StringUtil.isNotEmpty(operationsString.toString())){
                            retMap.put("手术及操作名称", operationsString.toString());
                        }

                        if(StringUtil.isNotEmpty(operationLocationString.toString())){
                            retMap.put("手术及操作目标部位名称", operationLocationString.toString());
                        }
                        if(StringUtils.isNotEmpty(retMap.get("手术及操作名称"))){
                            resMedString.append("手术及操作名称"+":"+retMap.get("手术及操作名称")+";");
                        }

                        if(StringUtils.isNotEmpty(retMap.get("手术及操作目标部位名称"))){
                            resMedString.append("手术及操作目标部位名称"+":"+retMap.get("手术及操作目标部位名称")+";");
                        }

                  }

                    if(ListUtil.isNotEmpty(rescueLabel.getMethods())){
                        for (Method methods : rescueLabel.getMethods()) {
                            if(StringUtils.isNotEmpty(methods.getName())){
                                if(rescueLabel.getMethods().size()>1){
                                    methodsString.append((methodsCount++) + ".");
                                }
                                methodsString.append( methods.getName());
                            }
                            if( methods.getCount() != null){
                                if(rescueLabel.getMethods().size()>1){
                                    countString.append((count++) + ".");
                                }
                                countString.append(methods.getName()+methods.getCount().getName());
                            }
                        }
                        if(StringUtil.isNotEmpty(methodsString.toString())){
                            retMap.put("操作方法", methodsString.toString());
                        }
                        if(StringUtil.isNotEmpty(countString.toString())){
                            retMap.put("操作次数", countString.toString());
                        }

                        if(StringUtils.isNotEmpty(retMap.get("操作方法"))){
                            resMedString.append("操作方法"+":"+retMap.get("操作方法")+";");
                        }
                        if(StringUtils.isNotEmpty(retMap.get("操作次数"))){
                            resMedString.append("操作次数"+":"+retMap.get("操作次数")+";");
                        }

                        }

                    if(ListUtil.isNotEmpty(rescueLabel.getInterventions())){
                        for (Intervention intervention : rescueLabel.getInterventions()) {
                            if(StringUtils.isNotEmpty(intervention.getName())){
                                if(rescueLabel.getInterventions().size()>1){
                                    interventionString.append((interventionCount++) + ".");
                                }
                                interventionString.append(intervention.getName());
                            }
                        }
                        if(StringUtil.isNotEmpty(interventionString.toString())){
                            retMap.put("介入物名称",interventionString.toString());
                        }
                    }

                List<String> strDate = new ArrayList<>();
                if(ListUtil.isNotEmpty(rescueLabel.getConditions())){
                        //抢救病情长度1时间没有，大于1时间开始取最初 结束取最后
                        if(rescueLabel.getConditions().size()>1){
                            for (Condition condition : rescueLabel.getConditions()) {
                                if(null != condition.getPd() && StringUtils.isNotEmpty( condition.getPd().getValue())){
                                    strDate.add(condition.getPd().getValue());
                                }
                            }
                            if(ListUtil.isNotEmpty(strDate)){
                                String startHmsTime = transHmTime(strDate.get(0));
                                retMap.put("抢救开始日期时间",startHmsTime);
                                if(strDate.size()>1 && ! strDate.get(0).equals(strDate.get(strDate.size()-1))){
                                    String endHmsTime = transHmTime(strDate.get(strDate.size() - 1));
                                    if(!endHmsTime.contains(" ")){
                                        endHmsTime = endHmsTime.replace("日", "日 ");
                                    }
                                    retMap.put("抢救结束日期时间",endHmsTime);
                                }
                            }
                        }
                    for (Condition conditions : rescueLabel.getConditions()) {
                        if(StringUtils.isNotEmpty(conditions.getName())){
                            if(rescueLabel.getInterventions().size()>1){
                                conditionsString.append((conditionsCount++) + ".");
                            }
                            conditionsString.append(conditions.getName());
                        }

                    }
                        if(StringUtil.isNotEmpty(conditionsString.toString())){
                            retMap.put("病情变化情况",conditionsString.toString());
                        }
                  }

                    if(StringUtils.isNotEmpty(retMap.get("抢救开始日期时间"))){
                        String resuceStartDate = retMap.get("抢救开始日期时间");
                        if(!resuceStartDate.contains("年")){
                            String date = transDate(extractDate(text));
                            if(StringUtils.isNotEmpty(date.trim())){
                                resuceStartDate= date+" "+resuceStartDate;
                                retMap.put("抢救开始日期时间",resuceStartDate);
                            }
                        }
                        String flagTime = resuceStartDate.substring(resuceStartDate.lastIndexOf("日"), resuceStartDate.lastIndexOf("时"));
                        if(!flagTime.contains(" ")){
                            resuceStartDate = resuceStartDate.replace("日", "日 ");
                            retMap.put("抢救开始日期时间",resuceStartDate);
                        }

                    }

                if(StringUtils.isNotEmpty(retMap.get("抢救结束日期时间"))){
                    String resuceStartDate = retMap.get("抢救开始日期时间");
                    String resuceEndDate = retMap.get("抢救结束日期时间");
                    if(!resuceEndDate.contains("年")){
                        String date = resuceStartDate.split("日")[0];
                        if(StringUtils.isNotEmpty(date.trim())){
                            resuceEndDate= date+"日 "+resuceEndDate;
                            retMap.put("抢救结束日期时间",resuceEndDate);
                        }
                    }
                    compareDate(resuceStartDate,resuceEndDate,retMap);
                }


                    if(ListUtil.isNotEmpty(rescueLabel.getDiagnosis())){
                    for (Diagnosis diagnosis : rescueLabel.getDiagnosis()) {
                        if(StringUtils.isNotEmpty(diagnosis.getName())){
                            if(rescueLabel.getInterventions().size()>1){
                                diagnosisString.append((diagnosisCount++) + ".");
                            }
                            diagnosisString.append(diagnosis.getName());
                        }
                    }
                        if(StringUtil.isNotEmpty(conditionsString.toString())){
                            retMap.put("疾病诊断名称", diagnosisString.toString());
                        }
                  }


                if(!retMap.containsKey("抢救措施")&&StringUtils.isEmpty(retMap.get("抢救措施"))){
                    //抢救药品只会出现在抢救措施里面
                    if(ListUtil.isNotEmpty(rescueLabel.getDrugs())){
                        for (Drug drugs : rescueLabel.getDrugs()) {
                            if(StringUtils.isNotEmpty(drugs.getName())){
                                if(rescueLabel.getDrugs().size()>1){
                                    drugsString.append((drugsCount++) + ".");
                                }
                                drugsString.append(drugs.getName());
                            }
                        }
                        if(StringUtils.isNotEmpty( drugsString.toString())){
                            resMedString.append("抢救药品"+":"+ drugsString.toString()+";");
                        }
                    }
                    if(StringUtils.isNotEmpty( drugsString.toString())){
                        String resMedStr = resMedString.toString();
                        if(resMedStr.endsWith(";")){
                            resMedStr = resMedStr.substring(0, resMedStr.lastIndexOf(";"));
                        }
                        retMap.put("抢救措施",resMedStr);
                    }
                }
            });
        }
    }
    /**
     * 抽取文本中的第一个时间
     *
     * @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;
    }

    /**
     * 时间比较
     *
     * @param startTime,endTime
     * @return
     */
    public static void compareDate(String startTime,String endTime,Map<String, String> retMap) {
        if(StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)){
            return ;
        }
        SimpleDateFormat dateFormatSec = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分");
        try {
                long start = dateFormatSec.parse(startTime).getTime();
                long end = dateFormatSec.parse(endTime).getTime();
                if(start>end){
                    retMap.remove("抢救结束日期时间");
                }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    public static String transHmTime(String time) {
        if(StringUtils.isEmpty(time)){
            return null;
        }

         time = time.replace(".", "-").replace("：", ":").replace("::", ":").replace("于", "").replace("时 ", "时");
        if(time.contains(":")){
            time =   time.replace("时", "").replace("分", "");
        }
        if(time.contains(":") && !time.contains("-")){
           String[] split = time.split(":");
           time =  split[0]+"时"+ split[1]+"分";
       }
        if(time.contains("秒") && time.contains("分")){
            time.substring(time.lastIndexOf("分")+"分".length());
        }
        //完整时间
        if(time.contains("-") && time.contains("时")){
            String hmsDate = time.substring(time.lastIndexOf(extractDate(time))+extractDate(time).length()).trim();
            String filterTime = transDate(extractDate(time));
            return filterTime+" "+hmsDate;
        }
        if(time.contains("-") && time.contains(":")){
            String hmsDate = time.substring(time.lastIndexOf(extractDate(time))+extractDate(time).length()).trim();
            String filterTime = transDate(extractDate(time));
            return filterTime+" "+hmsDate.replace(":","时")+"分";
        }
      return time;
    }
    /**
     * 时间格式转换
     *
     * @param time
     * @return
     */
    public static String transDate(String time) {
        if(StringUtils.isEmpty(time)){
            return null;
        }
        if(time.contains("-")) {
            String[] split = time.split("-");
            time = split[0]+"年"+split[1]+"月"+ split[2]+"日";
        }
        return time;
        }
    }