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.operation.OperationDoc;
import com.lantone.structure.model.doc.operation.PreoperativeDiscussionDoc;
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/2/26 14:52
 */
@Slf4j
public class PreoperativeDiscussionTran extends TargetTran {

    @Override
    public Map<String, String> convert(String text) {
         List<OperationDoc> operationDocs = new ArrayList<>();
        OperationDoc operationDoc = new OperationDoc();
        PreoperativeDiscussionDoc preoperativeDiscussionDoc = new  PreoperativeDiscussionDoc();
        preoperativeDiscussionDoc.setText(text);
        operationDoc.setPreoperativeDiscussionDoc(preoperativeDiscussionDoc);
        operationDocs.add(operationDoc);
        inputInfo.setOperationDocs(operationDocs);
        Map<String, String> structureMap = new HashMap<String, String>();
        Map<String, String> retMap = new HashMap<String, String>();
        Boolean falg = false;
        String file = text.split("\n")[0];
        //术前小结-术前讨论
        if(file.contains("讨论记录") || file.contains("术前讨论")){
            structureMap = cutWordRe(text);
            falg = true;
        }else{
            structureMap = cutWord(text);
        }
        pDContrast(falg,inputInfo.getOperationDocs(), structureMap);
        mapKeyContrastCommon(structureMap,stagesContrasts,retMap);
        preoperativeDiscussionDoc.setStructureMap(retMap);
        aiProcess();
        lastSovle(inputInfo.getOperationDocs(),retMap);
        return retMap;
    }

    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.containsKey("其他术前相关情况")
        || sourceMap.containsKey("一般情况") || sourceMap.containsKey("目前服用的药物") || sourceMap.containsKey("诊疗计划")){
            sourceMap.remove("术前诊断");
            sourceMap.remove("月经史");
            sourceMap.remove("一般情况");
            sourceMap.remove("其他术前相关情况");
            sourceMap.remove("目前服用的药物");
            sourceMap.remove("诊疗计划");
        }
        return sourceMap;
    }

    private Map<String, String> cutWordRe(String text) {
        Map<String, String> sourceMap = Maps.newHashMap();
        List<String> titleReplace = CommonAnalysisUtil.sortTitles(
                Lists.newArrayList("讨论时间","讨论地点","讨论主持人","参加人员","参加讨论人员","情况如下","术前诊断","讨论摘要","主持人总结","医师总结"),
                text
        );
        CommonAnalysisUtil.cutByTitles(text, titleReplace, 0, sourceMap);
        if(sourceMap.containsKey("术前诊断")){
            sourceMap.remove("术前诊断");
        }
        return sourceMap;
    }



    private List<String> stagesContrasts = Lists.newArrayList(
            "讨论时间=讨论日期时间",
            "讨论主持人=主持人姓名",
            "手术指征=手术指征",
            "手术指征=手术适应证",
            "手术禁忌=手术禁忌症",
            "参加人员=参加讨论人员名单",
            "拟实施手术名称=拟实施手术及操作名称",
            "拟施手术名称和方式=拟实施手术及操作名称",
            "防范措施=注意事项",
            "防范措施=手术要点",
            "主持人总结=讨论结论",
            "讨论摘要=讨论意见",
            "手术审批医师=手术者签名",
            "药物、食物过敏史=过敏史"
    );

    public void pDContrast(Boolean flag,List<OperationDoc> operationDocs,Map<String, String> retMap) {
        String text = operationDocs.get(0).getPreoperativeDiscussionDoc().getText();
        if(flag == false){
        //小结日期时间
            if(text.contains("简要病情")){
                String caseFile = text.substring(0,text.indexOf("简要病情："));
                String sumdDate = extractDate(caseFile);
                if(StringUtil.isNotEmpty(sumdDate)){
                    retMap.put("小结日期时间",sumdDate);
                }
            }


        //病历摘要   诊断依据
        if(StringUtil.isNotEmpty(retMap.get("简要病情"))) {
            String simCaseRet = retMap.get("简要病情");
            retMap.put("病历摘要",simCaseRet);
            retMap.put("诊断依据",simCaseRet);
            if(StringUtil.isNotEmpty(retMap.get("入院后辅助检查"))) {
                retMap.put("病历摘要",simCaseRet+" "+"入院后辅助检查:"+retMap.get("入院后辅助检查"));
            }
        }

    //辅助检查结果
        if(StringUtil.isNotEmpty(retMap.get("简要病情"))) {
            String simCase = retMap.get("简要病情");
            String helpSee = "";
            if(simCase.contains("辅助检查：")) {
                 helpSee = simCase.substring(simCase.indexOf("辅助检查：")+5);
                retMap.put("辅助检查结果",helpSee);
            }
            if(StringUtil.isNotEmpty(retMap.get("入院后辅助检查"))) {
                retMap.put("辅助检查结果",helpSee+" "+"入院后辅助检查:"+retMap.get("入院后辅助检查"));
            }
        }
        if(StringUtil.isNotEmpty(retMap.get("简要病情"))) {
            retMap.remove("简要病情");
        }
        if(StringUtil.isNotEmpty(retMap.get("入院后辅助检查"))) {
            retMap.remove("入院后辅助检查");
        }

        //手术禁忌
        if(text.contains("手术禁忌：")) {
            String opration = text.substring(text.indexOf("手术禁忌：") + 5);
            String s = opration.split("\n")[0];
            retMap.put("手术禁忌",s);
        }

        //手术指征
        if(text.contains("手术指征：")) {
            String opration = text.substring(text.indexOf("手术指征：") + 5);
            if(opration.contains("拟实施手术名称")){
                   opration = opration.substring(0,opration.indexOf("拟实施手术名称"));
            }
            if(opration.contains("主刀医生")){
                opration = opration.substring(0,opration.indexOf("主刀医生"));
            }
            String[] split = opration.split("\n");
            if(StringUtil.isNotEmpty(split[0])){
                retMap.put("手术指征",split[0]);
            }
        }

        //拟实施手术及操作日期时间
        if(text.contains("拟定于")) {
            String opration = text.substring(text.indexOf("拟定于"));
            String date = extractDate(opration);
            retMap.put("拟实施手术及操作日期时间",date);
        }

        //手术审批医师
        String oprationDoc = "";
        if(text.contains("手术审批医师：")){
             oprationDoc =  text.substring(text.indexOf("手术审批医师：" )+ 7).trim();
        }
        if(StringUtil.isEmpty(retMap.get("手术审批医师"))) {
            String oprationSign = "";
            if(oprationDoc.contains("医师签名")){
                 oprationSign = text.substring(text.indexOf("手术审批医师：") + 7, text.indexOf("医师签名")).trim();
            }else{
                if(oprationDoc.contains("年") ||oprationDoc.contains( "-")){
                    String subStr= text.substring(text.indexOf("手术审批医师：")+7);
                    oprationSign = subStr.split("\n")[0].trim();
                }
            }
                retMap.put("手术审批医师",oprationSign);
        }else{
            String trim = "";
            if(oprationDoc.contains("医师签名")){
                trim = oprationDoc.substring(0, oprationDoc.indexOf("医师签名")).trim();
            }else{
                trim = oprationDoc.split("\n")[0].trim();
            }
            if(StringUtil.isNotEmpty(trim) && (trim.contains("年") || trim.contains("-"))){
                String trimDate = extractDate(trim);
                if(StringUtil.isNotEmpty(trimDate)){
                    trim = oprationDoc.substring(0, oprationDoc.indexOf(trim)).trim();
                }else{
                    trim = oprationDoc.substring(0, oprationDoc.indexOf("年")).trim();
                }
            }
                retMap.put("手术审批医师",trim);

            if(StringUtil.isEmpty(retMap.get("手术审批医师").trim())){
                retMap.remove("手术审批医师");
            }

        }

        //医师签名
        if(text.contains("医师签名：")) {
            String sign =  text.substring(text.indexOf("医师签名：")+5).trim();
            if(sign.contains("年") ||sign.contains( "-")){
                String subStr= text.substring(text.indexOf("医师签名：")+5);
                sign = subStr.split("\n")[0].trim();
            }
            if(StringUtil.isNotEmpty(sign)){
                retMap.put("医师签名",sign);
            }else{
                retMap.remove("医师签名");
            }
        }
        String date = "";
        String sub = "";
        if(text.contains("手术审批医师：")){
             sub = text.substring(text.lastIndexOf("手术审批医师："));
        }else{
            if(text.contains("诊疗计划：")){
             sub = text.substring(text.lastIndexOf("诊疗计划："));
            }
        }
        date = extractDate(sub);
        if(StringUtil.isNotEmpty(date)){
            retMap.put("签名日期时间",date);
        }

            StringBuffer sbx = new StringBuffer();
            if(StringUtil.isNotEmpty(retMap.get("拟实施手术名称"))){
                String plan = retMap.get("拟实施手术名称");
                sbx.append("拟实施手术名称:"+plan+" ");
            }
            if(StringUtil.isNotEmpty(retMap.get("手术方式"))){
                String plan = retMap.get("手术方式");
                sbx.append("手术方式:"+plan+" ");
            }
            if(StringUtil.isNotEmpty(retMap.get("拟实施麻醉方式"))){
                String plan = retMap.get("拟实施麻醉方式");
                sbx.append("拟实施麻醉方式:"+plan+" ");
            }
            if(StringUtil.isNotEmpty(sbx.toString())){
                retMap.put("手术方案",sbx.toString());
            }
        }

//        ===========================术前讨论===================================

/*
        if(text.contains("\n")){
            String[] split = text.split("\n");
            for (int i = 0; i < split.length-1; i++) {
                if(i == 0 && split[i].contains("讨论记录")){
                   flag = true;

                   break;
                    }
                }
            }
*/

        //参加人员
        if(flag){
            //主持人姓名去职称
            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;
                    }
                }
            }

            if(StringUtil.isEmpty(retMap.get("讨论摘要"))){
                if(StringUtil.isNotEmpty(retMap.get("情况如下"))){
                    String caseFir = retMap.get("情况如下");
                    if(caseFir.contains("医师：")){
                        String flagCase = caseFir.split("医师：")[1];
                        if(flagCase.contains("：")){
                            flagCase = caseFir.split("：")[0];
                            if(flagCase.contains("。")){
                                flagCase = caseFir.substring(0,caseFir.lastIndexOf("。"));
                            }
                        }
                        if(StringUtil.isNotEmpty(flagCase)){
                            retMap.put("讨论摘要",flagCase);
                        }
                    }
                }
            }
                String fir = "";
                if(StringUtil.isNotEmpty(retMap.get("参加人员"))){
                    fir = text.substring(text.indexOf("参加人员：")+"参加人员：".length(), text.lastIndexOf("汇报病史"));
                }
                if(StringUtil.isNotEmpty(retMap.get("参加讨论人员"))){
                    retMap.remove("参加讨论人员");
                    fir = text.substring(text.indexOf("参加讨论人员：")+"参加讨论人员：".length(), text.lastIndexOf("情况如下："));
                }
                String[] split = fir.split("\n");
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < split.length-1; i++) {
                    sb.append(split[i]).append("  ");
                }
            if(StringUtil.isNotEmpty(sb.toString())){
                retMap.put("参加人员",sb.toString());
            }

            if(StringUtil.isNotEmpty(retMap.get("主持人总结"))||StringUtil.isNotEmpty(retMap.get("医师总结"))){
                String dirSum = retMap.get("主持人总结");
                if(StringUtil.isEmpty(dirSum)){
                    dirSum = retMap.get("医师总结");
                }
                String date = extractDate(dirSum);
                String signName = "";
                if(dirSum.contains("记录者（签名）")){
                    signName = dirSum.substring(dirSum.lastIndexOf("记录者（签名）")+"记录者（签名）".length());
                }
                if (StringUtil.isNotEmpty(date)) {
                    retMap.put("签名日期时间",date);
                    if( signName.contains(date)){
                        signName = signName.substring(0, signName.lastIndexOf(date));
                    }
                }
                if (StringUtil.isNotEmpty(signName) && StringUtil.isNotEmpty(signName.trim())) {
                    retMap.put("医师签名",signName);
                }
                if(dirSum.contains("主持人（签名）")){
                    dirSum = dirSum.substring(0, dirSum.lastIndexOf("主持人（签名）"));
                }
                if(dirSum.contains("主持人：")){
                    dirSum = dirSum.substring(0, dirSum.lastIndexOf("主持人："));
                }
                retMap.put("主持人总结",dirSum);
            }
            retMap.remove("参加讨论人员");
            retMap.remove("情况如下");
            retMap.remove("医师总结");
        }
        retMap.remove("手术方式");
        retMap.remove("拟实施麻醉方式");
        retMap.remove("拟施麻醉方式");
    }

    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}[-][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<OperationDoc> operationDocs , Map<String,String> rep) {
        if(!operationDocs.isEmpty() && operationDocs.get(0)!=null && operationDocs.get(0)
                .getPreoperativeDiscussionDoc()!=null&& operationDocs.get(0)
                .getPreoperativeDiscussionDoc().getPreoperativeDiscussionLabel()!=null){
            PreoperativeDiscussionDoc preoperativeDiscussionDoc = operationDocs.get(0).getPreoperativeDiscussionDoc();
            String allergyRecord = preoperativeDiscussionDoc.getPreoperativeDiscussionLabel().getAllergyRecord();
            String opBottomName = preoperativeDiscussionDoc.getPreoperativeDiscussionLabel().getOpBottomName();
            String opContraindication = preoperativeDiscussionDoc.getPreoperativeDiscussionLabel().getOpContraindication();
            if(StringUtil.isEmpty(rep.get("药物、食物过敏史")) && StringUtil.isNotEmpty(allergyRecord)){
                rep.put("过敏史",allergyRecord);
            }
            if(StringUtil.isNotEmpty(opBottomName)){
                rep.put("拟实施手术目标部位名称",opBottomName);
            }
            if(StringUtil.isEmpty(rep.get("手术禁忌症")) && StringUtil.isNotEmpty(opContraindication)){
                rep.put("手术禁忌症",opContraindication);
            }
        }
    }
}