package com.lantone.qc.kernel.catalogue.beilun.threelevelward;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.lantone.qc.kernel.catalogue.QCCatalogue;
import com.lantone.qc.kernel.util.CatalogueUtil;
import com.lantone.qc.kernel.util.SimilarityUtil;
import com.lantone.qc.pub.model.InputInfo;
import com.lantone.qc.pub.model.OutputInfo;
import com.lantone.qc.pub.model.doc.BeHospitalizedDoc;
import com.lantone.qc.pub.model.doc.DoctorAdviceDoc;
import com.lantone.qc.pub.model.doc.FirstCourseRecordDoc;
import com.lantone.qc.pub.model.doc.LeaveHospitalDoc;
import com.lantone.qc.pub.model.doc.ThreeLevelWardDoc;
import com.lantone.qc.pub.model.doc.consultation.ConsultationDoc;
import com.lantone.qc.pub.model.doc.operation.OperationDiscussionDoc;
import com.lantone.qc.pub.model.doc.operation.OperationDoc;
import com.lantone.qc.pub.model.doc.operation.OperationRecordDoc;
import com.lantone.qc.pub.model.entity.Drug;
import com.lantone.qc.pub.util.DateUtil;
import com.lantone.qc.pub.util.StringUtil;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @ClassName : THR02985
 * @Description : 医嘱有抗生素使用病程无记录
 * 药品类型(0.普药 1.抗生素 2.激素)
 * @Author : 胡敬
 * @Date: 2020-06-23 10:04
 */
@Component
public class THR02985 extends QCCatalogue {
    @Autowired
    SimilarityUtil similarityUtil;

    public void start(InputInfo inputInfo, OutputInfo outputInfo) {
        status.set("0");
        List<DoctorAdviceDoc> doctorAdviceDocs = inputInfo.getDoctorAdviceDocs();
        List<ThreeLevelWardDoc> threeLevelWardDocs = inputInfo.getThreeLevelWardDocs();
        FirstCourseRecordDoc firstCourseRecordDoc = inputInfo.getFirstCourseRecordDoc();
        BeHospitalizedDoc beHospitalizedDoc = inputInfo.getBeHospitalizedDoc();
        List<OperationDoc> operationDocs = inputInfo.getOperationDocs();
        LeaveHospitalDoc leaveHospitalDoc = inputInfo.getLeaveHospitalDoc();
        List<ConsultationDoc> consultationDocs = inputInfo.getConsultationDocs();
        if (doctorAdviceDocs.size() == 0) {
            return;
        }

        List<Map<String, String>> docAdvStruct = doctorAdviceDocs
                .stream()
                .filter(Objects::nonNull)
                .map(DoctorAdviceDoc::getStructureMap)
                .filter(x -> StringUtil.isNotBlank(x.get("药品类型")) && x.get("药品类型").contains("抗生素"))
//                .filter(x -> StringUtil.isNotBlank(x.get("医嘱状态判别")) && !x.get("医嘱状态判别").contains("已停止"))
                .collect(Collectors.toList());

        docAdvStruct.removeIf(x -> StringUtil.isNotBlank(x.get("给药方式")) && !filterKey.contains(x.get("给药方式")));
        //记录同一天内是否开过多次同一抗生素
        Map<String, Map<Date, Integer>> antibioticDateTimes = Maps.newHashMap();
        //记录同一抗生素同一天内是否开过多次，用于医嘱中需要处理的抗生素过滤（一天内同一抗生素开过多次的抗生素直接过滤）
        getAntibioticTimes(docAdvStruct, antibioticDateTimes);
        Map<Date, String> doctorAdviceDrugMap = Maps.newLinkedHashMap();
        Date startDate = null;
        for (Map<String, String> adviceDoc : docAdvStruct) {
            String drugName = adviceDoc.get("医嘱项目名称");
            String startDateStr = adviceDoc.get("医嘱开始时间");
            if (StringUtil.isNotBlank(drugName)) {
                startDate = DateUtil.dateZeroClear(StringUtil.parseDateTime(startDateStr));
//                startDate = StringUtil.parseDateTime(startDateStr);
                if (antibioticDateTimes.get(drugName).get(startDate) > 0) {
                    continue;   //一天内同一抗生素开过多次的抗生素直接过滤
                }
                drugName = removeBracket(drugName).replaceAll("[^\u4e00-\u9fa5]", "");
                String drugStandardWord = similarityUtil.getDrugStandardWord(drugName);
                if (StringUtil.isNotBlank(drugStandardWord)) {
                    drugName = drugStandardWord;
                }
                if (Arrays.asList(KSS).contains(drugName)) {
                    doctorAdviceDrugMap.put(startDate, adviceDoc.get("医嘱项目名称"));
                }
            }
        }

        Map<String, Date> info = Maps.newLinkedHashMap();
        Map<String, List<Drug>> infoModel = Maps.newLinkedHashMap();
        String dateStr = null;
        //入院记录中获取信息
        /*if (beHospitalizedDoc != null) {
            Map<String, String> structureMap = beHospitalizedDoc.getStructureMap();
            getInfo(info, structureMap, "入院记录", "入院日期", "治疗计划");
        }*/
        //从首程治疗计划中获取信息
        if (firstCourseRecordDoc != null) {
            getInfo(info, firstCourseRecordDoc.getStructureMap(), "首次病程录", "病历日期", "诊疗计划");
            if (firstCourseRecordDoc.getDrugLabel() != null) {
                List<Drug> drugs = firstCourseRecordDoc.getDrugLabel().getDrugs();
                dateStr = firstCourseRecordDoc.getStructureMap().get("病历日期");
                if (StringUtil.isNotBlank(dateStr)) {
                    getInfo(infoModel, dateStr, drugs);
                }
            }
        }

        //从查房记录中获取信息
        if (threeLevelWardDocs.size() > 0) {
            List<ThreeLevelWardDoc> allDoctorWradDocs = threeLevelWardDocs.get(0).getAllDoctorWradDocs();
            List<ThreeLevelWardDoc> wardDocs = allDoctorWradDocs
                    .stream()
                    .filter(x -> StringUtil.isNotBlank(x.getStructureMap().get("查房日期")) && x.getThreeLevelWardLabel().size() > 0)
                    .collect(Collectors.toList());
            wardDocs.forEach(x -> getInfo(info, x.getStructureMap(), "查房记录", "查房日期", "病情记录", "治疗计划和措施"));
            wardDocs.forEach(x -> getInfo(infoModel, x.getStructureMap().get("查房日期"), x.getThreeLevelWardLabel().get(x.getThreeLevelWardLabel().size() - 1).getDrugs()));
        }
        //从手术记录中获取信息
        if (operationDocs.size() > 0) {
            //手术记录
            List<OperationRecordDoc> operationRecordDocs = operationDocs
                    .stream()
                    .map(OperationDoc::getOperationRecordDoc)
                    .filter(Objects::nonNull)
                    .filter(x -> x.getOperationRecordLabel() != null && StringUtil.isNotBlank(x.getStructureMap().get("手术时间")))
                    .collect(Collectors.toList());
            operationRecordDocs.forEach(x -> getInfo(info, x.getStructureMap(), "手术记录", "手术时间", "手术经过及处理"));
            operationRecordDocs.forEach(x -> getInfo(infoModel, x.getStructureMap().get("手术时间"), x.getOperationRecordLabel().getDrugs()));
            //术后首程
            List<OperationDiscussionDoc> operationDiscussionDocs = operationDocs
                    .stream()
                    .map(OperationDoc::getOperationDiscussionDoc)
                    .filter(Objects::nonNull)
                    .filter(x -> x.getOperationDiscussionLabel() != null && StringUtil.isNotBlank(x.getStructureMap().get("病历日期")))
                    .collect(Collectors.toList());
            operationDiscussionDocs.forEach(x -> getInfo(info, x.getStructureMap(), "术后首程", "病历日期", "手术简要经过", "术后处理措施"));
            operationDiscussionDocs.forEach(x -> getInfo(infoModel, x.getStructureMap().get("病历日期"), x.getOperationDiscussionLabel().getDrugs()));
        }

        //从会诊记录中获取信息
        /*if (consultationDocs.size() > 0) {
            List<ConsultationResultsDoc> consultationResultsDocs = consultationDocs
                    .stream()
                    .map(ConsultationDoc::getConsultationResultsDoc)
                    .filter(Objects::nonNull)
                    .filter(x -> x.getConsultationResultLabel() != null && StringUtil.isNotBlank(x.getStructureMap().get("会诊日期及时间")))
                    .collect(Collectors.toList());
            consultationResultsDocs.forEach(x -> getInfo(info, x.getStructureMap(), "会诊结果单", "会诊日期及时间", "会诊意见"));
            consultationResultsDocs.forEach(x -> getInfo(infoModel, x.getStructureMap().get("会诊日期及时间"), x.getConsultationResultLabel().getDrugs()));
        }*/

        //从出院小结中获取信息
        if (leaveHospitalDoc != null) {
            if (inputInfo.getMedicalRecordInfoDoc() != null) {
                Map<String, String> medicalRecordInfoStructureMap = inputInfo.getMedicalRecordInfoDoc().getStructureMap();
                dateStr = medicalRecordInfoStructureMap.get("leaveHospitalDate");
                //如果存在出院小结，出院日期为空，存储系统当前时间
                if (StringUtil.isBlank(dateStr)) {
                    dateStr = DateUtil.formatDateTime(new Date());
                }
            }
            if (StringUtil.isNotBlank(dateStr)) {
                if (leaveHospitalDoc.getLeaveHospitalLabel() != null) {
                    List<Drug> drugs = leaveHospitalDoc.getLeaveHospitalLabel().getDrugs();
                    getDischargeInfo(info, leaveHospitalDoc.getStructureMap(), "出院小结", dateStr, "诊治经过");
                    getInfo(infoModel, dateStr, drugs);
                }
            }
        }

        StringBuffer sb = new StringBuffer();
        Map<Object, Object> data = Maps.newHashMap();
        Set<String> existDrug = Sets.newHashSet();
        String infoStr = "";
        for (Map.Entry<Date, String> doctorAdviceDrug : doctorAdviceDrugMap.entrySet()) {
            Date doctorAdviceDate = doctorAdviceDrug.getKey();
            String drugs = doctorAdviceDrug.getValue();
            if (drugs.contains(" ")) {
                drugs = drugs.split(" ")[0];
            }
//            drugs = removeBracket(drugs).replaceAll("[^\u4e00-\u9fa5]", "");
            Set<String> splitDrugs = CatalogueUtil.getRegexWords(drugs, "[(（\\[][^\\[\\]()（）]+[\\]）)]")
                    .stream().filter(x -> !x.equals("合资") && !x.equals("进口") && !x.equals("国产")).collect(Collectors.toSet());
            /**********************************************先文本匹配************************************************/
            String missDrug = "";
            for (Map.Entry<String, Date> map : info.entrySet()) {
                missDrug = getMissDrug(map.getKey(), map.getValue(), doctorAdviceDate, splitDrugs, 2, missDrug, existDrug);
                //当前抗生素药（drugs）在info中已找到，直接跳出当前循环
                if (StringUtil.isBlank(missDrug)) {
                    break;
                }
            }
            if (StringUtil.isBlank(missDrug)) {
                continue;
            }
            /**********************************************文本匹配没有找到药，再走模型************************************************/
            boolean modelFind = false;
            for (Map.Entry<String, List<Drug>> modelMap : infoModel.entrySet()) {
                dateStr = modelMap.getKey();
                List<Drug> diags = modelMap.getValue();
                Date date = StringUtil.parseDateTime(dateStr);
                //医嘱开始时间往后2天或往前一天找药
                if ((doctorAdviceDate.before(date) && !CatalogueUtil.compareTime(doctorAdviceDate, date, 48 * 60L))
                        || (date.before(doctorAdviceDate) && !CatalogueUtil.compareTime(date, doctorAdviceDate, 24 * 60L))) {
                    for (String adDrug : splitDrugs) {
                        for (Drug courseDrug : diags) {
                            if (compareStandard(courseDrug.getName(), adDrug)) {
                                modelFind = true;
                                break;
                            }
                        }
                    }
                }
                if (modelFind) {
                    break;
                }
            }

            if (StringUtil.isNotBlank(missDrug) && !modelFind && CatalogueUtil.compareTime(doctorAdviceDate, new Date(), 48 * 60L)) {
                infoAppend(sb, drugs, DateUtil.formatDateTime(doctorAdviceDate));
                data.put(doctorAdviceDate, splitDrugs.toString().replaceAll("[\\[\\]]", ""));
            }
        }
        if (StringUtil.isNotBlank(sb.toString())) {
            this.status.set("-1");
            this.info.set("医嘱：" + sb.toString().substring(0, sb.toString().length() - 1));
            extData.set(data);
        }
    }

    /**
     * 记录同一抗生素同一天内是否开过多次，用于医嘱中需要处理的抗生素过滤（一天内同一抗生素开过多次的抗生素直接过滤）
     *
     * @param docAdvStruct
     * @param antibioticDateTimes
     */
    private void getAntibioticTimes(List<Map<String, String>> docAdvStruct, Map<String, Map<Date, Integer>> antibioticDateTimes) {
        String drugName;
        String startDateStr;
        Date startDate;
        Map<Date, Integer> antibioticDateTime;
        for (Map<String, String> structMap : docAdvStruct) {
            drugName = structMap.get("医嘱项目名称");
            startDateStr = structMap.get("医嘱开始时间");
            startDate = DateUtil.dateZeroClear(StringUtil.parseDateTime(startDateStr));
//            startDate = StringUtil.parseDateTime(startDateStr);
            if (antibioticDateTimes.containsKey(drugName)) {
                Map<Date, Integer> map = antibioticDateTimes.get(drugName);
                if (map.containsKey(startDate)) {
                    map.put(startDate, map.get(startDate) + 1);
                } else {
                    map.put(startDate, 0);
                }
            } else {
                antibioticDateTime = Maps.newHashMap();
                antibioticDateTime.put(startDate, 0);
                antibioticDateTimes.put(drugName, antibioticDateTime);
            }
        }
    }

    /**
     * 获取各模块信息<入院记录、首次病程录、手术记录、术后首程、会诊结果单、查房记录>
     *
     * @param structureMap
     * @param info
     */
    private void getInfo(Map<String, Date> info, Map<String, String> structureMap, String modelType, String dateKey, String... contentKey) {
        String content = CatalogueUtil.structureMapJoin(structureMap, Lists.newArrayList(contentKey));
        String recordDateStr = structureMap.get(dateKey);
        if (StringUtil.isNotBlank(recordDateStr)) {
            Date date = StringUtil.parseDateTime(recordDateStr);
            if (StringUtil.isNotBlank(content) && date != null) {
                info.put(modelType + "->" + content, date);
            }
        }
    }

    /**
     * 获取出院小结模块信息
     *
     * @param structureMap
     * @param info
     */
    private void getDischargeInfo(Map<String, Date> info, Map<String, String> structureMap, String modelType, String dateStr, String... contentKey) {
        String content = CatalogueUtil.structureMapJoin(structureMap, Lists.newArrayList(contentKey));
        if (StringUtil.isNotBlank(dateStr)) {
            Date date = StringUtil.parseDateTime(dateStr);
            if (StringUtil.isNotBlank(content) && date != null) {
                info.put(modelType + "->" + content, date);
            }
        }
    }

    private void getInfo(Map<String, List<Drug>> info, String dateKey, List<Drug> drugs) {
        List<Drug> tempDrugs = new ArrayList<>();
        if (null != drugs && drugs.size() > 0) {
            for (Drug drug : drugs) {
                if (null != drug.getConsumption() && !drug.getConsumption().getName().contains("mg/Kg")) {
                    tempDrugs.add(drug);
                }
            }
        }
        if (info.containsKey(dateKey)) {
            info.get(dateKey).addAll(tempDrugs);
        } else {
            info.put(dateKey, tempDrugs);
        }
    }

    /**
     * 核心：从文本中找药
     *
     * @param content          文本
     * @param wardDate
     * @param doctorAdviceDate
     * @param drugs
     * @param days
     * @return 如果文本中找到该药，则返回空字符串
     */
    private String getMissDrug(String content, Date wardDate, Date doctorAdviceDate, Set<String> drugs, int days, String missDrug, Set<String> existDrug) {
        if ("时间不匹配".equals(missDrug)) {
            missDrug = "";//初始化缺失药物
        }
        //开医嘱时间起，昨天今天明天记录内查找药
        if ((doctorAdviceDate.before(wardDate) && !CatalogueUtil.compareTime(doctorAdviceDate, wardDate, days * 24 * 60L))
                || (wardDate.before(doctorAdviceDate) && !CatalogueUtil.compareTime(wardDate, doctorAdviceDate, 24 * 60L)) ||
                DateUtils.isSameDay(wardDate, doctorAdviceDate)) {
            boolean findDrug = false;
            String standardDrug = null;
            for (String drug : drugs) {
                if (StringUtil.isBlank(drug)) {
                    continue;
                }
                drug = drug.replaceAll("[^\\u4e00-\\u9fa5]", "");
                standardDrug = similarityUtil.getDrugStandardWord(drug);
                if (content.contains(drug) || (StringUtil.isNotBlank(content) && StringUtil.isNotBlank(standardDrug) && content.contains(standardDrug))
                        || (existDrug.contains(drug) && (regexFind(content, "继续", "治疗") || regexFind(content, "维持", "治疗")
                        || regexFind(content, "继续", "抗感染") || regexFind(content, "治疗", "同前") || regexFind(content, "治疗同前")))) {
                    findDrug = true;
                    existDrug.add(drug);
                    break;
                } else {
                    missDrug = concatInfo(missDrug, drug);
                }
            }
            if (findDrug) {
                missDrug = "";//如果找到一种抗生素药，就把报错信息置为空
            }
        } else {
            if (StringUtil.isBlank(missDrug)) {
                missDrug = "时间不匹配";
            }
        }
        return missDrug;
    }

    private String concatInfo(String infoStr, String content) {
        if (StringUtil.isBlank(infoStr)) {
            infoStr += content;
        } else {
            if (!infoStr.contains(content)) {
                infoStr += "或" + content;
            }
        }
        return infoStr;
    }

    private boolean regexFind(String content, String... str) {
        String s = "";
        for (String word : str) {
            s += word + ".*";
        }
        s = s.substring(0, s.lastIndexOf(".*"));
        Pattern p = Pattern.compile(s);
        Matcher m = p.matcher(content);
        return m.find();
    }

    /**
     * 比较两个抗生素标准词是否一致
     *
     * @param firstWord
     * @param secordWord
     * @return
     */
    private boolean compareStandard(String firstWord, String secordWord) {
        if (StringUtil.isBlank(firstWord) || StringUtil.isBlank(secordWord)) {
            return false;
        }
        String drugStandardWord1 = similarityUtil.getDrugStandardWord(firstWord);
        String drugStandardWord2 = similarityUtil.getDrugStandardWord(secordWord);
        if (drugStandardWord1 == null || drugStandardWord2 == null) {
            return firstWord.equals(secordWord) || firstWord.contains(secordWord) || secordWord.contains(firstWord);
        }
        return drugStandardWord1.equals(drugStandardWord2);
    }

    /**
     * 如果文本包含中括号（[海正]美罗培南针），取括号之后的文字
     *
     * @param str
     * @return
     */
    private String removeBracket(String str) {
        if (str.contains("]") && str.indexOf("]") != str.length() - 1) {
            return str.substring(str.indexOf("]") + 1);
        }
        return str;
    }

    /**
     * 拼接提示信息
     *
     * @param sb
     * @param drugKey
     * @param date
     */
    private void infoAppend(StringBuffer sb, String drugKey, String date) {
        sb.append(drugKey).append("(").append(date).append(")").append("_");
    }

    private static final List<String> filterKey = Lists.newArrayList("ACF", "ID", "IG", "IM", "IP", "IV",
            "关节腔注射", "宫颈注射", "皮下注射", "皮下注射(儿童)", "皮下注射(免费)", "皮下注射(成人)", "皮内", "皮内注射",
            "结膜下注射", "肌注", "肌肉注射(儿童)", "肌肉注射(公卫专用)", "肌肉注射(成人)", "胸腔注射", "腹腔内注射", "腹腔注射",
            "静滴(儿童)", "静滴(成人)", "静脉注射", "静脉注射(儿童)", "静脉注射(免费)", "静脉注射(成人)", "静脉注射(泵)",
            "静脉滴注", "静脉滴注(泵)", "鞘内注射", "微泵");

    private static final String[] KSS = {
            "万古霉素",
            "两性霉素B",
            "亚胺培南西司他丁",
            "伊曲康唑",
            "伏立康唑",
            "依替米星",
            "克拉霉素",
            "克林霉素",
            "利奈唑胺",
            "利奈唑胺葡萄糖",
            "利福昔明",
            "制霉菌素",
            "卡泊芬净",
            "厄他培南",
            "吗啉硝唑",
            "呋喃唑酮",
            "哌拉西林他唑巴坦",
            "磺胺甲恶唑",
            "多粘菌素B",
            "多西环素",
            "夫西地酸",
            "头孢丙烯",
            "头孢他啶",
            "头孢他啶阿维巴坦",
            "头孢他美酯",
            "头孢克洛",
            "头孢克肟",
            "头孢吡肟",
            "头孢呋辛",
            "头孢哌酮舒巴坦",
            "头孢唑林",
            "头孢噻肟",
            "头孢地嗪",
            "头孢地尼",
            "头孢拉定",
            "头孢曲松",
            "头孢替安",
            "头孢美唑",
            "头孢西丁",
            "奥硝唑",
            "妥布霉素",
            "妥布霉素地塞米松",
            "左氧氟沙星",
            "左氧氟沙星",
            "庆大霉素",
            "异帕米星",
            "拉氧头孢",
            "替加环素",
            "替硝唑",
            "替考拉宁",
            "比阿培南",
            "氟康唑",
            "氟康唑",
            "氟胞嘧啶",
            "氨曲南",
            "氨苄西林",
            "泊沙康唑",
            "特比萘芬",
            "甲硝唑",
            "甲硝唑",
            "磷霉素",
            "磷霉素氨丁三醇",
            "米卡芬净",
            "米诺环素",
            "红霉素",
            "美罗培南",
            "苄星青霉素",
            "莫西沙星",
            "莫西沙星",
            "达托霉素",
            "阿奇霉素",
            "阿奇霉素枸橼酸二氢钠",
            "阿洛西林",
            "阿米卡星",
            "阿莫西林",
            "阿莫西林克拉维酸",
            "青霉素"
    };
}