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.consultation.ConsultationDoc;
import com.lantone.structure.model.doc.consultation.ConsultationRecordDoc;
import com.lantone.structure.util.MapUtil;
import lombok.extern.slf4j.Slf4j;

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


/**
 * @Description:会诊
 * @author: cy
 * @time: 2021/3/09 09:56
 */
@Slf4j
public class ConsultationTran extends TargetTran {

    @Override
    public Map<String, String> convert(String text) {
        List<ConsultationDoc> consultationDocs = new ArrayList<ConsultationDoc>();
        ConsultationDoc consultationDoc = new ConsultationDoc();
        ConsultationRecordDoc consultationRecordDoc = new ConsultationRecordDoc();
        consultationRecordDoc .setText(text);
        consultationDoc.setConsultationRecordDoc(consultationRecordDoc);
        consultationDocs.add(consultationDoc);
        inputInfo.setConsultationDocs(consultationDocs);
        Map<String, String> structureMap = cutWord(text);
        Map<String, String> retMap = new HashMap<String, String>();
        consultationContrast(inputInfo.getConsultationDocs(), 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);
        if(sourceMap.containsKey("日期") || sourceMap.containsKey("拟会诊日期")){
            sourceMap.remove("日期");
            sourceMap.remove("拟会诊日期");
        }
        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));
            }
        }
    }


    public void consultationContrast( List<ConsultationDoc> consultationDocs, Map<String, String> retMap) {
        if(consultationDocs != null) {
            String text = consultationDocs.get(0).getConsultationRecordDoc().getText();
            if(text.contains("\n")){
                String[] split = text.split("\n");
                for (int i = 0; i < split.length; i++) {
                    String hero = split[i];
                    if(hero.contains("医院") && hero.length()<10){
                        if(StringUtil.isNotEmpty(hero)){
                            retMap.put("会诊医师所在医疗机构名称",hero);
                        }
                    }if(hero.contains("日期：")){
                        String firRet = hero.substring(hero.indexOf("日期：")+"日期：".length());
                        if(StringUtil.isNotEmpty(firRet)){
                            retMap.put("会诊日期时间",firRet);
                        }
                    }
                }
            }
            if(StringUtil.isNotEmpty(retMap.get("会诊日期时间"))){
                String date = retMap.get("会诊日期时间");
                 date = extractDate(date);
                if(StringUtil.isEmpty(date)){
                    retMap.remove("会诊日期时间");
                }
            }
            //会诊医师签名
                String data = "";
                String ret = "";
                if(text.contains("科室：")){
                data = text.substring(text.lastIndexOf("科室：")+"科室：".length());
                    if(data.contains("医师：")){
                        ret = data.substring(data.lastIndexOf("医师：")+"医师：".length());
                    }
            }
            if(StringUtil.isNotEmpty(ret.trim())) {
                retMap.put("会诊医师签名",ret);
            }

            //辅助检查结果
            if(StringUtil.isNotEmpty(retMap.get("其病历简述如下"))) {
                String specical = retMap.get("其病历简述如下");
                String retStr = "";
                if (specical.contains("辅助检查：")) {
                    String[] split = specical.split("辅助检查：");
                    if (split.length > 1) {
                        retStr = split[1];
                    }

                if(StringUtil.isNotEmpty(retStr)){
                    retMap.put("辅助检查结果",retStr);
                }
                }
            }
            //西医诊断名称
            if(StringUtil.isNotEmpty(retMap.get("目前诊断考虑"))) {
                String firStr = retMap.get("目前诊断考虑");
                retMap.put("西医诊断名称",firStr);
            }else{
                if(StringUtil.isNotEmpty(retMap.get("其病历简述如下"))){
                    String specical = retMap.get("其病历简述如下");
                    String retStr = "";
                    if (specical.contains("诊断为：")) {
                         retStr = specical.substring( specical.lastIndexOf("诊断为：")+"诊断为：".length());
                    }
                    if (specical.contains("辅助检查：")) {
                        retStr = retStr.substring(0,retStr.lastIndexOf("辅助检查："));
                    }
                    if(StringUtil.isNotEmpty(retStr)) {
                        retMap.put("西医诊断名称",retStr);
                    }
                }
            }


           // 会诊意见
            if(StringUtil.isEmpty(retMap.get("会诊意见")) && StringUtil.isNotEmpty(retMap.get("会诊结论"))) {
                String result = retMap.get("会诊结论");
                String firStr = text.substring(text.lastIndexOf("会诊结论：")+"会诊结论：".length(), text.lastIndexOf("科室："));
                String tip = "";
                if(firStr.contains("\n")){
                    String[] split = firStr.split("\n");
                    for (int i = 0; i < split.length; i++) {
                       if( split[i].contains("医院")){
                           tip =  split[i];
                       }
                    }
                }
                if(StringUtil.isNotEmpty(tip)){
                    String retData = result.substring(0, result.lastIndexOf(tip));
                    retMap.put("会诊意见",retData);
                }

                    retMap.remove("会诊结论");
            }

            String[] firSplit = text.split("\n");

            //区别
            if(firSplit.length>0){
                String deptStr = "";
                for (int i = 0; i < firSplit.length; i++) {
                    String firStr = firSplit[i];
                    if(firStr.contains("日期")){
                         firStr = firStr.split("日期")[0];
                    }
                    if(firStr.contains("请求")){
                         deptStr = firStr.substring(firStr.indexOf("请求")+"请求".length());
                    }
                    if(deptStr.contains(" ")){
                        String[] split = deptStr.split(" ");
                        if(split.length>=2 && StringUtil.isNotEmpty(deptStr)){
                            deptStr =deptStr.trim();
                        }
                    }

                    if(StringUtil.isNotEmpty(deptStr)){
                        retMap.put("会诊科室名称",deptStr);
                    }
                }

                for (int i = 0; i < firSplit.length-4; i++) {
                    String firStr = firSplit[i];
                    if(firStr.contains("医师:")){
                        String firRet = firStr.substring(0, firStr.indexOf("医师:"));
                        String retStr = "";
                        Boolean flag = true;
                        if(flag && firRet.contains("科")){
                            retStr = firRet.substring(0, firRet.indexOf("科")+"科".length());
                           if(firRet.contains(")")){
                               retStr = firRet.substring(0, firRet.indexOf(")")+")".length());
                            }
                           flag = false;
                        }
                        if( flag && firRet.contains("区")){
                            retStr = firRet.substring(0, firRet.indexOf("区")+"区".length());
                            if(firRet.contains(")")){
                                retStr = firRet.substring(0, firRet.indexOf(")")+")".length());
                            }
                        }
                        if( flag && firRet.contains("房")){
                            retStr = firRet.substring(0, firRet.indexOf("房")+"房".length());
                            if(firRet.contains(")")){
                                retStr = firRet.substring(0, firRet.indexOf(")")+")".length());
                            }
                        }

                        if(StringUtil.isNotEmpty(retStr)) {
                            retMap.put("会诊申请科室",retStr);
                        }
                    }
                }

                if(StringUtil.isNotEmpty(retMap.get("会诊目的")) && StringUtil.isNotEmpty(retMap.get("会诊申请科室")) ){
                    String firStr = retMap.get("会诊目的");
                    String secStr = retMap.get("会诊申请科室");
                    if(firStr.contains(secStr)){
                        String retData = firStr.substring(0, firStr.lastIndexOf(secStr));
                        if(StringUtil.isNotEmpty(retData)){
                            retMap.put("会诊目的",retData);
                        }
                    }
                }

                if(StringUtil.isEmpty(retMap.get("会诊目的")) || StringUtil.isEmpty(retMap.get("会诊理由")) && StringUtil.isNotEmpty(retMap.get("会诊理由及目的"))) {
                    String firStr = retMap.get("会诊理由及目的");
                    String specialName = retMap.get("会诊申请科室");
                    if(StringUtil.isNotEmpty(firStr) && StringUtil.isNotEmpty(specialName) &&  firStr.contains(specialName)){
                         firStr = firStr.substring(0, firStr.lastIndexOf(specialName));
                        retMap.put("会诊目的",firStr);
                        retMap.put("会诊理由",firStr);
                    }

                }
                retMap.remove("会诊理由及目的");
            }

            if(StringUtil.isNotEmpty("日期")){
                retMap.remove("日期");
            }
            if(StringUtil.isNotEmpty("科室")){
                retMap.remove("科室");
            }
            if(StringUtil.isEmpty(retMap.get("会诊意见"))){
                retMap.remove("会诊意见");

            }
            if(StringUtil.isEmpty(retMap.get("会诊结论"))){
                retMap.remove("会诊结论");
            }
            //===============兼容模板===================
                if(text.contains("科室:") && text.contains("床号:")){
                    String subStr = text.substring(text.indexOf("科室:") + "科室:".length(), text.indexOf("床号:"));
                    if(StringUtil.isNotEmpty(subStr)) {
                        retMap.put("会诊申请科室",subStr);
                    }
                }

            if(StringUtil.isNotEmpty(retMap.get("申请医师签名"))){
                String sign = retMap.get("申请医师签名");
                if(sign.contains("会诊")){
                    sign = sign.substring(0, sign.lastIndexOf("会诊"));
                    if(StringUtil.isNotEmpty(sign)){
                        retMap.put("申请医师签名",sign);
                    }else{
                        retMap.remove("申请医师签名");
                    }
                }
            }

            if(StringUtil.isEmpty(retMap.get("会诊医师签名")) || StringUtil.isEmpty(retMap.get("会诊医师签名").trim())){
                retMap.remove("会诊医师签名");
            }

            if(StringUtil.isNotEmpty(retMap.get("会诊时间"))){
                String date = retMap.get("会诊时间");
                String dateRet = extractDate(date);
                if(StringUtil.isNotEmpty(dateRet)){
                    retMap.put("会诊时间",dateRet);
                }else{
                    retMap.remove("会诊时间");
                }
            }
            if(StringUtil.isNotEmpty(retMap.get("目前诊断"))){
                String strFir = retMap.get("病历摘要及诊疗经过");
                String str = retMap.get("目前诊断");
                String strThr = retMap.get("其他科情况");
                if(StringUtil.isNotEmpty(str) && StringUtil.isNotEmpty(strThr)){
                    strFir = strFir+str+strThr;
                }else{
                    if(StringUtil.isNotEmpty(str)&& StringUtil.isEmpty(strThr)){
                        strFir = strFir+str;
                    }
                    if(StringUtil.isEmpty(str)&& StringUtil.isNotEmpty(strThr)){
                        strFir = strFir+strThr;
                    }
                }
                retMap.put("病历摘要及诊疗经过",strFir);
                if(str.contains("、")){
                    String[] split = str.split("、");
                    for (int i = 1; i < split.length; i++) {
                       String retStr = split[i].trim();
                       Boolean flag = false;
                        try {
                            String strInt = String.valueOf(retStr.charAt(retStr.length() - 1));
                            int num = Integer.parseInt(strInt);
                            flag = true;
                        } catch (Exception e) {
                            log.error(e.getMessage());
                        }
                        if(!flag){
                            String flagRet = split[i - 1];
                            String sub = str.substring(str.indexOf(flagRet));
                            if(sub.contains("。")){
                                String flagFir = sub.split("。")[0];
                                 flagFir = str.substring(0, str.indexOf(flagFir) + flagFir.length());
                                retMap.put("目前诊断",flagFir);
                            }
                            break;
                        }
                    }
                }
            }

            if(StringUtil.isNotEmpty(retMap.get("病历摘要及诊疗经过"))){
                String firStr = retMap.get("病历摘要及诊疗经过");
                if(StringUtil.isNotEmpty(retMap.get("目前诊断"))){
                    String caseStr = retMap.get("目前诊断");
                    if(firStr.contains(caseStr)){
                        String subStr= firStr.substring(firStr.lastIndexOf(caseStr) + caseStr.length() + 1);
                        if(StringUtil.isNotEmpty(subStr)){
                            retMap.put("诊疗过程描述",subStr);
                        }
                    }
                }
            }
            if(StringUtil.isNotEmpty(retMap.get("邀请"))){
                String interFace = retMap.get("邀请");
                String falgFir = interFace;
                String retStr = "";
                if(interFace.contains("医院")){
                    interFace = interFace.substring(0, interFace.lastIndexOf("医院")+"医院".length());
                    falgFir = falgFir.substring(falgFir.lastIndexOf("医院")+"医院".length());
                }
                if( falgFir.contains("科")){
                    retStr = falgFir.substring(0, falgFir.indexOf("科")+"科".length());
                    if(falgFir.contains(")")){
                        retStr = falgFir.substring(0, falgFir.indexOf(")")+")".length());
                    }
                }
                if( falgFir.contains("区")){
                    retStr = falgFir.substring(0, falgFir.indexOf("科")+"科".length());
                    if(falgFir.contains(")")){
                        retStr = falgFir.substring(0, falgFir.indexOf(")")+")".length());
                    }
                }
                if( falgFir.contains("房")){
                    retStr = falgFir.substring(0, falgFir.indexOf("科")+"科".length());
                    if(falgFir.contains(")")){
                        retStr = falgFir.substring(0, falgFir.indexOf(")")+")".length());
                    }
                }
                if(StringUtil.isNotEmpty(retStr)) {
                    retMap.put("会诊科室名称",retStr);
                }
                if(StringUtil.isNotEmpty(interFace)) {
                    retMap.put("会诊医师所在医疗机构名称",interFace);
                }
            }
              retMap.remove("邀请");
            retMap.remove("其他科情况");
        }
    }

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