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.InformedConsentDoc;
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/10 10:12
 */
@Slf4j
public class InformedConsentTran extends TargetTran {

    @Override
    public Map<String, String> convert(String text) {
        InformedConsentDoc informedConsentDoc = new InformedConsentDoc();
        informedConsentDoc .setText(text);
        inputInfo.setInformedConsentDoc(informedConsentDoc);
        Map<String, String> structureMap = cutWord(text);
        Map<String, String> retMap = new HashMap<String, String>();
        informedConsentContrast(inputInfo.getInformedConsentDoc(), 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.containsKey("医师签名")
                || sourceMap.containsKey("住院号")|| sourceMap.containsKey("住院号码")|| sourceMap.containsKey("病历号")){
            sourceMap.remove("联系地址");
            sourceMap.remove("医生签字");
            sourceMap.remove("医师签名");
            sourceMap.remove("住院号");
            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 informedConsentContrast( InformedConsentDoc informedConsentDoc, Map<String, String> retMap) {
        if(informedConsentDoc != null) {
            String text = informedConsentDoc.getText();
            String flag = " ";
            if (text.contains("\n")) {
                String[] split = text.split("\n");
                for (int i = 0; i < split.length; i++) {
                    String hero = split[i];
                    if(i == 0 ){
                        if (!hero.contains(flag)) {
                            flag = "_";
                        }
                    if ( hero.contains(flag)) {
                        String[] motton = hero.split(flag);
                        String firStr = motton[0];
                        String secStr = "";
                        if (StringUtil.isNotEmpty(firStr)) {
                             secStr = hero.substring(hero.lastIndexOf(firStr) + firStr.length());
                            if(firStr.contains("_")){
                                 firStr = firStr.substring(0, firStr.lastIndexOf("_"));
                            }
                            if(secStr.contains("_")){
                                secStr = secStr.substring(secStr.lastIndexOf("_")+"_".length());
                            }
                            retMap.put("知情同意书编号", firStr);
                        }
                        if (StringUtil.isNotEmpty(secStr)) {
                            retMap.put("知情同意书名称", secStr);
                        }
                    }
                }
                    String doctorSign = "医生签字:";
                    if (hero.contains("医生签名")) {
                        doctorSign = "医生签名";
                    }
                    if (hero.contains("医生签名:")) {
                        doctorSign = "医生签名:";
                    }
                    if (hero.contains("医生签名：")) {
                        doctorSign = "医生签名：";
                    }
                    if (hero.contains("医生签字：")) {
                        doctorSign = "医生签字：";
                    }
                    if (hero.contains("医师签名:")) {
                        doctorSign = "医师签名:";
                    }
                    if (hero.contains("医师签名：")) {
                        doctorSign = "医师签名：";
                    }
                    String signDate = "签名时间";
                    if (hero.contains("签名日期")) {
                        signDate = "签名日期";
                    }
                    if (hero.contains(doctorSign)) {
                        if (StringUtil.isNotEmpty(hero)) {
                            String firRet = doctorSign;
                            String firStr = hero.substring(hero.lastIndexOf(firRet) + firRet.length());
                            String date = extractDate(firStr);
                            String secStr = "";
                            if (StringUtil.isNotEmpty(date)) {
                                retMap.put("医师签名日期时间", date);
                                secStr = hero.substring(hero.lastIndexOf(firRet) + firRet.length(), hero.lastIndexOf(date));
                            } else {
                                if (firStr.contains("年")) {
                                    secStr = firStr.substring(0, firStr.lastIndexOf("年"));
                                }
                            }
                            if(hero.contains(signDate)){
                                secStr = hero.substring(hero.lastIndexOf(firRet) + firRet.length(), hero.lastIndexOf(signDate));
                            }
                            if (StringUtil.isNotEmpty(secStr)) {
                                secStr = parseString(secStr.trim());
                                if (StringUtil.isNotEmpty(secStr) && StringUtil.isNotEmpty(secStr.trim())) {
                                retMap.put("医师签名", secStr);
                            }
                            }
                        }
                    }

                    String hitSign = "患方签字:";

                    if (hero.contains("患者签名")) {
                        hitSign = "患者签名";
                    }
                    if (hero.contains("患方签字：")) {
                        hitSign = "患方签字：";
                    }
                    if (hero.contains("患方签名:")) {
                        hitSign = "患方签名:";
                    }
                    if (hero.contains("患方签名：")) {
                        hitSign = "患方签名：";
                    }
                    if (hero.contains("患者授权亲属签名")) {
                        hitSign = "患者授权亲属签名";
                    }
                    if (hero.contains(hitSign)) {
                        String firRet = hitSign;
                        String firStr = hero.substring(hero.lastIndexOf(firRet) + firRet.length());
                        String date = extractDate(firStr);
                        if (StringUtil.isNotEmpty(date)) {
                            retMap.put("患者/法定代理人签名日期时间", date);
                        }
                    }
                }
            }
            List<String> hitRecords = Arrays.asList("授权委托人意见","患方意见","患者知情选择","患者知情选择","患者承诺内容");
            String hitRecordStr = "";
            for (String hitRecord : hitRecords) {
                if(text.contains(hitRecord)){
                     hitRecordStr = text.substring(text.indexOf(hitRecord)+hitRecord.length());
                     break;
                }
            }
            hitRecordStr =  hitRecordStr.replace("签名","签字").replace("患者签字","患者（或授权人）签字").replace("患方签字","患者（或授权人）签字").replace("患者（代理人）签字","患者（或授权人）签字");
            if(hitRecordStr.contains("患者（或授权人）签字")){
               String hitRecordRet = hitRecordStr.split("患者（或授权人）签字")[0];
                if(hitRecordRet.contains("签字")){
                    hitRecordRet = hitRecordRet.split("签字")[0];
                }
               if(StringUtil.isNotEmpty(hitRecordRet)){
                   retMap.put("患者/法定代理人意见", hitRecordRet);
               }
            }else{
                String strFlag = "以上情况浙江省台州医院已经详细告知，我充分了解上述内容，并确认提供的信息属实，若信息不真实，愿承担相应责任。";
                if(text.contains(strFlag)){
                    retMap.put("患者/法定代理人意见", strFlag);
                }
            }

            String caseStr = "您好！感谢您对浙江省台州医院的信任。在当前新型冠状病毒感染的肺炎疫情特殊时期，我院高度重视在院病友的医疗安全，每日定期对所有诊疗场所、公共区域、电梯等进行严格、专业的消杀，确保向您提供一个安全的就诊及住院环境。";
            if(text.contains(caseStr)){
                retMap.put("医疗机构意见", caseStr);
            }


                //知情同意内容&&医疗机构意见
            if (StringUtil.isNotEmpty(retMap.get("病情告知")) && StringUtil.isNotEmpty(retMap.get("病情告知").trim())) {
                String tell = retMap.get("病情告知");
                       tell = repalce(tell);
                retMap.put("病情告知",tell);
            }
                if (StringUtil.isNotEmpty(retMap.get("知情选择"))&& StringUtil.isNotEmpty(retMap.get("知情选择").trim())) {
                    String choose = retMap.get("知情选择");
                    choose = repalce(choose);
                    retMap.put("知情选择",choose);
                    if (StringUtil.isNotEmpty(retMap.get("病情告知")) && StringUtil.isNotEmpty(retMap.get("病情告知").trim())) {
                        String tell = retMap.get("病情告知");
                        retMap.put("病情告知",tell+"  知情选择: "+choose);
                    }
                    /*else{
                        retMap.put("病情告知",choose);
                    }*/
                }

                if (StringUtil.isNotEmpty(retMap.get("具体如下"))&& StringUtil.isNotEmpty(retMap.get("具体如下").trim())) {
                    String tell = retMap.get("具体如下");
                    if(tell.contains("医生签字")){
                        tell = tell.substring(0, tell.lastIndexOf("医生签字"));
                    }
                    String choose = "";
                    if (text.contains("患者知情选择")) {
                        choose = text.substring(text.indexOf("患者知情选择")+"患者知情选择".length());
                    }
                    if (choose.contains("患方签名")) {
                        choose = choose.substring(0,choose.indexOf("患方签名"));
                    }
                    if (choose.contains("医生签字")) {
                        choose = choose.substring(0,choose.indexOf("医生签字"));
                    }
                    if(StringUtil.isNotEmpty(choose)){
                        retMap.put("病情告知",tell+"  患者知情选择:"+choose);
                        retMap.put("医疗机构意见", choose);
                    }
                    else{
                        retMap.put("病情告知",tell);
                    }
                    retMap.remove("具体如下");
                }else{
                    String choose = "";
                    if (text.contains("患者知情选择")) {
                        choose = text.substring(text.indexOf("患者知情选择")+"患者知情选择".length());
                    }
                    if (choose.contains("患方签名")) {
                        choose = choose.substring(0,choose.indexOf("患方签名"));
                    }
                    if(StringUtil.isNotEmpty(choose)){
                        retMap.put("病情告知",choose);
                    }
                }

                //镇静镇痛谈话 && 阿片类药物治疗知情同意书
            if(text.contains("疾病介绍和治疗建议")){
                String advice = "";
                if (text.contains("疾病介绍和治疗建议")) {
                    advice = text.substring(text.indexOf("疾病介绍和治疗建议")+"疾病介绍和治疗建议".length());
                }
                String replaceName = "患方签名";
                if (advice.contains("患者签名")) {
                    replaceName = "患者签名";
                }
                if (advice.contains(replaceName)) {
                    advice = advice.substring(0,advice.indexOf(replaceName));
                }
                if(StringUtil.isNotEmpty(advice)){
                    retMap.put("病情告知",advice);
                }
            }

            //输血血液制品治疗知情同意书
            if(text.contains("授权委托人意见:")){
                String advice = "";
                if (text.contains("授权委托人意见:")) {
                    advice = text.substring(text.indexOf("授权委托人意见:")+"授权委托人意见:".length());
                }
                String replaceName = "患方签名";
                if (advice.contains("患者签名")) {
                    replaceName = "患者签名";
                }
                if (advice.contains(replaceName)) {
                    advice = advice.split(replaceName)[0];
                }
                if(StringUtil.isNotEmpty(advice)){
                    retMap.put("患者/法定代理人意见",advice);
                }
            }
             String flagName = "医护人员陈述：";
            if(text.contains("医护人员陈述:")){
                flagName = "医护人员陈述:";
            }
            if(text.contains("医生陈述")){
                flagName = "医生陈述";
            }
            if(text.contains("医生陈述:")){
                flagName = "医生陈述:";
            }
            if(text.contains("医生陈述：")){
                flagName = "医生陈述：";
            }
            if(text.contains(flagName)){
                String advice = "";
                if (text.contains(flagName)) {
                    advice = text.substring(text.indexOf(flagName)+flagName.length());
                }
                advice = advice.replace("医护人员签名 ","医生签名");
                String replaceName = "医生签名";
                if (advice.contains(replaceName)) {
                    advice = advice.split(replaceName)[0];
                }
                if(StringUtil.isNotEmpty(advice)){
                    retMap.put("医疗机构意见",advice);
                    retMap.remove("具体如下");
                    retMap.remove("知情选择");
                }
            }

            //特殊医用材料使用知情同意书
            if(text.contains("材料内容")){
                String record = "";
                if (text.contains("材料内容")) {
                    record = text.substring(text.indexOf("材料内容")+"材料内容".length());
                }
                if (record.contains("患者（或授权人）签字")) {
                    record = record.substring(0,record.indexOf("患者（或授权人）签字"));
                }
                if(StringUtil.isNotEmpty(record)){
                    retMap.put("病情告知",record);
                }
            }

            if(StringUtil.isNotEmpty(retMap.get("病情告知"))){
                String tell = retMap.get("病情告知");
                       tell = lineFeed(tell);
                       tell = strFirLast(tell);
                    if(StringUtil.isNotEmpty(tell)){
                        retMap.put("病情告知",tell);
                    }
                }
            }
        }

    // 取/前
    public static String parseStr(String text){
        if(text.contains("/")){
            text = text.substring(0,text.lastIndexOf("/"));
            text= parseStr(text);
        }
        return text;
    }

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

    //去换行符
    public static String lineFeed(String firStr){
        if(StringUtil.isNotEmpty(firStr)){
            if(firStr.contains("\n")){
                StringBuffer sb = new StringBuffer();
                String[] split = firStr.split("\n");
                for (int i = 0; i < split.length; i++) {
                    sb.append(split[i]+"  ");
                }
                if(StringUtil.isNotEmpty(sb.toString())){
                    return sb.toString();
                }
            }
            return firStr;
        }
        return null;
    }

    //去首尾字符串字符
    public static String strFirLast(String firStr){
        if(StringUtil.isNotEmpty(firStr)){
            String flag = "：";
            String flagReplace = ":";
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < firStr.length(); i++) {
                String str = String.valueOf(firStr.charAt(i));
                if(i <=2 && str.contains(flag)||str.contains(flagReplace)){
                    continue;
                }
                if(i<=firStr.length()-1 && i>2 && str.contains(flag)||str.contains(flagReplace)){
                    continue;
                }
                sb.append(str);
            }
        return sb.toString();
        }
        return null;
    }

    /**
     * 抽取文本中的第一个时间
     * @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 repalce(String choose) {
       if(choose.contains("医生签字")){
        choose = choose.substring(0, choose.lastIndexOf("医生签字"));
    }
                    if(choose.contains("医生签名")){
        choose = choose.substring(0, choose.lastIndexOf("医生签名"));
    }
                    if(choose.contains("医师签字")){
        choose = choose.substring(0, choose.lastIndexOf("医师签字"));
    }
                    if(choose.contains("医师签名")){
        choose = choose.substring(0, choose.lastIndexOf("医师签名"));
         }
        return choose;
    }
}