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.DifficultCaseDiscussDoc;
import com.lantone.structure.util.MapUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;

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

/**
 * @Description:疑难病例讨论记录
 * @author: cy
 * @time: 2021/3/02 09:53
 */
@Slf4j
public class DifficultCaseDiscussTran extends TargetTran {
    @Override
    public Map<String, String> convert(String text) {
        List<DifficultCaseDiscussDoc> difficultCaseDiscussDocs = new ArrayList<>();
        DifficultCaseDiscussDoc difficultCaseDiscussDoc = new DifficultCaseDiscussDoc();
        difficultCaseDiscussDoc.setText(text);
        difficultCaseDiscussDocs.add(difficultCaseDiscussDoc);
        inputInfo.setDifficultCaseDiscussDocs(difficultCaseDiscussDocs);
        Map<String, String> structureMap = cutWord(text);
        Map<String, String> retMap = new HashMap<String, String>();
        dDContrast(inputInfo.getDifficultCaseDiscussDocs(), 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.remove("汇报");
        }
        return sourceMap;
    }


    private List<String> stagesContrasts = Lists.newArrayList(
            "讨论时间=讨论日期时间",
            "讨论主持人=主持人姓名",
            "讨论摘要=讨论意见",
            "参加人员=参加讨论人员名单",
            "主持人总结=主持人总结意见"
    );

    public void dDContrast ( List<DifficultCaseDiscussDoc> difficultCaseDiscussDocs,Map<String, String> retMap) {
        String text = difficultCaseDiscussDocs.get(0).getText();

        //主持人姓名去职称
        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.isNotEmpty(retMap.get("主持人总结"))){
            String dirSum = retMap.get("主持人总结");
            if(dirSum.contains("主持人（签名）")){
                String substring = dirSum.substring(0, dirSum.lastIndexOf("主持人（签名）"));
                if(StringUtil.isNotEmpty(substring)){
                    retMap.put("主持人总结",substring);
                }
            }
        }

        if(StringUtil.isNotEmpty(retMap.get("参加人员"))){
            String fir = text.substring(text.indexOf("参加人员：")+5, 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("  ");
            }
            retMap.put("参加人员",sb.toString());
        }

        String trueRet = "";
        if(text.contains("主持人（签名）") && text.contains("记录者（签名）")){
            trueRet = text.substring( text.indexOf("主持人（签名）")+7, text.indexOf("记录者（签名）")).trim();
        }
        if(StringUtil.isNotEmpty(trueRet)){
            retMap.put("主任医师签名",trueRet);
        }

        if(text.contains(" 记录者（签名）")){
          String  record = text.substring(text.indexOf("记录者（签名）")+7);
            StringBuffer sb = new StringBuffer();

            String[] split = record.split(" ");
            sb.append(split[0].trim()).append(split[1].trim()).append(split[2].trim());
            if(StringUtil.isNotEmpty(sb.toString())){
            retMap.put("主治医师签名",sb.toString());
           }
        }
    }

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

    /**
     * 抽取文本中的最后时间
     *
     * @param top
     * @return
     */
    public static String lastTime(String top) {
        int length = top.trim().length();
        String substring = top.trim().substring(length - 22, length);
        String stringDate = "";
        if( substring.contains("年")){
            String[] time = substring.split("年");
            String timeYear = time[0].trim();
            timeYear = extractDate(timeYear);
            if( substring.contains("月")){
                String[] timeLater = time[1].split("月");
                String timeMouth = timeLater[0].trim();
                if(substring.contains("日")){
                    String[] timeLast = timeLater[1].split("日");
                    String timeDate = timeLast[0].trim();
                    if(StringUtil.isNotEmpty(timeYear) && StringUtil.isNotEmpty(timeMouth) && StringUtil.isNotEmpty(timeDate)){
                        stringDate = timeYear + "年" + timeMouth + "月" + timeDate + "日" ;
                    }
                }
            }
        }
        Date date = null;
        try {
            date = DateUtils.parseDate(stringDate, StringUtil.dateFormats);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        if(date!= null){
            return stringDate;
        }else{
            return "";
        }
    }

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