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.ThreeLevelWardDoc;
import com.lantone.structure.model.label.ThreeLevelWardLabel;
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: cy
 * @time: 2021/2/20 14:07
 */
@Slf4j
public class ThreeLevelWardTran extends TargetTran {

    @Override
    public Map<String, String> convert(String text) {
        List<ThreeLevelWardDoc> wardRecordDocList = new ArrayList<>();
        ThreeLevelWardDoc wardRecordDoc = new ThreeLevelWardDoc();
        wardRecordDoc.setText(text);
        wardRecordDocList.add(wardRecordDoc);
        inputInfo.setThreeLevelWardDocs(wardRecordDocList);
        Map<String, String> structureMap = cutWord(text);
        wardRecordContrast(inputInfo.getThreeLevelWardDocs(), structureMap);
        wardRecordDoc.setStructureMap(structureMap);
        aiProcess();
        lastSovle(inputInfo.getThreeLevelWardDocs(),structureMap);
        return structureMap;
    }

    private Map<String, String> cutWord(String text) {
        Map<String, String> sourceMap = Maps.newHashMap();
        List<String> titles = CommonAnalysisUtil.sortTitles(
                Lists.newArrayList("鉴别诊断","诊疗计划","诊断考虑","补充诊断","Caprini评分为","注意事项"),
                text
        );
        CommonAnalysisUtil.cutByTitles(text, titles, 0, sourceMap);
        sourceMap.entrySet().removeIf(entry -> entry.getKey().equals("鉴别诊断") || entry.getKey().equals("补充诊断") || entry.getKey().equals("注意事项") || entry.getKey().equals("Caprini评分为") || entry.getKey().equals("诊断考虑"));
        return sourceMap;
    }


    public void wardRecordContrast( List<ThreeLevelWardDoc> wardRecordDoc,Map<String, String> retMap) {
        String text = wardRecordDoc.get(0).getText();
        String fir = text;
        //查房日期时间
        String sumdDate = extractDate(text);
        if(StringUtil.isNotEmpty(sumdDate)){
            retMap.put("查房日期时间",sumdDate);
        }

        String signName= parseString(text);
        if(StringUtil.isNotEmpty(signName) && StringUtil.isNotEmpty(signName.trim()) && signName.length()<15){
            retMap.put("记录人签名",signName);
        }

        if(StringUtil.isNotEmpty(sumdDate)){
            String[] split = text.split(sumdDate);
            fir = text.substring(text.lastIndexOf(split[1]));
            String[] notes = fir.split("查房记录");
            if(notes.length<=1){
                notes = fir.split("日常查房");
            }
            if(notes.length<=1){
                notes = fir.split("查房录");
            }
            if(notes.length<=1){
                notes = fir.split("医师查房");
            }
            fir = fir.substring(fir.lastIndexOf(notes[1]));
        }

        if( StringUtil.isNotEmpty(signName.trim()) && signName.length()<15){
            fir = fir.substring(0,fir.lastIndexOf(signName));
            String flag  = "/";
            if(fir.endsWith("//")){
                flag = "//";
            }
            fir = fir.substring(0,fir.lastIndexOf(flag));
        }

        if(StringUtil.isNotEmpty(fir)){
            retMap.put("查房记录",fir);
        }

        //规则诊疗计划
        if(StringUtil.isNotEmpty(retMap.get("诊疗计划"))){
            String plan = retMap.get("诊疗计划");
            if(StringUtil.isNotEmpty( retMap.get("记录人签名")) && StringUtil.isNotEmpty( retMap.get("记录人签名").trim())){
                String name = retMap.get("记录人签名").trim();
                if(plan.contains(name)){
                plan = plan.substring(0,plan.lastIndexOf(name));
                }
                if(plan.endsWith("今予")){
                    plan = plan.substring(0,plan.lastIndexOf("今予"));
                }
            }
            if(plan.contains("诊断考虑：")){
                plan = plan.substring(0,plan.lastIndexOf("诊断考虑："));
            }
            if(plan.contains("VTE风险评估")){
                plan = plan.substring(0,plan.lastIndexOf("。")+"。".length());
            }
            String flag  = "/";
            if(fir.endsWith("//")){
                flag = "//";
            }
            if(plan.endsWith(flag)){
                plan = plan.substring(0,plan.lastIndexOf(flag));
            }
            if(plan.endsWith("，")){
                plan = plan.substring(0,plan.lastIndexOf("，"));
            }
               retMap.put("诊疗计划",plan);
           }

        //内涵诊疗计划
        if(StringUtil.isEmpty(retMap.get("诊疗计划"))){
            text = text.replace("处理意见:","处理意见：").replace("诊疗意见：","处理意见：")
                       .replace("处理方案：","处理意见：").replace("查房记录：","查房认为")
                       .replace("查房示：","查房认为")  .replace("查房后示：","查房认为")
                       .replace("分析病情示：","查房认为")  .replace("查房分析指出","查房认为")
                       .replace("查房后分析指出","查房认为") .replace("查房后分析","查房认为")
                       .replace("查房分析","查房认为")  .replace("今查房示","查房认为")
                       .replace("医师查看","查房认为") ;
            String sFir = "";
            List<String> subPlanList = Arrays.asList(
                    "治疗计划：","分析指出：","处理意见：","查房认为","指出", "认为"//不包含
                     );
            //包含
            List<String> containList = Arrays.asList(
                 "予查","予复查","后予以", "治疗上", "拟明","目前继续","继续目前","。继续","，继续","；继续","今继续","余继续","术后继续",
                   "患者现病情","患者目前病情" ,"病情较前好转","较前明显好转","一般情况可","定期监测","患者目前咳嗽","可先行"
            );

            List<String> indexList = Arrays.asList(
                    "，","：","，","。"
            );
            List<String> endStrs = Arrays.asList(
                    "注意事项：","今日镇静镇痛评分" //"补充诊断：","予补充诊断：",
            );
            Boolean flag = true;
            for (String str : subPlanList) {
                if(text.contains(str)){
                    flag = false;
                    sFir = text.substring(text.lastIndexOf(str)+str.length());
                    break;
                }
            }

             if(flag){
                 for (String conStr : containList) {
                     if(text.contains(conStr)){
                         sFir = text.substring(text.lastIndexOf(conStr));
                         break;
                     }
                 }
             }

            for (String str : indexList) {
                if(sFir.startsWith(str)){
                    sFir = sFir.substring(1);
                    break;
                }
            }
            for (String endStr : endStrs) {
                if(sFir.contains(endStr)){
                    sFir = sFir.split(endStr)[0];
                }
            }
            String name = retMap.get("记录人签名");
            if(StringUtils.isNotEmpty(name) && sFir.contains(name)){
                sFir = sFir.substring(0,sFir.lastIndexOf(name));
            }
            String endFlag  = "/";
            if(fir.endsWith("//")){
                endFlag = "//";
            }
            if(sFir.endsWith(endFlag)){
                sFir = sFir.substring(0,sFir.lastIndexOf(endFlag));
            }

            retMap.put("诊疗计划",sFir);
        }
        }

    // 取/后
    public static String parseString(String text){
        if(text.contains("/")){
            text = text.substring(text.lastIndexOf("/")+1);
            text= parseString(text);
        }
        return text;
    }

    // 取/前
    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;
    }

    public static void lastSovle(List<ThreeLevelWardDoc> threeLevelWardDocs, Map<String,String> structureMap) {
        if(ListUtil.isNotEmpty(threeLevelWardDocs) && threeLevelWardDocs.get(0)!=null && threeLevelWardDocs.get(0)
                .getThreeLevelWardLabel().size()>0 && threeLevelWardDocs.get(0).getThreeLevelWardLabel().get(0)!=null){
            ThreeLevelWardLabel threeLevelWardLabel = threeLevelWardDocs.get(0).getThreeLevelWardLabel().get(0);
            String doctorAdviceRecord = threeLevelWardLabel.getDoctorAdviceRecord();
            if(StringUtil.isNotEmpty(doctorAdviceRecord)){
                structureMap.put("医嘱内容",doctorAdviceRecord);
            }
        }
    }
}