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.transferrecord.TransferRecordDoc;
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/01 16:50
 */
@Slf4j
public class TransferRecordTran extends TargetTran {
    @Override
    public Map<String, String> convert(String text) {
        TransferRecordDoc transferRecordDocs = new TransferRecordDoc();
        transferRecordDocs.setText(text);
        inputInfo.setTransferRecordDocs(transferRecordDocs);
        Map<String, String> structureMap = cutWord(text);
        Map<String, String> retMap = new HashMap<String, String>();
        transferRecordContrast(inputInfo.getTransferRecordDocs(), structureMap);
        mapKeyContrastCommon(structureMap,stagesContrasts,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.remove("入院诊断");
            sourceMap.remove("目前诊断");
            sourceMap.remove("转入诊断");
            sourceMap.remove("签名时间");
            sourceMap.remove("患者或代理人签名");
        }
        return sourceMap;
    }


    private List<String> stagesContrasts = Lists.newArrayList(
            "简要病情=入院情况",
            "诊疗经过=诊疗过程描述",
            "转科理由=转科目的",
            "转科目的及其注意事项=转科目的",
            "转科目的及其注意事项=注意事项",
            "防范措施=注意事项",
            "防范措施=手术要点",
            "医生签名=转出医师签名",
            "下一步治疗方案=转入诊疗计划"
    );

    public void transferRecordContrast (TransferRecordDoc transferRecordDocs,Map<String, String> retMap) {
        //转入日期时间取第一时间
        String text = transferRecordDocs.getText();
        String fileName = "转入记录";
        if(text.contains("转科记录")){
            fileName = "转科记录";
        }
        String[] split = text.split(fileName);
        String fir = split[0]+fileName;
        String planText = "";
        if(text.contains("转入诊疗计划：")){
            planText = text.substring( text.indexOf("转入诊疗计划："));
        }
        if(text.contains("下一步治疗方案：")){
            planText = text.substring( text.indexOf("下一步治疗方案："));
        }

        if(!(text.contains("简要病情") || text.contains("入院情况"))){
            if(text.contains("入院诊断") && (StringUtil.isEmpty(retMap.get("入院情况")) || StringUtil.isEmpty(
                    retMap.get("简要病情")))){
                String ret = text.substring( text.indexOf(fir)+fir.length(),text.lastIndexOf("入院诊断"));
                retMap.put("入院情况",ret);
            }
        }

        if(fir.contains("转入记录")){
            String date = extractDate(fir);
            if(StringUtil.isNotEmpty(date)){
                retMap.put("转入日期时间",date);
            }
        }
        if(StringUtil.isNotEmpty(retMap.get("医生签名"))){
            String signName = retMap.get("医生签名");
            if(signName.contains("签名时间")){
                retMap.remove("医生签名");
                signName = signName.substring(0, signName.lastIndexOf("签名时间"));
                if(StringUtil.isNotEmpty(signName)){
                    retMap.put("医生签名",signName);
                }
            }
        }

        if(fir.contains("转科记录")){
            if(StringUtil.isNotEmpty(retMap.get("转出日期"))){
                 fir = retMap.get("转出日期");
                String date = extractDate(fir);
            if(StringUtil.isNotEmpty(date)){
                retMap.put("转出日期时间",date);
                retMap.remove("转出日期");
            }
            }
        }

        String innerSignName = parseString(planText);
        if(StringUtil.isNotEmpty(innerSignName.trim()) && planText.contains("/")){
            retMap.put("转入医师签名",innerSignName.trim());
        }

        if(text.contains("转入诊疗计划：")){
            String inFir = text.substring(text.indexOf("转入诊疗计划：") + 7);
            String innerPlanRet = inFir.split("\n")[0];
            if(innerPlanRet.contains("/")){
                innerPlanRet = parseStr(innerPlanRet);
            }
            retMap.put("转入诊疗计划",innerPlanRet);
        }

        if(text.contains("下一步治疗方案：") && StringUtil.isEmpty(retMap.get("转入诊疗计划"))){
            String  plan = text.substring( text.indexOf("下一步治疗方案：")+"下一步治疗方案：".length());
            String planRet = plan.split("\n")[0];
            if(planRet.contains("/")){
                planRet = parseStr(planRet);
            }
            retMap.put("下一步治疗方案",planRet);
        }

        if(StringUtil.isNotEmpty(retMap.get("医生签名"))){
            String innerPlan = retMap.get("医生签名").trim();
            if(StringUtil.isEmpty(innerPlan)){
                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 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;
    }
}