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.DutyShiftSystemDoc;
import com.lantone.structure.util.MapUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @Description:交接班记录
 * @author: cy
 * @time: 2021/3/01 18:52
 */
@Slf4j
public class DutyShiftSystemTran extends TargetTran {
    @Override
    public Map<String, String> convert(String text) {
        List<DutyShiftSystemDoc> dutyShiftSystemDocs = new ArrayList<>();
        DutyShiftSystemDoc dutyShiftSystemDoc = new DutyShiftSystemDoc();
        dutyShiftSystemDoc.setText(text);
        dutyShiftSystemDocs.add(dutyShiftSystemDoc);
        inputInfo.setDutyShiftSystemDocs(dutyShiftSystemDocs);
        Map<String, String> structureMap = cutWord(text);
        Map<String, String> retMap = new HashMap<String, String>();
        dutyShiftSystemContrast(inputInfo.getDutyShiftSystemDocs(), 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.remove("入院诊断");
            sourceMap.remove("目前诊断");
            sourceMap.remove("查体");
        }
        return sourceMap;
    }


    private List<String> stagesContrasts = Lists.newArrayList(
            "入院日期=入院日期时间",
            "交班日期=交班日期时间",
            "接班日期=接班日期时间",
            "主    诉=主诉",
            "诊治经过=诊疗过程描述",
            "治疗情况=目前情况",
            "交班注意事项=注意事项",
            "诊疗计划=接班诊疗计划"
    );

    public void dutyShiftSystemContrast ( List<DutyShiftSystemDoc> dutyShiftSystemDocs,Map<String, String> retMap) {
        Set<String> sourceList = StreamSovle();
        Set<String> targetSet = new CopyOnWriteArraySet<>();
        List<String> sortList = new ArrayList<>();
        Set<String> deleteSet = new HashSet<>();
        String text = dutyShiftSystemDocs.get(0).getText();
        String fir = text;
        String cureCondition = "";
        //治疗情况
        StringBuilder sb = new StringBuilder();
        if(StringUtil.isNotEmpty(retMap.get("治疗情况"))){
             cureCondition= retMap.get("治疗情况");
            if(cureCondition.contains("查体：")){
                cureCondition = cureCondition.substring(0,cureCondition.lastIndexOf("查体："));
            }
        }else{
            //兼容短文档
            cureCondition = text;
        }
        cureCondition = cureCondition .replace("。","，").replace("：","，");
        //转换为标准关系语句  无发热、头痛-> 无发热、无头痛
        if(cureCondition.contains("，")){
            String[] split = cureCondition.split("，");
            for (String str : split) {
                if(str.contains("、")){
                    String[] splits = str.split("、");
                    Boolean flag = false;
                    for (int i = 0; i < splits.length; i++) {
                        if(i == 0 && splits[0].contains("无")){
                            flag = true;
                            continue;
                        }
                        if(flag && !splits[i].contains("无")){
                            cureCondition = cureCondition.replace(splits[i],"无"+splits[i]);
                        }
                    }
                }
            }
        }

        //标准关系语句
        String keep = cureCondition;
        sourceList.parallelStream().filter(obj->keep.contains(obj) && StringUtil.isNotEmpty(obj)).map(obj->targetSet.add(obj)).collect(Collectors.toList());
        String[] splitStr = {keep};
        if(keep.contains("，")){
            splitStr = keep.split("，");
        }

        for (String str : splitStr) {
            String flagStr = "无";
            if(!str.contains("无") && str.contains("不")){
                flagStr = "不";
            }
            for (String strFir : targetSet) {
                if(str.contains(flagStr) && str.contains(strFir) && ! strFir.contains(flagStr)){
                    //命中不准的关键词删除
                    deleteSet.add(strFir);
                }
                //按照顺序返回关键词
                if(str.contains(strFir)){
                    sortList.add(strFir);
                }
            }
        }
        //包含关系的关键词也进行删除
        for (String strFir : targetSet) {
            for (String strSec : targetSet) {
                if(!strFir.equals(strSec) && strFir.contains(strSec)){
                    deleteSet.add(strSec);
                }
                if(targetSet.size()>1 && "无".equals(strFir)){
                    deleteSet.add("无");
                }
            }
        }

        //List去重
        List<String> tempList = new ArrayList<String>();
        Iterator it = sortList.iterator();
        while(it.hasNext()) {
            String obj = it.next().toString();
            if(!tempList.contains(obj)) {
                tempList.add(obj);
            }
        }
        for (String str : deleteSet) {
            tempList.remove(str);
        }
        for (String str : tempList) {
            sb.append(str+" ");
        }
        if(StringUtil.isNotEmpty(sb.toString())){
            retMap.put("治疗情况",sb.toString());
        }



        if(StringUtil.isNotEmpty(retMap.get("诊疗计划"))){
            String subStr = text.substring(text.indexOf("诊疗计划：")+"诊疗计划：".length());
            String planRet = retMap.get("诊疗计划");
            String planSignDate = "";
            if(subStr.contains("/")){
                planSignDate = parseString(planRet);
                planRet = parseStr(planRet);
            }
            retMap.put("诊疗计划",planRet);
            if(fir.contains("接班记录") && StringUtil.isNotEmpty(planSignDate.trim())){
                retMap.put("接班者签名",planSignDate);
            }
        }

        if(StringUtil.isNotEmpty(retMap.get("交班注意事项"))){
            String subStr = text.substring(text.indexOf("交班注意事项：")+"交班注意事项：".length());
            String planRet = retMap.get("交班注意事项");
            String planSignDate = "";
            if(subStr.contains("/")){
                planSignDate = parseString(planRet);
                 planRet = parseStr(planRet);
            }

            retMap.put("交班注意事项",planRet);
            if(fir.contains("交班记录") && StringUtil.isNotEmpty(planSignDate.trim())){
                    retMap.put("交班者签名",planSignDate);
            }
        }
    }


    public Set<String> StreamSovle() {
        Set<String> sourceList = new HashSet<>();
        try {
            InputStream is = this.getClass().getResourceAsStream("/交接班记录目前情况.txt");
            InputStreamReader in = new InputStreamReader(is);
            BufferedReader bIn = new BufferedReader(in);
            String line = null;
            while ((line = bIn.readLine()) != null) {
                line = line+"\n";
                if(StringUtil.isNotEmpty(line) && StringUtil.isNotEmpty(line.trim())){
                    sourceList.add(line.trim());
                }
            }
            in.close();
            bIn.close();
        }  catch (FileNotFoundException e) {
            e.printStackTrace();
        }  catch (IOException e) {
            e.printStackTrace();
        }
        return sourceList;
    }


    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;
    }
}