package com.lantone.structure.facade.tran;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lantone.common.util.DateUtil;
import com.lantone.common.util.ListUtil;
import com.lantone.common.util.StringUtil;
import com.lantone.structure.facade.tran.util.CommonAnalysisUtil;
import com.lantone.structure.model.doc.CaesareanSectionDoc;
import com.lantone.structure.model.entity.ApgarScore;
import com.lantone.structure.model.entity.Drug;
import com.lantone.structure.model.entity.UCAgent;
import com.lantone.structure.model.label.CaesareanSectionLabel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description:
 * @author: rengb
 * @time: 2021/2/2 13:48
 */
@Slf4j
public class CesareanSectionTran extends TargetTran {

    @Override
    public Map<String, String> convert(String text) {
        List<CaesareanSectionDoc> caesareanSectionDocList = new ArrayList<>();
        CaesareanSectionDoc caesareanSectionDoc = new CaesareanSectionDoc();
        caesareanSectionDoc.setText(text);
        caesareanSectionDocList.add(caesareanSectionDoc);
        inputInfo.setCaesareanSectionDocs(caesareanSectionDocList);
        aiProcess();

        Map<String, String> sourceMap = cutWord(text);
        sourceMap = caesareanSectionMethod(sourceMap);
        insertCrf(sourceMap);
        return sourceMap;
    }

    private Map<String, String> cutWord(String text) {
        Map<String, String> ret = Maps.newHashMap();
        Map<String, String> sourceMap = Maps.newHashMap();
        text = text.replace("第1次手术", "第1次手术：");
        List<String> titles = CommonAnalysisUtil.sortTitles(
                Lists.newArrayList("手术开始时间", "手术结束时间", "手术日期", "术前诊断", "手术名称", "术中诊断", "手 术 者","护婴者","麻醉方法",
                        "麻 醉 者", "手术标本", "术中并发症", "术中失血量", "手术经过", "第1次手术"),
                text
        );
        CommonAnalysisUtil.cutByTitles(text, titles, 0, sourceMap);
        opeTimeHandle(sourceMap, ret);
        if(StringUtils.isNotEmpty(sourceMap.get("护婴者"))){
            ret.put("护婴者", sourceMap.get("护婴者"));
        }
        ret.put("术前诊断", sourceMap.get("术前诊断"));
        ret.put("剖宫产手术过程", sourceMap.get("手术经过").replace("（包括体位、切口处理经过，病理标本肉眼所见）", "").trim());
        return ret;
    }

    private Map<String, String> caesareanSectionMethod( Map<String, String> retMap) {
        if(retMap.containsKey("剖宫产手术过程")){
            String caesareanSection = retMap.get("剖宫产手术过程").replace("分娩胎","").replace("助娩","分娩").replace("娩出","分娩").replace("，予保暖、清理呼吸道后5分钟Apgar评分10分","").replace("子宫下段收缩","宫缩").replace("子宫下段仍收缩","宫缩").replace("子宫收缩","宫缩").replace(",","，").replace("。","，").replace("：",",");
            if(caesareanSection.contains("新生儿外观")){
                String newKidCase= caesareanSection.substring(caesareanSection.lastIndexOf("新生儿外观"));
                if(newKidCase.contains("胎盘胎膜")){
                     newKidCase= newKidCase.split("胎盘胎膜")[0];
                    newKidCase= newKidCase.substring(0,newKidCase.lastIndexOf("，"));
                    retMap.put("新生儿异常情况", newKidCase);
                }
            }
            if(caesareanSection.contains("，")){
                String[] split = caesareanSection.split("，");
                for (String str : split) {
                    if(str.contains("宫缩")){
                        String strFir = str.substring(str.indexOf("宫缩")+"宫缩".length());
                        if(strFir.trim().length()>0){
                            retMap.put("术后宫缩", strFir);
                        }
                    }
                    if(str.contains("性别")){
                        if(str.contains("男")){
                            retMap.put("新生儿性别", "男");
                        }
                        if(str.contains("女")){
                            retMap.put("新生儿性别", "女");
                        }
                    }
                    if(str.contains("分娩一")){
                        String strFir = str.substring(str.indexOf("分娩一"));
                        if(strFir.trim().length()>0){
                            retMap.put("分娩结局", strFir);
                        }
                    }
                    if(!str.contains("分娩") && str.contains("胎膜包裹死胎")){
                        retMap.put("分娩结局", "胎膜包裹死胎");
                    }

                    if(str.contains("有产瘤") || str.contains("cm产瘤")){
                        retMap.put("产瘤", "有产瘤");
                    }
                    if(str.contains("无产瘤")){
                        retMap.put("产瘤", "无产瘤");
                    }

                }
            }
        }
        return retMap;
    }

    private void opeTimeHandle(Map<String, String> sourceMap, Map<String, String> ret) {
        try {
            String opeStartTime = sourceMap.get("手术开始时间");
            String opeEndTime = sourceMap.get("手术结束时间");
            if (StringUtil.isNotBlank(sourceMap.get("手术日期"))) {
                String[] arry = sourceMap.get("手术日期").split("-");
                opeStartTime = StringUtil.removeBlank(arry[0].replaceAll("(开始时间)[:：]", ""));
                opeEndTime = StringUtil.removeBlank(arry[1].replaceAll("(结束时间)[:：]", ""));
            }
            ret.put("手术开始日期时间", opeStartTime);
            ret.put("手术结束日期时间", opeEndTime);
            ret.put("手术全程时间（min）", (DateUtil.parseDate(opeEndTime, "yyyy年MM月dd日HH时mm分").getTime() - DateUtil.parseDate(opeStartTime, "yyyy年MM月dd日HH时mm分").getTime()) / 60000 + "min");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    private void insertCrf(Map<String, String> sourceMap) {
        List<CaesareanSectionDoc> caesareanSectionDocs = inputInfo.getCaesareanSectionDocs();
        if (ListUtil.isEmpty(caesareanSectionDocs)) {
            return;
        }
        CaesareanSectionDoc caesareanSectionDoc = caesareanSectionDocs.get(0);
        CaesareanSectionLabel caesareanSectionLabel = caesareanSectionDoc != null ? caesareanSectionDoc.getCaesareanSectionLabel() : null;
        if (caesareanSectionLabel == null) {
            return;
        }
        StringBuffer value = new StringBuffer();

        //手术指征
        //        if (ListUtil.isNotEmpty(caesareanSectionLabel.getDiagnosis())) {
        //            caesareanSectionLabel.getDiagnosis().stream().filter(i -> i != null && StringUtil.isNotBlank(i.getName())).forEach(i -> {
        //                value.append(i.getName()).append("；");
        //                ;
        //            });
        //            sourceMap.put("手术指征", value.toString());
        //            value.setLength(0);
        //        }

        //麻醉体位
        if (caesareanSectionLabel.getAnesthesiaMethod() != null) {
            sourceMap.put("麻醉体位", caesareanSectionLabel.getAnesthesiaMethod().getName());
        }

        //麻醉效果
        if (caesareanSectionLabel.getAnestheticEffect() != null) {
            sourceMap.put("麻醉效果", caesareanSectionLabel.getAnestheticEffect().getName());
        }

        //子宫情况
        if (ListUtil.isNotEmpty(caesareanSectionLabel.getUterusConditions())) {
            caesareanSectionLabel.getUterusConditions().stream().filter(i -> i != null && StringUtil.isNotBlank(i.getName())).forEach(i -> {
                value.append(i.getName()).append("；");
                ;
            });
            sourceMap.put("子宫情况", value.toString());
            value.setLength(0);
        }

        //胎儿娩出方式
        if (caesareanSectionLabel.getChildbirthWay() != null) {
            sourceMap.put("胎儿娩出方式", caesareanSectionLabel.getChildbirthWay().getName());
        }

        //羊水性状
        //羊水量（mL）
        if (caesareanSectionLabel.getAmnioticFluid() != null) {
            if (caesareanSectionLabel.getAmnioticFluid().getAmnioticFluidCharacter() != null) {
                sourceMap.put("羊水性状", caesareanSectionLabel.getAmnioticFluid().getAmnioticFluidCharacter().getName());
            }
            if (caesareanSectionLabel.getAmnioticFluid().getQuantity() != null) {
                sourceMap.put("羊水量（mL）", caesareanSectionLabel.getAmnioticFluid().getQuantity().getName());
            }
        }

        //胎盘娩出情况
        if (ListUtil.isNotEmpty(caesareanSectionLabel.getChildbirthConditions())) {
            caesareanSectionLabel.getChildbirthConditions().stream().filter(i -> i != null && StringUtil.isNotBlank(i.getName())).forEach(i -> {
                value.append(i.getName()).append("；");
            });
            sourceMap.put("胎盘娩出情况", value.toString());
            value.setLength(0);
        }

        //脐带长度（cm）
        if (caesareanSectionLabel.getUmbilicalCord() != null) {
            if (caesareanSectionLabel.getUmbilicalCord().getExtent() != null) {
                sourceMap.put("脐带长度（cm）", caesareanSectionLabel.getUmbilicalCord().getExtent().getName());
            }
        }

        //绕颈身（周）
        if (caesareanSectionLabel.getCordAroundNeck() != null || caesareanSectionLabel.getCordAroundBody() != null) {
            String rjValue = "";
            if (caesareanSectionLabel.getCordAroundNeck() != null) {
                if (caesareanSectionLabel.getCordAroundNeck().getNegative() != null) {
                    if (StringUtil.isNotBlank(caesareanSectionLabel.getCordAroundNeck().getNegative().getName())) {
                        rjValue += caesareanSectionLabel.getCordAroundNeck().getNegative().getName() + "绕颈";
                    }
                }
                if (caesareanSectionLabel.getCordAroundNeck().getCylinderNumber() != null) {
                    if (StringUtil.isNotBlank(caesareanSectionLabel.getCordAroundNeck().getCylinderNumber().getName())) {
                        rjValue += caesareanSectionLabel.getCordAroundNeck().getCylinderNumber().getName();
                    }
                }
                rjValue += " ";
            }
            if (caesareanSectionLabel.getCordAroundBody() != null) {
                if (caesareanSectionLabel.getCordAroundBody().getNegative() != null) {
                    if (StringUtil.isNotBlank(caesareanSectionLabel.getCordAroundBody().getNegative().getName())) {
                        rjValue += caesareanSectionLabel.getCordAroundBody().getNegative().getName() + "绕身";
                    }
                }
                if (caesareanSectionLabel.getCordAroundBody().getCylinderNumber() != null) {
                    if (StringUtil.isNotBlank(caesareanSectionLabel.getCordAroundBody().getCylinderNumber().getName())) {
                        rjValue += caesareanSectionLabel.getCordAroundBody().getCylinderNumber().getName();
                    }
                }
            }
            sourceMap.put("绕颈身（周）", rjValue.trim());
        }

        //子宫壁缝合情况
        if (ListUtil.isNotEmpty(caesareanSectionLabel.getUterineWallSutures())) {
            caesareanSectionLabel.getUterineWallSutures().stream().filter(i -> i != null && StringUtil.isNotBlank(i.getName())).forEach(i -> {
                value.append(i.getName()).append("；");
            });
            sourceMap.put("子宫壁缝合情况", value.toString());
            value.setLength(0);
        }

        //宫缩剂名称
        //宫缩剂使用方法
        if (ListUtil.isNotEmpty(caesareanSectionLabel.getUCAgents())) {
            StringBuffer gsjName = new StringBuffer();
            StringBuffer gsjMd = new StringBuffer();
            List<UCAgent> uCAgents = caesareanSectionLabel.getUCAgents().stream()
                    .filter(i -> i != null && StringUtil.isNotBlank(i.getName()))
                    .collect(Collectors.toList());
            uCAgents.forEach(i -> {
                gsjName.append(i.getName()).append("；");
                if (i.getConsumption() != null && StringUtil.isNotBlank(i.getConsumption().getName())) {
                    gsjMd.append(i.getName()).append(" ").append(i.getConsumption().getName()).append(" ");
                }
                if (i.getUsageWardRound() != null && StringUtil.isNotBlank(i.getUsageWardRound().getName())) {
                    gsjMd.append(i.getUsageWardRound().getName());
                }
                gsjMd.append("；");
            });
            sourceMap.put("宫缩剂名称", gsjName.toString());
            sourceMap.put("宫缩剂使用方法", gsjMd.toString());
        }

        //宫腔探查异常情况描述
        if (ListUtil.isNotEmpty(caesareanSectionLabel.getUterineCavityAbnormity())) {
            caesareanSectionLabel.getUterineCavityAbnormity().stream().filter(i -> i != null && StringUtil.isNotBlank(i.getName())).forEach(i -> {
                value.append(i.getName()).append("；");
                ;
            });
            sourceMap.put("宫腔探查异常情况描述", value.toString());
            value.setLength(0);
        }

        //宫腔探查处理情况
        if (ListUtil.isNotEmpty(caesareanSectionLabel.getUterineCavityDispose())) {
            caesareanSectionLabel.getUterineCavityDispose().stream().filter(i -> i != null && StringUtil.isNotBlank(i.getName())).forEach(i -> {
                value.append(i.getName()).append("；");
            });
            sourceMap.put("宫腔探查处理情况", value.toString());
            value.setLength(0);
        }

        //手术时产妇情况
        if (ListUtil.isNotEmpty(caesareanSectionLabel.getPuerperaCondition())) {
            caesareanSectionLabel.getPuerperaCondition().stream().filter(i -> i != null && StringUtil.isNotBlank(i.getName())).forEach(i -> {
                value.append(i.getName()).append("；");
            });
            sourceMap.put("手术时产妇情况", value.toString());
            value.setLength(0);
        }

        //出血量（mL）
        if (caesareanSectionLabel.getHemorrhage() != null) {
            if (caesareanSectionLabel.getHemorrhage().getQuantity() != null) {
                sourceMap.put("出血量（mL）", caesareanSectionLabel.getHemorrhage().getQuantity().getName());
            }
        }

        //输液量（mL）
        if (caesareanSectionLabel.getFluidInfusion() != null) {
            if (caesareanSectionLabel.getFluidInfusion().getQuantity() != null) {
                sourceMap.put("输液量（mL）", caesareanSectionLabel.getFluidInfusion().getQuantity().getName());
            }
        }

        //新生儿出生体重（g）
        //新生儿出生身长（cm）
        if (caesareanSectionLabel.getNewborn() != null) {
            if (caesareanSectionLabel.getNewborn().getWeight() != null) {
                sourceMap.put("新生儿出生体重（g）", caesareanSectionLabel.getNewborn().getWeight().getName());
            }
            if (caesareanSectionLabel.getNewborn().getExtent() != null) {
                sourceMap.put("新生儿出生身长（cm）", caesareanSectionLabel.getNewborn().getExtent().getName());
            }
        }

        //Apgar评分值
        if (ListUtil.isNotEmpty(caesareanSectionLabel.getApgarScores())) {
            List<ApgarScore> apgarScores = caesareanSectionLabel.getApgarScores().stream()
                    .filter(i -> i != null && StringUtil.isNotBlank(i.getName()) && i.getScore() != null && StringUtil.isNotBlank(i.getScore().getName()))
                    .collect(Collectors.toList());
            if (ListUtil.isNotEmpty(apgarScores)) {
                sourceMap.put("Apgar评分值", apgarScores.get(0).getScore().getName());
            }
        }

        //产瘤大小
        //产瘤部位
        if (caesareanSectionLabel.getCaputSuccedaneum() != null) {
            if (caesareanSectionLabel.getCaputSuccedaneum().getVolume() != null) {
                sourceMap.put("产瘤大小", caesareanSectionLabel.getCaputSuccedaneum().getVolume().getName());
            }
            if (caesareanSectionLabel.getCaputSuccedaneum().getCaputSuccedaneumPart() != null) {
                sourceMap.put("产瘤部位", caesareanSectionLabel.getCaputSuccedaneum().getCaputSuccedaneumPart().getName());
            }
        }

        //手术用药
        //手术用药量
        if (ListUtil.isNotEmpty(caesareanSectionLabel.getDrugs())) {
            StringBuffer drugName = new StringBuffer();
            StringBuffer consumption = new StringBuffer();
            List<Drug> drugs = caesareanSectionLabel.getDrugs().stream()
                    .filter(i -> i != null && StringUtil.isNotBlank(i.getName()))
                    .collect(Collectors.toList());
            drugs.forEach(i -> {
                drugName.append(i.getName()).append("；");
                if (i.getConsumption() != null && StringUtil.isNotBlank(i.getConsumption().getName())) {
                    consumption.append(i.getName()).append(" ").append(i.getConsumption().getName());
                }
                consumption.append("；");
            });
            sourceMap.put("手术用药", drugName.toString());
            sourceMap.put("手术用药量", consumption.toString());
        }

        //输血成分
        //输血量（mL）
        if (caesareanSectionLabel.getTransfusion() != null) {
            sourceMap.put("输血成分", caesareanSectionLabel.getTransfusion().getName());
            if (caesareanSectionLabel.getTransfusion().getQuantity() != null) {
                sourceMap.put("输血量（mL）", caesareanSectionLabel.getTransfusion().getQuantity().getName());
            }
        }
    }

}