package com.lantone.qc.kernel.catalogue.behospitalized;

import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import com.lantone.qc.kernel.catalogue.QCCatalogue;
import com.lantone.qc.kernel.client.ChiefPresentSimilarityServiceClient;
import com.lantone.qc.kernel.structure.ai.ModelAI;
import com.lantone.qc.kernel.util.CatalogueUtil;
import com.lantone.qc.pub.model.InputInfo;
import com.lantone.qc.pub.model.OutputInfo;
import com.lantone.qc.pub.model.entity.Diag;
import com.lantone.qc.pub.model.entity.GeneralDesc;
import com.lantone.qc.pub.model.entity.Pacs;
import com.lantone.qc.pub.model.label.DiagLabel;
import com.lantone.qc.pub.model.label.PacsLabel;
import com.lantone.qc.pub.model.label.PastLabel;
import com.lantone.qc.pub.model.label.PresentLabel;
import com.lantone.qc.pub.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ClassName : BEH0011
 * @Description : 初步诊断不完整
 * 原逻辑 --初步诊断没有既往史里的慢性疾病
 * 现逻辑 --检查现病史中一般情况之后的疾病名称，既往史中的疾病名称是否都在初步诊断里
 * @Author : 楼辉荣
 * @Date: 2020-03-06 17:28
 */
@Slf4j
@Component
public class BEH0011 extends QCCatalogue {
    //    @Autowired
    //    private SpecialStorageUtil specialStorageUtil;
    @Autowired
    ChiefPresentSimilarityServiceClient chiefPresentSimilarityServiceClient;

    private List<String> containList = Arrays.asList("脑萎缩", "慢性", "纤颤", "高血压", "糖尿", "冠状", "冠心病", "支架", "起搏器", "房颤", "风湿");
    private List<String> filterList = Arrays.asList("心脏病", "低血糖", "急性", ";");

    public void start(InputInfo inputInfo, OutputInfo outputInfo) {
        if (inputInfo.getBeHospitalizedDoc() == null) {
            status.set("0");
            return;
        }
        PresentLabel presentLabel = inputInfo.getBeHospitalizedDoc().getPresentLabel();
        DiagLabel initialDiagLabel = inputInfo.getBeHospitalizedDoc().getInitialDiagLabel();
        PastLabel pastLabel = inputInfo.getBeHospitalizedDoc().getPastLabel();
        PacsLabel pacsLabel = inputInfo.getBeHospitalizedDoc().getPacsLabel();
        if (initialDiagLabel == null) {
            status.set("0");
            return;
        }
        Set<String> presentPastDiags = new HashSet<>();
        if (presentLabel != null) {
            List<GeneralDesc> generals = presentLabel.getGenerals();
            if (generals.size() > 0) {
                String presentText = presentLabel.getText();
                List<Diag> presentDiags = presentLabel.getDiags();
                /* 取现病史中一般情况之后的疾病名称 */
                if (StringUtil.isNotBlank(presentText) && presentDiags.size() > 0) {
                    String lastGeneral = generals.get(generals.size() - 1).getName();
                    int lastGeneralIndex = presentText.indexOf(lastGeneral);
                    for (Diag presentDiag : presentDiags) {
                        if (presentDiag.getNegative() != null || presentDiag.getHospitalDiagName().contains("否认")) {
                            continue;
                        }
                        /* 现病史中一般情况之后的疾病名称 */
                        if (presentText.indexOf(presentDiag.getHospitalDiagName()) > lastGeneralIndex) {
                            if (isContains(presentDiag.getHospitalDiagName()) && !isFilter(presentDiag.getHospitalDiagName())) {
                                presentPastDiags.add(presentDiag.getHospitalDiagName());
                            }
                        }
                    }
                }
            }
        }
        /* 取既往史中疾病名称 */
        if (pastLabel != null && StringUtils.isNotEmpty(pastLabel.getText())) {
            List<Diag> pastDiags = pastLabel.getDiags();
            addDiagHospitalName(presentPastDiags, pastDiags);
        } else {            //结构化数据
            List<Diag> pastDiags = new ArrayList<>();

            Map<String, String> structureMap = inputInfo.getBeHospitalizedDoc().getStructureMap();
            String a1 = structureMap.get("高血压");
            if (StringUtils.isNotEmpty(a1) && !"否认".equals(a1)) {
                Diag diag = new Diag();
                diag.setName("高血压");
                diag.setHospitalDiagName("高血压");
                if (!isHave(presentPastDiags, "高血压")) {
                    pastDiags.add(diag);
                }
            }
            a1 = structureMap.get("糖尿病");
            if (StringUtils.isNotEmpty(a1) && !"否认".equals(a1)) {
                Diag diag = new Diag();
                diag.setName("糖尿病");
                diag.setHospitalDiagName("糖尿病");
                if (!isHave(presentPastDiags, "糖尿病")) {
                    pastDiags.add(diag);
                }
            }
            addDiagHospitalName(presentPastDiags, pastDiags);
        }

        /* 取辅检中疾病名称 */
        if (pacsLabel != null) {
            List<Pacs> pacses = pacsLabel.getPacses();
            if (pacses != null && pacses.size() > 0) {
                List<List<Diag>> pacsDiags = pacses.stream().map(Pacs::getDiags).filter(x -> x.size() > 0).collect(Collectors.toList());
                if (pacsDiags.size() > 1) {
                    List<Diag> diagList = pacsDiags.get(pacsDiags.size() - 1);
                    //把辅检提取出的疾病去除包含术后之后的疾病放入presentPastDiags
                    Set<String> diagStringList = diagList.stream().map(Diag::getHospitalDiagName).filter(x -> StringUtil.isNotBlank(x) && !x.contains("术后")).collect(Collectors.toSet());
                    presentPastDiags.addAll(diagStringList);
                }
            }
        }


        /* 取初步诊断中疾病名称 */
        List<String> initDiags = new ArrayList<>();
        List<Diag> initialDiagDiags = initialDiagLabel.getDiags();
        addInitDiagHospitalName(initDiags, initialDiagDiags);

        String infoStr = "";
        /*先两两对比，能对上就删除，对不上的再走相似度模型*/
        Iterator<String> iterator = presentPastDiags.iterator();
        while (iterator.hasNext()) {
            String presentPastDiag = iterator.next();
            for (String initDiag : initDiags) {
                if (presentPastDiag.equals(initDiag) || presentPastDiag.contains(initDiag) || initDiag.contains(presentPastDiag)) {
                    iterator.remove();
                }
            }
        }
        int matchSum = 0;
        ModelAI modelAI = new ModelAI();
        for (String presentPastDiag : presentPastDiags) {
            JSONArray jsonArray = modelAI.loadChiefPresentSimilarAI(presentPastDiag, initDiags, false
                    , "diagnose", chiefPresentSimilarityServiceClient);
            if (jsonArray.size() == 2) {
                /* 相似度最高症状 */
                String symptom = jsonArray.getString(0);
                /* 相似度分数 */
                double likeRate = jsonArray.getDoubleValue(1);
                if (likeRate > 0.85) {
                    matchSum++;
                } else if (symptom.contains(presentPastDiag) || presentPastDiag.contains(symptom)) {
                    matchSum++;
                } else {
                    infoStr = CatalogueUtil.concatInfo(infoStr, presentPastDiag);
                }
            } else {
                infoStr = CatalogueUtil.concatInfo(infoStr, presentPastDiag);
            }
        }
        info.set(infoStr);
        if (matchSum == presentPastDiags.size()) {
            status.set("0");
        }
        lackDiabetesFeritin(initDiags, presentLabel.getText(), inputInfo.getBeHospitalizedDoc().getStructureMap().get("长期用药"), inputInfo.getBeHospitalizedDoc().getStructureMap().get("外院用药"), inputInfo.getMedicalRecordInfoDoc().getStructureMap().get("behospitalCode"));
        /*
        if (initDiags.containsAll(presentPastDiags)) {
            status.set("0");
        }
         */
    }

    private void addDiagHospitalName(Set<String> presentPastDiag, List<Diag> pastDiags) {
        for (Diag pastDiag : pastDiags) {
            if (pastDiag.getNegative() != null) {
                continue;
            }
            if (isContains(pastDiag.getHospitalDiagName()) && !isFilter(pastDiag.getHospitalDiagName())) {
                presentPastDiag.add(pastDiag.getHospitalDiagName());
            }
        }
    }

    private void addInitDiagHospitalName(List<String> presentPastDiag, List<Diag> pastDiags) {
        for (Diag pastDiag : pastDiags) {
            if (pastDiag.getNegative() != null) {
                continue;
            }
            presentPastDiag.add(pastDiag.getHospitalDiagName());
        }
    }

    private boolean isHave(Set<String> presentDiag, String diagName) {
        for (String haveDiag : presentDiag) {
            if (haveDiag.contains(diagName) || diagName.contains(haveDiag)) {
                return true;
            }
        }
        return false;
    }

    private boolean isContains(String diagName) {
        for (String c : containList) {
            if (diagName.contains(c)) {
                return true;
            }
        }
        return false;
    }

    private boolean isFilter(String diagName) {
        for (String c : filterList) {
            if (diagName.contains(c)) {
                return true;
            }
        }
        return false;
    }
    /* 原逻辑
    Map<String, Map<String, Object>> diagMap = specialStorageUtil.getJsonStringValue(KernelConstants.CONCEPT_DIAG_PROPERTY_MAP);
    String initDiagText = CatalogueUtil.removeSpecialChar(initialDiagLabel.getText());
        if (pastLabel.getDiags() != null) {
            List<Diag> diags = pastLabel.getDiags().stream().filter(diag -> diag.getNegative() == null).collect(Collectors.toList());
            List<String> initDiags = Arrays.asList(initDiagText.split(","));
            if (diags.size() > 0) {
                for (Diag diag : diags) {
                    Map<String, Object> map = (Map<String, Object>) diagMap.get(diag.getName());
                    if (map != null && map.size() > 0) {
                        String chronic = (String) map.get("chronic");//1是慢病
                        if ("1".equals(chronic) && !initDiags.contains(diag.getName())) {
                            if (StringUtils.isEmpty(info.get())) {
                                info.set(diag.getName());
                            } else {
                                info.set(info.get() + "," + diag.getName());
                            }
                        }
                    }
                }
            }
        }
        if (StringUtils.isEmpty(info.get())) {
            status.set("0");
        }
     */

    //糖尿病、高血压药品过滤
    private void lackDiabetesFeritin(List<String> initDiags, String... texts) {
        String checkText = "";
        if (StringUtil.isNotBlank(texts[0])) {
            checkText += texts[0] + "。";
        }
        if (StringUtil.isNotBlank(texts[1])) {
            checkText += texts[1] + "。";
        }
        if (StringUtil.isNotBlank(texts[2])) {
            checkText += texts[2] + "。";
        }
        if (StringUtil.isBlank(checkText)) {
            return;
        }
        long diabetes = initDiags.stream().filter(x -> x.contains("糖尿病")).count();
        for (String diabetesDrug : diabetesDrugs) {
            if (checkText.contains(diabetesDrug) && checkText.contains("糖尿病") && diabetes == 0) {
                if (StringUtil.isBlank(info.get()) || !info.get().contains("糖尿病")) {
                    info.set(CatalogueUtil.concatInfo(info.get(), "糖尿病"));
                    status.set("-1");
                    log.error("初步诊断不完整：" + texts[3]);
                }
                break;
            }
        }
        long hypertension = initDiags.stream().filter(x -> x.contains("高血压")).count();
        for (String feritinDrug : feritinDrugs) {
            if (checkText.contains(feritinDrug) && checkText.contains("高血压") && hypertension == 0) {
                if (StringUtil.isBlank(info.get()) || !info.get().contains("高血压")) {
                    info.set(CatalogueUtil.concatInfo(info.get(), "高血压"));
                    status.set("-1");
                    log.error("初步诊断不完整：" + texts[3]);
                }
                break;
            }
        }
    }

    //糖尿病药
    private List<String> diabetesDrugs = Lists.newArrayList(
            "重组人胰岛素",
            "重组赖脯胰岛素",
            "谷赖胰岛素",
            "赖脯胰岛素",
            "门冬胰岛素",
            "生物合成人胰岛素",
            "胰岛素",
            "低精蛋白锌胰岛素",
            "精蛋白生物合成人胰岛素",
            "精蛋白锌重组人胰岛素",
            "精蛋白重组人胰岛素",
            "德谷门冬双胰岛素",
            "30/70混合重组人胰岛素",
            "50/50混合重组人胰岛素",
            "精蛋白生物合成人胰岛素(预混30R)",
            "精蛋白锌胰岛素(30R)",
            "精蛋白锌混合重组赖脯胰岛素(50R)",
            "精蛋白锌混合重组赖脯胰岛素(25R)",
            "精蛋白重组人胰岛素(预混30/70)",
            "精蛋白重组人胰岛素(50/50)",
            "精蛋白锌重组人胰岛素(40/60)",
            "门冬胰岛素30",
            "门冬胰岛素50",
            "重组甘精胰岛素",
            "地特胰岛素",
            "德谷胰岛素",
            "甘精胰岛素",
            "精蛋白锌胰岛素",
            "米格列奈钙",
            "那格列奈",
            "瑞格列奈",
            "吡格列酮二甲双胍",
            "二甲双胍格列呲嗪",
            "二甲双胍格列齐特",
            "二甲双胍格列本脲Ⅰ",
            "二甲双胍格列本脲Ⅱ",
            "二甲双胍格列吡嗪",
            "二甲双胍维格列汀",
            "利格列汀二甲双胍",
            "瑞格列奈二甲双胍",
            "沙格列汀二甲双胍",
            "西格列汀二甲双胍",
            "格列本脲",
            "格列吡嗪",
            "格列喹酮",
            "格列美脲",
            "格列齐特",
            "格列齐特Ⅱ",
            "甲苯磺丁脲",
            "吡格列酮",
            "罗格列酮",
            "二甲双胍",
            "阿卡波糖",
            "伏格列波糖",
            "依帕司他",
            "硫辛酸",
            "艾塞那肽",
            "贝那鲁肽",
            "度拉糖肽",
            "聚乙二醇洛塞那肽",
            "利拉鲁肽",
            "利司那肽",
            "阿格列汀",
            "利格列汀",
            "沙格列汀",
            "维格列汀",
            "西格列汀"
    );
    //高血压药
    private List<String> feritinDrugs = Lists.newArrayList(
            "贝那普利",
            "福辛普利",
            "卡托普利",
            "喹那普利",
            "赖诺普利",
            "雷米普利",
            "咪达普利",
            "培哚普利",
            "依那普利",
            "贝那普利氢氯噻嗪",
            "复方卡托普利",
            "赖诺普利氢氯噻嗪",
            "培哚普利吲达帕胺",
            "依那普利氢氯噻嗪",
            "氨氯地平贝那普利Ⅱ",
            "氨氯地平贝那普利Ⅰ",
            "培哚普利氨氯地平",
            "依那普利叶酸",
            "奥美沙坦",
            "阿利沙坦",
            "厄贝沙坦",
            "坎地沙坦",
            "氯沙坦",
            "替米沙坦",
            "缬沙坦",
            "奥美沙坦酯氢氯噻嗪",
            "厄贝沙坦氢氯噻嗪",
            "坎地氢噻",
            "氯沙坦氢氯噻嗪",
            "替米沙坦氢氯噻嗪",
            "缬沙坦氢氯噻嗪",
            "奥美沙坦氨氯地平",
            "替米沙坦氨氯地平",
            "缬沙坦氨氯地平",
            "沙库巴曲缬沙坦",
            "氨氯地平阿托伐他汀钙",
            "多沙唑嗪",
            "萘哌地尔",
            "哌唑嗪",
            "乌拉地尔",
            "乌拉地尔氯化钠",
            "卡维地洛",
            "阿夫唑嗪",
            "赛洛多辛",
            "坦洛新",
            "特拉唑嗪",
            "复方利血平",
            "复方利血平氨苯蝶啶",
            "复方双嗪利血平",
            "复方四嗪利血平",
            "复方双肼屈嗪",
            "复方盐酸阿米洛利",
            "氨苯蝶啶氢氯噻嗪",
            "氢氯噻嗪",
            "复方地巴唑氢氯噻嗪",
            "复方三嗪芦丁",
            "地尔硫䓬",
            "洛美利嗪",
            "阿折地平",
            "氨氯地平",
            "氨氯地平叶酸",
            "贝尼地平",
            "非洛地平",
            "拉西地平",
            "乐卡地平",
            "马尼地平",
            "门冬氨酸氨氯地平",
            "尼卡地平",
            "尼莫地平",
            "尼群地平",
            "尼群洛尔",
            "尼索地平",
            "尼卡地平氯化钠",
            "尼卡地平葡萄糖",
            "硝苯地平",
            "西尼地平",
            "硝苯地平Ⅰ",
            "硝苯地平Ⅱ",
            "硝苯地平Ⅲ",
            "硝苯地平(Ⅳ)",
            "左旋氨氯地平",
            "氨苯蝶啶"
    );

}