package org.diagbot.graph.jdbc;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.diagbot.common.push.bean.FeatureRate;
import org.diagbot.common.push.bean.neo4j.*;
import org.diagbot.pub.utils.PropertiesUtil;
import org.neo4j.driver.v1.*;
import org.neo4j.driver.v1.types.Node;
import org.neo4j.driver.v1.types.Path;
import org.neo4j.driver.v1.types.Relationship;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileWriter;
import java.io.IOException;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Neo4j的API接口
 * Created by Mark Huang on 2018/10/29.
 */

public class Neo4jAPI {
    Logger logger = LoggerFactory.getLogger(Neo4jAPI.class);
    Driver driver = null;
    Calendar calendar = Calendar.getInstance();
    int YY = calendar.get(Calendar.YEAR);
    int MM = calendar.get(Calendar.MONTH) + 1;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ssss");
    PropertiesUtil propertiesUtil = new PropertiesUtil("bolt.properties");

    public Neo4jAPI(Driver driver) {
        this.driver = driver;
    }
    //    public Neo4jAPI() {
    //
    //    }

    /**
     * 获取所有标签名称
     *
     * @param
     * @return
     */
    public String GetAllLabels() {
        Session session = null;
        String Res = "";
        StatementResult Rset = null;
        Record rec;
        JSONObject jobj = new JSONObject();


        try {
            session = driver.session(AccessMode.READ);
            String key = "labels(n)";
            String val = "count(*)";
            String query = "MATCH (n) RETURN labels(n), count(*)";

            Rset = session.run(query);
            writeLog(query);

            while (Rset.hasNext()) {
                rec = Rset.next();
                //                System.out.println(rec);
                String lbl = rec.get(key).toString();
                jobj.put(lbl.substring(1, lbl.length() - 1), rec.get(val).toString());
            }

            Res = jobj.toJSONString();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            CloseSession(session);
            return Res;
        }
    }


    /**
     * 获取所有关系名称
     *
     * @param
     * @return
     */
    public String GetAllRelation() {
        Session session = null;
        String Res = "";
        StatementResult Rset = null;
        Record rec;
        JSONObject jobj = new JSONObject();

        try {
            session = driver.session(AccessMode.READ);
            String key = "type(r)";
            String val = "count(*)";
            String query = "MATCH (m)-[r]-(n) RETURN type(r), count(*)";

            Rset = session.run(query);

            while (Rset.hasNext()) {
                rec = Rset.next();

                String lbl = rec.get(key).toString();
                jobj.put(lbl.substring(1, lbl.length() - 1), rec.get(val).toString());
            }

            Res = jobj.toJSONString();

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            CloseSession(session);
            return Res;
        }
    }

    /**
     * 处理所有节点的申请
     *
     * @param name   节点名称
     * @param label  标签名称
     * @param prop   节点属性
     * @param origin 原始节点
     * @param newval 新节点
     * @param option 操作标志 (-1:删除,0:查询,1:更新/添加,)
     * @return
     */
    public Map<String, String> ProcessNode(String name, String label, JSONObject prop, JSONObject origin,
                                           JSONObject newval, String option) {
        Map<String, String> Res = new HashMap<>();

        try {
            switch (option) {
                case "-1":
                    Res = RemoveNode(name, label);
                    break;
                case "0":
                    Res = GetNode(name, label, prop);
                    break;
                case "1":
                    if (origin != null) {
                        name = origin.get(Neo4jModel.name).toString();
                        label = origin.get(Neo4jModel.label).toString();
                    }
                    if (newval != null) {
                        prop = newval.getJSONObject(Neo4jModel.property);
                    }
                    UpsertNode(name, label, origin, newval);
                    Res = GetNode(name, label, prop);
                    break;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return Res;
        }
    }

    /**
     * 查询节点
     *
     * @param name  节点名称
     * @param label 标签名称
     * @param prop  节点属性
     * @return
     */
    public Map<String, String> GetNode(String name, String label, JSONObject prop) {

        Map<String, Object> coll = new HashMap<>();
        Map<String, String> Res = new HashMap<>();
        StatementResult Rset = null;
        Session session = null;
        Map<String, Map<String, String>> Result = new HashMap<>();
        int count = 0;

        try {
            System.out.println("name:\t" + name + "\tlabel:\t" + label);
            session = driver.session(AccessMode.READ);

            String query = "MATCH (n";

            if (name.length() == 0) {
                if (label.trim().length() > 0) {
                    query += ":" + label.trim();
                }

                if (name.trim().length() > 0) {
                    query += "{" + Neo4jModel.name + ":'" + name + "'}";
                }
                query += ") ";

                if (prop.size() > 0) {
                    query += " WHERE ";
                    for (String key : prop.keySet()) {
                        query += "n." + key + "='" + prop.get(key) + "'";
                        count += 1;
                        if (count < prop.size()) {
                            query += " AND ";
                        }
                    }
                }
            } else if (label.length() == 0) {
                String[] namelist = name.split("，|,|、");

                query += ") WHERE ";

                for (String item : namelist) {
                    if (item.indexOf("*") >= 0) {

                        item = item.replaceAll("\\*", ".*");
                        query += "n.name=~'" + item + "' or ";
                    } else {
                        query += "n.name='" + item + "' or ";
                    }
                }

                query = query.substring(0, query.length() - 3);
            }

            query += " RETURN n LIMIT 50";

            Rset = session.run(query);

            writeLog(query);

            while (Rset.hasNext()) {
                Record rec = Rset.next();
                Node node = rec.get("n").asNode();
                String lbl = "";
                name = "";
                Result = new HashMap<>();

                Iterator<String> lbls = node.labels().iterator();

                while (lbls.hasNext()) {
                    lbl = lbls.next();
                    Result.put(lbl, new HashMap<>());
                }

                Map<String, Object> property = node.asMap();
                for (String key : property.keySet()) {
                    Result.get(lbl).put(key, property.get(key).toString());

                    if (key.equals("name")) {
                        name = property.get(key).toString();
                    }
                }

                if (coll.get(name) == null) {
                    coll.put(name, (Object) Result);
                } else {
                    JSONObject jobj = JSONObject.parseObject(JSONUtils.toJSONString(coll.get(name)));
                    jobj.put(lbl, Result.get(lbl));
                    coll.put(name, (Object) jobj);
                }

                //                System.out.println(name + "\t" + lbl + "\t" + JSONUtils.toJSONString(Result));
            }

            for (String key : coll.keySet()) {
                String val = JSONUtils.toJSONString(coll.get(key));
                Res.put(key, val);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            CloseSession(session);
            return Res;
        }
    }

    /**
     * 更新节点
     *
     * @param name   节点名称
     * @param label  标签名称
     * @param origin 原始节点
     * @param newval 新节点
     * @return
     */
    public void UpsertNode(String name, String label, JSONObject origin, JSONObject newval) {
        Map<String, String> Res = new HashMap<>();
        Session session = null;
        String query, createset, matchset, val;
        JSONObject prop = new JSONObject();

        try {
            session = driver.session(AccessMode.WRITE);

            if (origin != null) {
                prop = newval.getJSONObject(Neo4jModel.property);
            }

            query = "MERGE (n";
            createset = " on CREATE SET ";
            matchset = " on MATCH SET ";

            if (label.trim().length() > 0) {
                query += ":" + label;
            }

            if (name.trim().length() > 0) {
                query += "{name:'" + name + "'}";
                createset += " n.name='" + name + "', ";
            }

            for (String key : prop.keySet()) {
                val = prop.get(key).toString();
                createset += " n." + key + "='" + val + "', ";
                matchset += " n." + key + "='" + val + "', ";
            }

            createset = createset.substring(0, createset.length() - 2);
            matchset = matchset.substring(0, matchset.length() - 2);
            query += ")" + createset + matchset;

            session.run(query);

            writeLog(query);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            CloseSession(session);
        }
    }

    /**
     * 删除节点
     *
     * @param name  节点名称
     * @param label 标签名称
     * @return
     */
    public Map<String, String> RemoveNode(String name, String label) {
        Session session = null;

        Map<String, String> Res = new HashMap<>();

        StatementResult Rset = null;
        String query = "";
        try {
            session = driver.session(AccessMode.WRITE);

            String cond = "MATCH (n";

            if (label.trim().length() > 0) {
                cond += ":" + label.trim();
            }
            cond += ") ";

            if (name.trim().length() > 0) {
                cond += " WHERE n.name = " + name;
            }

            query = cond + " DETACH DELETE n; ";

            session.run(query);
            writeLog(query);

            Res = GetNode(name, label, new JSONObject());
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            CloseSession(session);
            return Res;
        }
    }


    /**
     * 获取节点信息
     *
     * @param node 节点
     * @return
     */
    public String GetNodeInfo(Node node) {
        String res = "";
        String lbl = "", name = "";
        Map<String, Map<String, String>> resmap = new HashMap<>();
        Map<String, String> content = new HashMap<>();
        try {
            Iterator<String> lbls = node.labels().iterator();

            while (lbls.hasNext()) {
                lbl += lbls.next() + ",";
            }
            lbl = lbl.substring(0, lbl.length() - 1);

            content.put(Neo4jModel.label, lbl);

            Map<String, Object> property = node.asMap();
            for (String key : property.keySet()) {
                content.put(key, property.get(key).toString());
            }

            if (content.get(Neo4jModel.name) != null && content.get(Neo4jModel.name).toString().trim().length() > 0) {
                name = content.get(Neo4jModel.name).toString();
            } else if ((content.get("title") != null && content.get("title").toString().trim().length() > 0)) {
                name = content.get("title").toString();
            } else {
                name = "name";
            }

            resmap.put(name, content);
            res = JSONUtils.toJSONString(resmap);
            //            System.out.println(res);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return res;
        }
    }

    /**
     * 处理所有路径的申请
     *
     * @param name     路径名称
     * @param label    标签名称
     * @param start    起始节点
     * @param end      终止节点
     * @param oldrel   原始关系名称
     * @param relation 新关系名称
     * @param option   操作标志 (-1:删除,0:查询,1:更新/添加,)
     * @return
     */
    public Map<String, String> ProcessPath(String name, String label, String level, JSONObject start,
                                           JSONObject end, String oldrel, String relation, String option) {
        Map<String, String> Res = new HashMap<>();

        try {
            switch (option) {
                case "-1":
                    RemovePath(start, end, oldrel);
                    //                    Res = GetPath(name, label, "1");
                    break;
                case "0":
                    Res = GetPath(name, label, level);
                    break;
                case "1":
                    if (start != null) {
                        name = start.get(Neo4jModel.name).toString();
                        label = start.get(Neo4jModel.label).toString();
                    }
                    UpsertPath(start, end, oldrel, relation);
                    Res = GetPath(name, label, "1");
                    break;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return Res;
        }
    }

    /**
     * 获取路径
     *
     * @param name  路径名称
     * @param label 标签名称
     * @param level 路径层级
     * @return
     */
    public Map<String, String> GetPath(String name, String label, String level) {
        Session session = null;
        StatementResult result;
        Map<String, Map<String, String>> coll = new HashMap<>();
        Map<String, String> route = new HashMap<>();
        Record rec;
        int count = 0;
        String Path = "";
        String query = "";
        Map<String, String> Res = new HashMap<>();

        try {
            session = driver.session(AccessMode.READ);

            if (label.equals("Relation")) {
                if (level.length() == 0 || level.equals("0")) {
                    level = "2";
                }
                query = "MATCH p=((n{name:'" + name + "'})-[*.." + level + "]-(e)) RETURN p";
            } else if (name.length() == 0) {
                level = "2";
                query = "MATCH p=((n:" + label + ")-[*.." + level + "]-(e)) RETURN p";
            } else {
                if (level.length() == 0) {
                    level = "3";
                }

                String[] items = name.split(",|，|、");
                query = "MATCH p=((n)-[*.." + level + "]-(c:" + label + ")) WHERE n.name in [";
                for (int i = 0; i < items.length; i++) {
                    query += "'" + items[i] + "',";
                }
                query = query.substring(0, query.length() - 1);
                query += "] ";
                query += "RETURN p";
            }

            result = session.run(query);

            writeLog(query);
            System.out.println(query);

            while (result.hasNext()) {
                rec = result.next();
                Path path = rec.get("p").asPath();
                Iterator<Path.Segment> iterator = path.iterator();

                while (iterator.hasNext()) {
                    route = new HashMap<>();
                    Path.Segment element = iterator.next();
                    Node start = element.start();
                    String snode = GetNodeInfo(start);

                    Relationship relation = element.relationship();
                    String rel = relation.type();

                    Node end = element.end();
                    String enode = GetNodeInfo(end);

                    if (start.id() == relation.startNodeId()) {
                        route.put("start", snode);
                        route.put("end", enode);
                    } else if (start.id() == relation.endNodeId()) {
                        route.put("start", enode);
                        route.put("end", snode);
                    }

                    route.put("relation", rel);

                    coll.put(Integer.toString(count), route);
                    count += 1;
                }
            }

            Res.put("path", JSONUtils.toJSONString(coll));

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            CloseSession(session);
            return Res;
        }
    }

    /**
     * 更新路径
     *
     * @param start    起始节点
     * @param end      终止节点
     * @param oldrel   原始关系名称
     * @param relation 新关系名称
     * @return
     */
    public void UpsertPath(JSONObject start, JSONObject end, String oldrel, String relation) {
        Session session = null;
        String query = "";

        try {
            session = driver.session(AccessMode.WRITE);

            query = "MATCH (s:" + start.getString(Neo4jModel.label);

            if (start.get(Neo4jModel.name) != null) {
                query += "{name:'" + start.getString(Neo4jModel.name) + "'})";
            }

            query += "-[r:" + oldrel + "]->";

            query += "(e:" + end.getString(Neo4jModel.label);

            if (end.get(Neo4jModel.name) != null) {
                query += "{name:'" + end.getString(Neo4jModel.name) + "'}) ";
            }

            query += " CREATE (s)-[r1:" + relation + "]->(e) ";
            query += "SET r1 = r WITH r DELETE r";

            session.run(query);

            writeLog(query);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            CloseSession(session);
        }
    }

    /**
     * 删除路径
     *
     * @param start  起始节点
     * @param end    终止节点
     * @param oldrel 原始关系名称
     * @return
     */
    public void RemovePath(JSONObject start, JSONObject end, String oldrel) {

        Session session = null;
        String query = "";

        try {
            session = driver.session(AccessMode.WRITE);

            query = "MATCH (s:" + start.getString(Neo4jModel.label);

            if (start.get(Neo4jModel.name) != null) {
                query += "{name:'" + start.getString(Neo4jModel.name) + "'})";
            }

            query += "-[r:" + oldrel + "]->";

            query += "(e:" + end.getString(Neo4jModel.label);

            if (end.get(Neo4jModel.name) != null) {
                query += "{name:'" + end.getString(Neo4jModel.name) + "'}) ";
            }

            query += " DELETE r; ";

            session.run(query);

            writeLog(query);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            CloseSession(session);
        }
    }

    /**
     * 只包含返回确诊的
     *
     * @param keys
     * @return
     */
    public Map<String, Map<String, String>> getCondition(String[] keys, String webDiag) {
        Map<String, Map<String, String>> diseaseCondition = new LinkedHashMap<>();
        List<String> newList = new ArrayList<>();
        ArrayList<String> fildList = new ArrayList<>();
        //输出确诊集合
        Set<String> quezhen = new LinkedHashSet<>();
        for (String fild : keys) {
            fildList.add("\"" + fild.trim() + "\"");
        }
        logger.info("根据 " + fildList + " 这些词推送图谱诊断!!!");
//        System.out.println("原始词为:\n"+fildList);
        Session session = null;
        StatementResult result = null;
        String query = "";
        try {
            session = driver.session(AccessMode.WRITE);
            logger.info("session 为: " + session);
            //第一步查询是否有组合的词
            query = propertiesUtil.getProperty("searchCollection1").replace("fildList", fildList.toString());
            logger.info("开始查询是否有组合的词,查询语句为: \n"+query);
//            System.out.println("查找是否有组合词语句:\n"+query);
            result = session.run(query);
            while (result.hasNext()) {
                Record next = result.next();
                String jundgement = next.get("jundgement").toString();
                String standName = next.get("standName").toString();
                if ("TRUE".equals(jundgement)) {
                    fildList.add(standName);
                }
            }
            query = propertiesUtil.getProperty("serchCollect").replace("fildList", fildList.toString());
            logger.info("开始查询近义词,查询语句为:\n"+query);
            result = session.run(query);
            while (result.hasNext()) {
                Record record = result.next();
                String fild = record.get("fild").toString();
                List<Object> typeCollect = record.get("typeCollect").asList();
                //如果不包含诊断依据就找它的同义词,否则就要这个词
                if ("近义词".equals(typeCollect.get(0)) && typeCollect.size() == 1) {
                    query = "match(l)-[r:近义词]->(h) where l.name=" + fild + " return h.name as js";
                    logger.info("如果有近义词就替换,查询语句为:\n"+query);
                    StatementResult jinyiResult = session.run(query);
                    while (jinyiResult.hasNext()) {
                        Record next = jinyiResult.next();
                        String js = next.get("js").toString();
                        fildList.remove(fild);
                        fildList.add(js);
                    }
                }
            }
            newList.addAll(fildList);
            int i = 1;
            while (newList.size() > 0) {
                query = propertiesUtil.getProperty("searchCondition1").replace("newList", newList.toString()).replace("fildList", fildList.toString());
                logger.info("第"+i+"次查询符合的诊断依据为:\n"+query);
//                System.out.println("第"+i+"次的查询语句为: \n"+query);
                i++;
                result = session.run(query);
                newList.clear();
                while (result.hasNext()) {
                    Record record = result.next();
                    String condition = record.get("condition").toString();
                    newList.add(condition);
                    fildList.add(condition);
                }
            }
            //第三步查找确诊
            query = propertiesUtil.getProperty("searchQuezhen").replace("fildList", fildList.toString());
            logger.info("开始查找确诊疑诊,语句为:\n"+query);
//            System.out.println("查找确诊的语句为: \n"+query);
            result = session.run(query);
            while (result.hasNext()) {
                Record record = result.next();
                String quezhenName = record.get("name").toString().replace("\"", "");
                String conditionType = record.get("relationType").toString().replace("\"", "");
                if ("确诊".equals(conditionType)) {
                    quezhen.add(quezhenName);
                } else if ("拟诊".equals(conditionType)) {
                    quezhen.add(quezhenName);
                }
            }
            for (String qu : quezhen) {
                Map<String, String> dis_res = new HashMap<>();
                dis_res.put("确诊", "");
                diseaseCondition.put(qu, dis_res);
                logger.info("图谱推出的诊断为: " + qu);
            }
            Set<String> queSets = diseaseCondition.keySet();
            if (webDiag != null && webDiag.trim() != "") {
                String[] webDiagSplits = webDiag.split(",");
                String mainDiag = webDiagSplits[0];
                query = propertiesUtil.getProperty("searchDifferentialDiagnose").replace("mainDis", mainDiag);
                logger.info("根据界面诊断查询鉴别诊断,界面诊断为:"+mainDiag+"查询语句为:\n"+query);
                result = session.run(query);
                while (result.hasNext()) {
                    Record record = result.next();
                    List<Object> coll = record.get("coll").asList();
                    if (coll != null && coll.size() > 0) {
                        for (Object o : coll) {
                            if (queSets.contains(o.toString().replace("\"", ""))) {
                                Map<String, String> stringStringMap = diseaseCondition.get(o.toString().replace("\"", ""));
                                stringStringMap.put("鉴别诊断", "");
                                diseaseCondition.put(o.toString().replace("\"", ""), stringStringMap);
                            } else {
                                Map<String, String> diffMap = new HashMap<>();
                                diffMap.put("鉴别诊断", "");
                                diseaseCondition.put(o.toString().replace("\"", ""), diffMap);
                            }
                        }
                    }
                }
            }
            //判断急诊
            Set<String> disSet = diseaseCondition.keySet();
            List<String> newDis = new ArrayList<>();
            if(disSet.size()>0){
                for (String dis:disSet) {
                    newDis.add("\""+dis+"\"");
                }
            }
            query =propertiesUtil.getProperty("searchEmergency").replace("disList",newDis.toString());
            logger.info("判断图谱推出的诊断中是否有急诊,判断语句为:\n"+query);
            result = session.run(query);
            while (result.hasNext()) {
                Record record = result.next();
                String emDis = record.get("emDis").toString();
                Map<String, String> stringStringMap = diseaseCondition.get(emDis.replace("\"", ""));
                stringStringMap.put("急诊", "");
                diseaseCondition.put(emDis.replace("\"", ""), stringStringMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            CloseSession(session);
            return diseaseCondition;
        }
    }

    /**
     * 新结构,包含关联词
     *
     * @param keys
     * @param webDiag
     * @return
     */
    public Map<String, Object> getNewCondition(String[] keys, String webDiag) {
        Map<String, Object> conditionMap = new HashMap<>();
        Map<String, Map<String, String>> diseaseCondition = new LinkedHashMap<>();
        Map<String, Map<String, String>> diseaseCondition1 = new LinkedHashMap<>(16, 0.75f, true);
        Map<String,Map<String,String>> neoPushMap = new HashMap<>();
        List<String> newList = new ArrayList<>();
        List<String> fildList = new ArrayList<>();
        List<String> startList = new ArrayList<>();
        //输出确诊集合
        Set<String> quezhen = new LinkedHashSet<>();
        for (String fild : keys) {
            fildList.add("\"" + fild.trim() + "\"");
        }
        logger.info("根据 " + fildList + " 这些词推送图谱诊断!!!");
        Session session = null;
        StatementResult result = null;
        String query = "";
        try {
            session = driver.session(AccessMode.WRITE);
            logger.info("session 为: " + session);
            //第一步查询输入的词所在number
            query = propertiesUtil.getProperty("searchNumColl").replace("startList", fildList.toString());
            System.out.println("查找词所在的number \n" + query);
            result = session.run(query);
            while (result.hasNext()) {
                Record next = result.next();
                String v = next.get("v").toString();
                startList.add(v);
            }
            newList.addAll(startList);
            int i = 1;
            while (newList.size() > 0) {
                query = propertiesUtil.getProperty("searchNewCondition").replace("newList", newList.toString()).replace("fildList", startList.toString());
                logger.info("第" + i + "次查询conditon语句 \n" + query);
                i++;
                result = session.run(query);
                newList.clear();
                while (result.hasNext()) {
                    Record record = result.next();
                    String condition = record.get("condition").toString();
                    newList.add(condition);
                    startList.add(condition);

                }
            }
            String que="";
            //第三步查找确诊
            query = propertiesUtil.getProperty("searchDis").replace("startList", startList.toString());
            logger.info("查询确诊的语句 \n" + query);
            result = session.run(query);
            while (result.hasNext()) {
                Record record = result.next();
                String quezhenName = record.get("name").toString().replace("\"", "");
                String conditionType = record.get("relationType").toString().replace("\"", "");
                que = conditionType;
                Map<String, String> queMap = neoPushMap.get(quezhenName);
                if(queMap != null && queMap.size()>0){
                    if("拟诊".equals(que) &&queMap.keySet().contains("确诊") ){
                        continue;
                    }
                    if(queMap.keySet().contains("拟诊") && "确诊".equals(que) ){
                        queMap.remove("拟诊");
                        queMap.put(que,"");
                        neoPushMap.put(quezhenName,queMap);
                    }else if(que.equals("警惕")){
                        queMap.put("警惕","");
                        neoPushMap.put(quezhenName,queMap);
                    } else if(que.equals("拟诊")){
                        queMap.put("拟诊","");
                        neoPushMap.put(quezhenName,queMap);
                    }else {
                        queMap.put(que,"");
                        neoPushMap.put(quezhenName,queMap);
                    }
                }else {
                    Map<String,String> newMap = new HashMap<>();
                    newMap.put(que,"");
                    neoPushMap.put(quezhenName,newMap);
                }

            }
            Map<String,Map<String,String>> queHighMap = new HashMap<>();
            Map<String,Map<String,String>> highMap = new HashMap<>();
            Map<String,Map<String,String>> quezhenMap = new HashMap<>();
            for (Map.Entry<String,Map<String,String>> l:neoPushMap.entrySet()) {
                String dis = l.getKey();
                Set<String> typeSet = l.getValue().keySet();
                Map<String,String> con = new HashMap<>();

                if(typeSet.size() == 2){
                    for (String type:typeSet) {
                        con.put(type,"");
                    }
                    queHighMap.put(dis,con);
                }
                if(typeSet.size() == 1 && (typeSet.contains("确诊") || typeSet.contains("拟诊"))){
                    for (String type:typeSet) {
                        con.put(type,"");
                    }
                    quezhenMap.put(dis,con);
                }
                if(typeSet.size() == 1 && typeSet.contains("警惕")){
                    for (String type:typeSet) {
                        con.put(type,"");
                    }
                    highMap.put(dis,con);
                }
            }
            if(queHighMap != null && queHighMap.size()>0){
                Set<String> queHighSet = queHighMap.keySet();
                for (String dis:queHighSet) {
                    Map<String,String> k = new HashMap<>();
                    k.put("确诊","");
                    k.put("警惕","");
                    diseaseCondition.put(dis,queHighMap.get(dis));
                }
                if(quezhenMap != null && quezhenMap.size()>0){
                    Set<String> queDis = quezhenMap.keySet();
                    for (String dis:queDis) {
                        Map<String,String> k = new HashMap<>();
                        k.put("确诊","");
                        diseaseCondition.put(dis,quezhenMap.get(dis));
                    }
                }
            }else {
                if(quezhenMap != null && quezhenMap.size()>0){
                    Set<String> queDis = quezhenMap.keySet();
                    for (String dis:queDis) {
                        Map<String,String> k = new HashMap<>();
                        k.put("确诊","");
                        diseaseCondition.put(dis,quezhenMap.get(dis));
                    }
                }
                if(highMap != null && highMap.size()>0){
                    Set<String> highSet = highMap.keySet();
                    for (String dis:highSet) {
                        Map<String,String> k = new HashMap<>();
                        k.put("警惕","");
                        diseaseCondition.put(dis,highMap.get(dis));
                    }
                }
            }
            Set<String> queSets = diseaseCondition.keySet();
            if (webDiag != null && webDiag.trim() != "") {
                String[] webDiagSplits = webDiag.split(",");
                String mainDiag = webDiagSplits[0];
                query = propertiesUtil.getProperty("searchDifferentialDiagnose").replace("mainDis", mainDiag);
                logger.info("查找鉴别诊断,语句为:\n"+query);
                result = session.run(query);
                while (result.hasNext()) {
                    Record record = result.next();
                    List<Object> coll = record.get("coll").asList();
                    if (coll != null && coll.size() > 0) {
                        for (Object o : coll) {
                            if (queSets.contains(o.toString().replace("\"", ""))) {
                                Map<String, String> stringStringMap = diseaseCondition.get(o.toString().replace("\"", ""));
                                stringStringMap.put("鉴别诊断", "");
                                diseaseCondition.put(o.toString().replace("\"", ""), stringStringMap);
                            } else {
                                Map<String, String> diffMap = new HashMap<>();
                                diffMap.put("鉴别诊断", "");
                                diseaseCondition.put(o.toString().replace("\"", ""), diffMap);
                            }
                        }
                    }
                }
                //查找是否有页面急诊
                List<String> webDiagList = new ArrayList<>();
               /* for (String wd:webDiagSplits) {
                    webDiagList.add("\'"+wd+"\'");
                }*/
                webDiagList.add("\'"+webDiagSplits[0]+"\'");
                query =propertiesUtil.getProperty("searchEmergency").replace("disList",webDiagList.toString());
                result = session.run(query);
                while (result.hasNext()) {
                    Record record = result.next();
                    String emDis = record.get("emDis").toString();
                    int em = record.get("em").asInt();//急诊
                    Map<String, String> stringStringMap = neoPushMap.get(emDis.replace("\"", ""));
                    if( stringStringMap == null ){
                        stringStringMap = new HashMap<>();
                    }
                    if(em == 1){
                        stringStringMap.put("页面急诊", "");
                        diseaseCondition.put(emDis.replace("\"", ""), stringStringMap);
                    }

                }
            }
            List<String> newDis = new ArrayList<>();
            //判断急诊
            for (Map.Entry<String, Map<String, String>> fs:diseaseCondition.entrySet()) {
                String dis = fs.getKey();
                Set<String> leiSet = fs.getValue().keySet();
                if(leiSet.contains("确诊") || leiSet.contains("拟诊")){
                    newDis.add("\""+dis+"\"");
                }
            }
            query =propertiesUtil.getProperty("searchEmergency").replace("disList",newDis.toString());
            logger.info("判断图谱推出的诊断中是否有急诊,判断语句为:\n"+query);
            result = session.run(query);
                while (result.hasNext()) {
                Record record = result.next();
                String emDis = record.get("emDis").toString();
                int em = record.get("em").asInt();//急诊
                Map<String, String> stringStringMap = neoPushMap.get(emDis.replace("\"", ""));
                if(em == 1){
                    stringStringMap.put("急诊", "");
                }
                    diseaseCondition.put(emDis.replace("\"", ""), stringStringMap);
            }
           /* Set<String> queset = new LinkedHashSet<>();
            Set<String> ll = new LinkedHashSet<>();
            Set<String> kk = new LinkedHashSet<>();
            for (Map.Entry<String,Map<String,String>> l:diseaseCondition.entrySet()) {
                if(l.getValue().keySet().contains("确诊")){
                    ll.add(l.getKey());
                    queset.add(l.getKey());
                }else {
                    kk.add(l.getKey());
                }
            }
            ll.addAll(kk);
            for (String dis:ll) {
                Map<String, String> stringStringMap = diseaseCondition.get(dis);
                for (Map.Entry<String,String>sd:stringStringMap.entrySet()) {
                    if("拟诊".equals(sd.getKey())){
                        stringStringMap.remove(sd.getKey());
                        stringStringMap.put("确诊","");
                        break;
                    }
                }
                diseaseCondition1.put(dis,stringStringMap);
            }
            conditionMap.put("确诊",queset);*/
            conditionMap.put("全部诊断",diseaseCondition);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            CloseSession(session);
            return conditionMap;
        }
    }

    /**
     * 不良反应推送
     */
    public Set<String> getUe(String[] keys) {
        //查找不良反应推送
        Set<String> indSet = new HashSet<>();
        List<String> newList = new ArrayList<>();
        List<String> fildList = new ArrayList<>();
        List<String> startList = new ArrayList<>();
        for (String fild : keys) {
            fildList.add("\"" + fild.trim() + "\"");
        }
        logger.info("根据 " + fildList + " 这些词推送不良反应!!!");
        Session session = null;
        StatementResult result = null;
        String query = "";
        try {
            session = driver.session(AccessMode.WRITE);
            logger.info("session 为: " + session);
            //第一步查询输入的词所在number
            query = propertiesUtil.getProperty("searchNumColl").replace("startList", fildList.toString());
            logger.info("查找词所在的number \n" + query);
            result = session.run(query);
            while (result.hasNext()) {
                Record next = result.next();
                String v = next.get("v").toString();
                startList.add(v);
            }
            newList.addAll(startList);
            int i = 1;
            while (newList.size() > 0) {
                query = propertiesUtil.getProperty("searchNewCondition").replace("newList", newList.toString()).replace("fildList", startList.toString());
                logger.info("第" + i + "次查询conditon语句 \n" + query);
                i++;
                result = session.run(query);
                newList.clear();
                while (result.hasNext()) {
                    Record record = result.next();
                    String condition = record.get("condition").toString();
                    newList.add(condition);
                    startList.add(condition);
                }
            }
            query = propertiesUtil.getProperty("searchUe").replace("fildList", startList.toString());
            logger.info("查找界面输入是否有不良反应,处理语句为:\n"+query);
            result = session.run(query);
            while (result.hasNext()) {
                Record record = result.next();
                String indName = record.get("name").toString().replace("\"", "");
                indSet.add(indName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            CloseSession(session);
            return indSet;
        }
    }

    /**
     * 指标推送
     */
    public Set<String> getInd(String[] keys,String sex,int age) {
        //查找指标推送
        Set<String> indSet = new HashSet<>();
        List<String> newList = new ArrayList<>();
        List<String> startList = new ArrayList<>();
        ArrayList<String> fildList = new ArrayList<>();
        for (String fild : keys) {
            fildList.add("\"" + fild.trim() + "\"");
        }
        logger.info("根据 " + fildList + " 这些词推送指标!!!");
        Session session = null;
        StatementResult result = null;
        String query = "";
        try {
            session = driver.session(AccessMode.WRITE);
            //第一步查询输入的词所在number
            query = propertiesUtil.getProperty("searchNumColl").replace("startList", fildList.toString());
            logger.info("查找词所在的number \n" + query);
            result=session.run(query);
            while (result.hasNext()) {
                Record next = result.next();
                String v = next.get("v").toString();
                startList.add(v);
            }
            newList.addAll(startList);
            int i = 0;
            while (newList.size() > 0) {
                query = propertiesUtil.getProperty("searchNewCondition").replace("newList", newList.toString()).replace("fildList", startList.toString());
                logger.info("第" + i + "次查询conditon语句 \n" + query);
                i++;
                result = session.run(query);
                newList.clear();
                while (result.hasNext()) {
                    Record record = result.next();
                    String condition = record.get("condition").toString();
                    newList.add(condition);
                    startList.add(condition);
                }
            }
            query = propertiesUtil.getProperty("searchIndication").replace("fildList", startList.toString()).replace("age",String.valueOf(age)).replace("Sex",sex);
            logger.info("查找可以推送的指标\n"+query);
            result = session.run(query);
            while (result.hasNext()) {
                Record record = result.next();
                String indName = record.get("name").toString().replace("\"", "");
                indSet.add(indName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            CloseSession(session);
            return indSet;
        }
    }

    /**
     * 指标推送,检查预警
     */
    public Map<String,String> getNewInd(String[] keys) {
        //查找指标推送
        Map<String ,String> indMap = new HashMap<>();
        List<String> fildList = new ArrayList<>();
        for (String fild : keys) {
            fildList.add("\"" + fild.trim() + "\"");
        }
        logger.info("根据 " + fildList + " 这些词推送指标!!!");
        Session session = null;
        StatementResult result = null;
        String query = "";
        try {
            session = driver.session(AccessMode.WRITE);
            //第一步查询输入的词所在number
            query = "match(t:Temporary)-[r:属于]->(n:NewCondition)-[r1:诊断依据]->(n1:NewCondition)-[r2:拟诊]->(n2:NewIndicators) \n" +
                    "where t.name in "+fildList+" return n2.name as name";
            System.out.println(query);
            result = session.run(query);
            while (result.hasNext()) {
                Record record = result.next();
                String newIndName = record.get("name").toString();
                StringBuffer s = new StringBuffer();
                query = "match(n2:NewIndicators)-[r:表现]->(t:Temporary) where n2.name="+newIndName+" return collect(t.name) as names";
                StatementResult sr = session.run(query);
                while (sr.hasNext()){
                    Record next = sr.next();
                    List<Object> names = next.get("names").asList();
                    if(names.size()>0){
                        for (Object o:names) {

                            if(fildList.indexOf("\""+o.toString()+"\"") >= 0){
                                s.append(o.toString().replace("\"", ""));
                            }
                        }
                    }
                }
                indMap.put(newIndName.replace("\"", ""),s.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            CloseSession(session);
            return indMap;
        }
    }
    /**
     * 多疾病下治疗方案
     *
     * @param disease
     * @param filds
     * @return
     */
    public Map<String, String> getMulDiseaseTreat(String disease, String filds) {
        Session session = null;
        NumberFormat nf = NumberFormat.getPercentInstance();
        Map<String, String> resultMap = new HashMap<>();
        String[] diseaseArray = disease.split(",|，|、");
        List<String> diseaseList = new ArrayList<>();//诊断数组
        for (int i = 0; i < diseaseArray.length; i++) {
            diseaseList.add(diseaseArray[i]);
        }
        Map<String, ArrayList> diseFilds = new HashMap<>();
        for (int i = 0; i < diseaseList.size(); i++) {
            String[] fildsArray = filds.split(",");
            ArrayList<String> fildsList = new ArrayList<>();//其他条件数组
            for (String fild : fildsArray) {
                fildsList.add("\'" + fild + "\'");
            }
            for (int j = 0; j < diseaseList.size(); j++) {
                if (i != j) {
                    fildsList.add("\'" + diseaseList.get(j) + "\'");
                }
            }
            diseFilds.put(diseaseList.get(i), fildsList);
        }
        try {
            session = driver.session(AccessMode.WRITE);
            session.writeTransaction(new TransactionWork<Integer>() {
                @Override
                public Integer execute(Transaction tx) {
                    StatementResult result = null;
                    String query = "";
                    for (Map.Entry<String, ArrayList> df : diseFilds.entrySet()) {
                        String diseaseName = df.getKey();//疾病
                        ArrayList value = df.getValue();//其他条件
                        StringBuffer s1 = new StringBuffer();
                        s1.append("match (d:Disease{name:'" + disease + "'})-[r0:推荐]->(m:Drugs)-[:包含]->(n:Medicine),(d:Disease)-[r1:推荐]->(n)");
                        s1.append("\n");
                        s1.append("where r0.p<6").append("\n");
                        s1.append("return m.name as 类, r0.p as sort, n.name as 药物, r1.rate as a order by sort , a desc");
                        query = s1.toString();
                        result = tx.run(query);
                        LinkedHashMap<String, LinkedHashMap<String, String>> contentMap = new LinkedHashMap<>();
                        while (result.hasNext()) {
                            Record record = result.next();
                            String[] splits = record.values().toString().split(",");
                            String drugs = splits[0].replace("[", "").replace("\"", "");
                            if (contentMap.containsKey(drugs)) {
                                LinkedHashMap<String, String> stringStringHashMap = contentMap.get(drugs);
                                stringStringHashMap.put(splits[2].replace("\"", ""), splits[3].replace("]", ""));
                                contentMap.put(drugs, stringStringHashMap);
                            } else {
                                LinkedHashMap<String, String> sa = new LinkedHashMap<>();
                                sa.put(splits[2].replace("\"", ""), splits[3].replace("]", ""));
                                contentMap.put(drugs, sa);
                            }
                        }

                        HashMap<String, String> shortLargeMap = new HashMap<>();
                        //大项查询
                        query = "match (n:Disease{name:'" + diseaseName + "'})-[:推荐]->(d:Drugs)<-[:包含]-(m) return d.name as short,m.name as large";
                        result = tx.run(query);
                        while (result.hasNext()) {
                            Record record = result.next();
                            String aShort = record.get("short").toString().replace("\"", "");
                            String large = record.get("large").toString().replace("\"", "");
                            shortLargeMap.put(aShort, large + "(" + aShort + ")");
                        }
                        LinkedHashMap<String, LinkedHashMap<String, String>> mapSortValueDa = new LinkedHashMap<>();
                        for (Map.Entry<String, LinkedHashMap<String, String>> f : contentMap.entrySet()
                                ) {
                            String key = f.getKey();
                            if (shortLargeMap.get(key) != null) {
                                mapSortValueDa.put(shortLargeMap.get(key), contentMap.get(key));
                            } else {
                                mapSortValueDa.put(key, contentMap.get(key));
                            }
                        }
                        /**
                         * mapSortValueDa是包含大小项的Map
                         * 抗胃酸药(质子泵抑制剂)  兰索拉唑  0.85
                         */

                        Map<String, String> medicationUseMap = new HashMap<>();//key:药名 value:禁忌(慎用)
                        StringBuffer fildBuffer = new StringBuffer();
                        fildBuffer.append("match (n:Disease{name:'" + diseaseName + "'})-[:推荐]->(d)<-[r0:慎用]-(m)").append("\n");
                        fildBuffer.append("where m.name in " + value + "").append("\n");
                        fildBuffer.append("return d.name as ff,type(r0) as hh").append("\n").append("union\n");
                        fildBuffer.append("match (n:Disease{name:'" + diseaseName + "'})-[:推荐]->(d)<-[r0:忌用]-(m)\n");
                        fildBuffer.append("where m.name in " + value + "").append("\n");
                        fildBuffer.append("return d.name as ff,type(r0) as hh");
                        query = fildBuffer.toString();
                        result = tx.run(query);
                        while (result.hasNext()) {
                            Record next = result.next();
                            String name = next.get("ff").toString().replace("\"", "");//药名
                            String type = next.get("hh").toString().replace("\"", "");//忌用(慎用)
                            medicationUseMap.put(name, type);
                        }
                        //大对象集合
                        ArrayList<Drugs> drugs = new ArrayList<Drugs>();
                        for (Map.Entry<String, LinkedHashMap<String, String>> w : mapSortValueDa.entrySet()) {
                            int i = 0;
                            Drugs drugs1 = new Drugs();
                            //                                drugs1.setDrugsName(w.getKey().trim());//药类
                            LinkedList<Medicition> medicitions = new LinkedList<>();
                            LinkedHashMap<String, String> value2 = w.getValue();
                            for (Map.Entry<String, String> d : value2.entrySet()) {
                                Medicition medicition = new Medicition();
                                medicition.setMedicitionName(d.getKey().trim());//药名
                                medicition.setRate(nf.format(Double.parseDouble(d.getValue().trim())));//使用率
                                i++;
                                if (i < 2) {
                                    medicition.setIsShow(1);//展示
                                } else {
                                    medicition.setIsShow(0);//不展示
                                }
                                if ("忌用".equals(medicationUseMap.get(d.getKey().trim()))) {
                                    medicition.setForbidden(2);
                                } else if ("慎用".equals(medicationUseMap.get(d.getKey().trim()))) {
                                    medicition.setForbidden(1);
                                } else {
                                    medicition.setForbidden(0);
                                }
                                medicitions.add(medicition);
                            }
                            drugs1.setMedicitionsList(medicitions);
                            drugs.add(drugs1);
                        }
                        Filnlly filnlly = new Filnlly();
                        filnlly.setTreatment(drugs);
                        String s = JSON.toJSONString(filnlly);
                        resultMap.put(diseaseName, s);
                    }
                    return 1;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            CloseSession(session);
            return resultMap;
        }
    }

    /**
     * 获取每个慢病对应的不良反应
     *
     * @param
     * @param diseaseType
     * @return
     */
    public Map<String, List<String>> getDisUE(String disName, Integer diseaseType) {
        Session session = null;
        Map<String, List<String>> disUE = new HashMap<>();
        List<String> webDiagList = new ArrayList<>();
        String[] webDiagArray = disName.split(",");
        if (diseaseType != null && 1 == diseaseType) {
            for (String dis : webDiagArray) {
                if (!"".equals(dis)) {
                    webDiagList.add("\"" + dis + "\"");
                }
            }
        }
        session = driver.session(AccessMode.WRITE);
        session.writeTransaction(new TransactionWork<Integer>() {
            @Override
            public Integer execute(Transaction tx) {
                StatementResult result = null;
                String query = "";
                query = "match(d:Disease)-[r:不良反应]->(u:UntowardEffect) where d.name in " + webDiagList + " \n" +
                        "return d.name as dis,collect(u.name) as ueCollect";
                logger.info("根据页面诊断查询每个诊断所对应的不良反应集合,查询语句为:\n"+query);
                result = tx.run(query);
                while (result.hasNext()) {
                    Record next = result.next();
                    String dis = next.get("dis").toString().replace("\"", "");
                    List<Object> stringList = next.get("ueCollect").asList();
                    List<String> ueList = new ArrayList<>();
                    for (Object o : stringList) {
                        ueList.add(o.toString().replace("\"", ""));
                    }
                    disUE.put(dis, ueList);
                }
                return 1;
            }
        });
        CloseSession(session);
        return disUE;
    }

    /**
     * 第二版治疗方案
     *
     * @param disease
     * @param filds   //     * @param sign 标志,2是平常诊断的治疗,0是复诊诊断的治疗,1是急诊
     * @return
     */
    public Map<String, Filnlly> getMulDiseaseTreat_2(String disName,String disease, Integer diseaseType, Set<String> disSet, Map<String, List<String>> disUE, Set<String> ueSet, String filds) {
        Map<String, Filnlly> diagTreat = new HashMap<>();
        Session session = null;
        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMinimumFractionDigits(0);//设置该百分比数字，保留2位小数;
        nf.setRoundingMode(RoundingMode.HALF_UP); //设置满5向上进位，即四舍五入;
        Map<String, String> resultMap = new HashMap<>();
        String[] diseaseArray = disease.split(",|，|、|;|:|；");
        List<String> diseaseList = new ArrayList<>();//诊断数组
        for (int i = 0; i < diseaseArray.length; i++) {
            diseaseList.add(diseaseArray[i]);
        }
        Map<String, ArrayList> diseFilds = new HashMap<>();
//        for (int i = 0; i < diseaseList.size(); i++) {
            String[] fildsArray = filds.split(",");
            ArrayList<String> fildsList = new ArrayList<>();//其他条件数组
            for (String fild : fildsArray) {
                fildsList.add("\'" + fild + "\'");
            }
            if(disSet != null && disSet.size()>0){
                for (String yizhen : disSet) {
                    fildsList.add("\'" + yizhen + "\'");
                }
            }

            for (String h : ueSet) {
                fildsList.add("\'" + h + "\'");
            }
           /* for (int j = 0; j < diseaseList.size(); j++) {
                if (i != j) {
                    fildsList.add("\'" + diseaseList.get(j) + "\'");
                }
            }*/

            diseFilds.put(disName, fildsList);
//        }
        try {
            session = driver.session(AccessMode.WRITE);
            Integer integer = session.writeTransaction(new TransactionWork<Integer>() {
                @Override
                public Integer execute(Transaction tx) {
                    StatementResult result = null;
                    String query = "";
                    for (Map.Entry<String, ArrayList> df : diseFilds.entrySet()) {
                        String diseaseName = df.getKey();//疾病
                        ArrayList value = df.getValue();//其他条件
                        query = propertiesUtil.getProperty("searchDrugsMedic").replace("diseaseName","\'"+diseaseName+"\'");
                        logger.info("查找诊断对应的类和药物,包括类和药的排序,查找语句为:\n"+query);
                        result = tx.run(query);
                        Map<String, LinkedHashMap<String, String>> contentMap = new LinkedHashMap<>();
                        while (result.hasNext()) {
                            Record record = result.next();
                            List<Value> values = record.values();
                            String drugs = values.get(0).toString().replace("\"", "");
                            if (contentMap.containsKey(drugs)) {
                                LinkedHashMap<String, String> stringStringHashMap = contentMap.get(drugs);
                                stringStringHashMap.put(values.get(2).toString().replace("\"", ""), values.get(3).toString());
                                contentMap.put(drugs, stringStringHashMap);
                            } else {
                                LinkedHashMap<String, String> sa = new LinkedHashMap<>();
                                sa.put(values.get(2).toString().replace("\"", ""), values.get(3).toString());
                                contentMap.put(drugs, sa);
                            }
                        }
                        //药类型的大小类拼接
                        Map<String, String> shortLargeMap = new HashMap<>();
                       query =  propertiesUtil.getProperty("searchBigSubDrugs").replace("diseaseName","\'"+diseaseName+"\'");
                        logger.info("查找诊断对应的大小类,进行拼接,查找语句为:\n"+query);
                        result = tx.run(query);
                        while (result.hasNext()) {
                            Record record = result.next();
                            String aShort = record.get("short").toString().replace("\"", "");
                            String large = record.get("large").toString().replace("\"", "");
                            shortLargeMap.put(aShort, large + "(" + aShort + ")");
                        }
                        Map<String, LinkedHashMap<String, String>> shortLargeMapConcat = new LinkedHashMap<>();
                        for (Map.Entry<String, LinkedHashMap<String, String>> f : contentMap.entrySet()
                                ) {
                            String key = f.getKey();
                            if (shortLargeMap.get(key) != null) {
                                shortLargeMapConcat.put(shortLargeMap.get(key), contentMap.get(key));
                            } else {
                                shortLargeMapConcat.put(key, contentMap.get(key));
                            }
                        }
                        Map<String, String> medicationUseMap = new HashMap<>();//key:药名 value:禁忌(慎用)
                        StringBuffer fildBuffer = new StringBuffer();
                        fildBuffer.append("match (n:Disease{name:'" + diseaseName + "'})-[:推荐]->(d:Medicine)<-[r0:慎用]-(m)").append("\n");
                        fildBuffer.append("where m.name in " + value + "").append("\n");
                        fildBuffer.append("return d.name as ff,type(r0) as hh").append("\n").append("union\n");
                        fildBuffer.append("match (n:Disease{name:'" + diseaseName + "'})-[:推荐]->(d:Medicine)<-[r0:忌用]-(m)\n");
                        fildBuffer.append("where m.name in " + value + "").append("\n");
                        fildBuffer.append("return d.name as ff,type(r0) as hh");
                        query = fildBuffer.toString();
                        result = tx.run(query);
                        while (result.hasNext()) {
                            Record next = result.next();
                            String name = next.get("ff").toString().replace("\"", "");//药名
                            String type = next.get("hh").toString().replace("\"", "");//忌用(慎用)
                            medicationUseMap.put(name, type);
                        }
                        /**
                         * 查找药类的忌用
                         */
                        Map<String, String> drugsUseMap = new HashMap<>();//key:药名 value:禁忌(慎用)
                        query = "match (n:Disease{name:'" + diseaseName + "'})-[:推荐]->(d:Drugs)<-[r0:慎用]-(m)\n" +
                                "where m.name in " + value + "" +
                                "return d.name as ff,type(r0) as hh\n" +
                                "union\n" +
                                "match (n:Disease{name:'" + diseaseName + "'})-[:推荐]->(d:Drugs)<-[r0:忌用]-(m)\n" +
                                "where m.name in " + value + "" +
                                "return d.name as ff,type(r0) as hh";
                        result = tx.run(query);
                        while (result.hasNext()) {
                            Record next = result.next();
                            String name = next.get("ff").toString().replace("\"", "");//类名
                            String type = next.get("hh").toString().replace("\"", "");//忌用(慎用)
                            drugsUseMap.put(name, type);
                        }
                        //大对象集合
                        ArrayList<Drugs> drugsList = new ArrayList<Drugs>();
                        DrugsPattern drugsPattern = new DrugsPattern();
                        for (Map.Entry<String, LinkedHashMap<String, String>> w : shortLargeMapConcat.entrySet()) {
                            int i = 0;
                            Drugs drugs = new Drugs();
                            String drugsName = w.getKey();//药类
                            //                            Map<String, String> bigSubDrugs = new DrugsPattern().bigSubDrugs(drugsName);
                            Map<String, String> bigSubDrugs = drugsPattern.bigSubDrugs(drugsName);
                            drugs.setBigdrugsName(bigSubDrugs.get("big"));
                            drugs.setSubdrugsName("");
                            // 如果大类和小类相等，则不推小类
                            if (!bigSubDrugs.get("sub").equals(drugs.getBigdrugsName())) {
                                drugs.setSubdrugsName(bigSubDrugs.get("sub"));
                            }
                            LinkedList<Medicition> medicitionsList = new LinkedList<>();
                            LinkedHashMap<String, String> meditionRate = w.getValue();
                            if ("忌用".equals(drugsUseMap.get(bigSubDrugs.get("big"))) || "忌用".equals(drugsUseMap.get(bigSubDrugs.get("sub")))) {
                                drugs.setDrugsForbidden(2);
                                for (Map.Entry<String, String> g : meditionRate.entrySet()
                                        ) {
                                    Medicition medicition = new Medicition();
                                    String meditionName = g.getKey().trim();//药名
                                    String rate = nf.format(Double.parseDouble(g.getValue().trim()));//百分比
                                    medicition.setMedicitionName(meditionName);
                                    medicition.setRate(rate);
                                    if (i < 3) {
                                        medicition.setIsShow(1);
                                        i++;
                                    } else {
                                        medicition.setIsShow(0);
                                    }
                                    medicition.setForbidden(2);
                                    medicitionsList.add(medicition);
                                }
                            } else if ("慎用".equals(drugsUseMap.get(bigSubDrugs.get("big"))) || "慎用".equals(drugsUseMap.get(bigSubDrugs.get("sub")))) {
                                drugs.setDrugsForbidden(1);
                                for (Map.Entry<String, String> g : meditionRate.entrySet()
                                        ) {
                                    Medicition medicition = new Medicition();
                                    String meditionName = g.getKey().trim();//药名
                                    String rate = nf.format(Double.parseDouble(g.getValue().trim()));//百分比
                                    medicition.setMedicitionName(meditionName);
                                    medicition.setRate(rate);
                                    if (i < 3) {
                                        medicition.setIsShow(1);
                                        i++;
                                    } else {
                                        medicition.setIsShow(0);
                                    }
                                    medicition.setForbidden(1);
                                    medicitionsList.add(medicition);
                                }
                            } else {
                                drugs.setDrugsForbidden(0);
                                for (Map.Entry<String, String> g : meditionRate.entrySet()
                                        ) {
                                    Medicition medicition = new Medicition();
                                    String meditionName = g.getKey().trim();//药名
                                    String rate = nf.format(Double.parseDouble(g.getValue().trim()));//百分比
                                    medicition.setMedicitionName(meditionName);
                                    medicition.setRate(rate);
                                    if (i < 3) {
                                        medicition.setIsShow(1);
                                        i++;
                                    } else {
                                        medicition.setIsShow(0);
                                    }
                                    if ("忌用".equals(medicationUseMap.get(meditionName))) {
                                        medicition.setForbidden(2);
                                    } else if ("慎用".equals(medicationUseMap.get(meditionName))) {
                                        medicition.setForbidden(1);
                                    } else {
                                        medicition.setForbidden(0);
                                    }
                                    medicitionsList.add(medicition);
                                }
                            }
                            drugs.setMedicitionsList(medicitionsList);
                            drugsList.add(drugs);
                        }
                        Filnlly filnlly = new Filnlly();
                        //显示不良反应
                        if (diseaseType != null && 1 == diseaseType) {
                            List<String> stringList = disUE.get(diseaseName);
                            logger.info(diseaseName + "下面有" + stringList + "不良反应");
                            if (stringList != null && stringList.size() > 0) {
                                List<Indicators> indicatorsList1 = new ArrayList<>();
                                for (String de : stringList) {
                                    Indicators indicators1 = getAdverse(ueSet, de);
                                    logger.info(disSet + "包含  " + de);
                                    indicatorsList1.add(indicators1);
                                }
                                filnlly.setAdverseEvent(indicatorsList1);
//                                Indicators indicators1 = getAdverse(ueSet, "低血糖反应");
//                                logger.info(disSet + "包含  低血糖反应");
//                                Indicators indicators2 = getAdverse(ueSet, "胃肠道不良反应");
//                                logger.info(disSet + "包含  胃肠道不良反应");
//                                indicatorsList1.add(indicators1);
//                                indicatorsList1.add(indicators2);
//                                filnlly.setAdverseEvent(indicatorsList1);
                            }
                        }
                        filnlly.setTreatment(drugsList);
                        diagTreat.put(diseaseName, filnlly);
                    }
                    return 1;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            CloseSession(session);
            //            driver.close();
            return diagTreat;
        }
    }

    /**
     * 推送指标
     *
     * @param idnSet 指标集
     * @param age    年龄
     * @param sex    性别
     * @return
     */
    public List<MedicalIndication> getIdn(Set<String> idnSet, Integer age, String sex) {
        String query = "";
        Session session = null;
        StatementResult result = null;
        List<MedicalIndication> medicalIndicationList = new ArrayList<>();
        if (idnSet != null && idnSet.size() > 0) {
            for (String s : idnSet) {
                MedicalIndication medicalIndication = new MedicalIndication();
                List<MedicalIndicationDetail> medicalIndicationDetailList = new ArrayList<>();
                medicalIndication.setName(s);
                MedicalIndicationDetail medicalIndicationDetail1 = null;
                MedicalIndicationDetail medicalIndicationDetail2 = null;
                MedicalIndicationDetail medicalIndicationDetail3 = null;
                JSONObject gongshiJson = null;
                List<JSONObject> detailList = null;
                List<JSONObject> resultList = null;
                List<JSONObject> sexList = null;
                List<JSONObject> shiFouList = null;
                JSONObject shiFouJson = null;
                Set<String> results = new LinkedHashSet<>();
                query = "match(d:Indicators{name:'" + s + "'})-[r2:内容]->(n:Content) where r2.p=1 \n" +
                        "return r2.p as sort1 ,n.name as conten,null as sort2,null as item,null as controlType,null as state,null as value,null as uint,null as details\n" +
                        "union\n" +
                        "match(d:Indicators{name:'" + s + "'})-[r2:内容]->(n:Content)-[r3:项目]->(i:Item) \n" +
                        "return r2.p as sort1 ,n.name as conten,r3.p as sort2,i.name as item,i.controlType as controlType,i.state as state,i.value as value,i.uint as uint,i.details as details order by sort1,sort2";
                session = driver.session(AccessMode.WRITE);
                result = session.run(query);
                while (result.hasNext()) {
                    Record next1 = result.next();
                    int sort1 = next1.get("sort1").asInt();
                    String conten = next1.get("conten").toString();
                    String sort2 = next1.get("sort2").toString();
                    String item = next1.get("item").toString();
                    String controlType = next1.get("controlType").toString();
                    String state1 = next1.get("state").toString();
                    String value = next1.get("value").toString();
                    String uint = next1.get("uint").toString();
                    String details = next1.get("details").toString();
                    //                    System.out.println(sort1+"\t"+conten+"\t"+sort2+"\t"+item+"\t"+controlType+"\t"+value+"\t"+uint+"\t"+details);
                    if (1 == sort1) {
                        if (medicalIndicationDetail1 == null) {
                            medicalIndicationDetail1 = new MedicalIndicationDetail();
                        }
                        medicalIndicationDetail1.setType(sort1);
                        JSONObject liangJson = new JSONObject();
                        liangJson.put("name", conten.replace("\"", ""));
                        medicalIndicationDetail1.setContent(liangJson);
                    } else if (2 == sort1) {
                        if (medicalIndicationDetail2 == null) {
                            medicalIndicationDetail2 = new MedicalIndicationDetail();
                        }
                        medicalIndicationDetail2.setType(2);
                        if (gongshiJson == null) {
                            gongshiJson = new JSONObject();
                        }
                        gongshiJson.put("name", conten.replace("\"", ""));
                        if (detailList == null) {
                            detailList = new ArrayList<>();
                        }
                        JSONObject ageJsonObject = new JSONObject();
                        ageJsonObject.put("controlType", Integer.parseInt(controlType));
                        ageJsonObject.put("name", item.replace("\"", ""));
                        ageJsonObject.put("value", value.replace("\"", ""));
                        ageJsonObject.put("uint", uint.replace("\"", ""));
                        if ("年龄".equals(item.replace("\"", ""))) {
                            ageJsonObject.put("value", age);
                            ageJsonObject.put("isShow",0);
                        }else if("性别".equals(item.replace("\"", ""))){
                            ageJsonObject.put("isShow",0);
                        }else {
                            ageJsonObject.put("isShow",1);
                        }
                        if (!"0".equals(controlType)) {
                            ageJsonObject.put("details", details.replace("\"", ""));
                        } else {
                            String query1 = "match(i:Item)-[r:详细]->(d:Detail) where i.name=" + item + "\n" +
                                    "return d.name as name,d.state as state,d.value as value order by r.p";
                            StatementResult run1 = session.run(query1);
                            if (sexList == null) {
                                sexList = new ArrayList<>();
                            }
                            while (run1.hasNext()) {
                                Record next = run1.next();
                                String name = next.get("name").toString();
                                int state = next.get("state").asInt();
                                String value1 = next.get("value").toString();
                                JSONObject manJson = new JSONObject();
                                manJson.put("detailName", name.replace("\"", ""));
                                manJson.put("value", value1.replace("\"", ""));
                                manJson.put("state", state);
                                if ("男".equals(name.replace("\"", "")) && "1".equals(sex)) {
                                    manJson.put("state", 1);
                                } else if ("女".equals(name.replace("\"", "")) && "2".equals(sex)) {
                                    manJson.put("state", 1);
                                }
                                sexList.add(manJson);
                            }
                            ageJsonObject.put("details", sexList);
                        }
                        detailList.add(ageJsonObject);
                        gongshiJson.put("details", detailList);
                        if (resultList == null) {
                            resultList = new ArrayList<>();
                        }
                        String query2 = "match(c:Content)-[r:结果]->(f:Result) where c.name=" + conten + "\n" +
                                "return f.name as name,f.text as text order by r.p";
                        StatementResult run1 = session.run(query2);
                        while (run1.hasNext()) {
                            Record next = run1.next();
                            String name = next.get("name").toString();
                            results.add(name.replace("\"", ""));
                        }
                    } else if (3 == sort1) {
                        if (medicalIndicationDetail3 == null) {
                            medicalIndicationDetail3 = new MedicalIndicationDetail();
                        }
                        medicalIndicationDetail3.setType(3);
                        if (shiFouList == null) {
                            shiFouList = new ArrayList<>();
                        }
                        if (shiFouJson == null) {
                            shiFouJson = new JSONObject();
                        }
                        shiFouJson.put("name", conten.replace("\"", ""));
                        shiFouJson.put("controlType", 0);
                        JSONObject shiJsonObject = new JSONObject();
                        shiJsonObject.put("detailName", item.replace("\"", ""));
                        shiJsonObject.put("state", Integer.parseInt(state1));
                        shiFouList.add(shiJsonObject);
                        shiFouJson.put("details", shiFouList);
                        medicalIndicationDetail3.setContent(shiFouJson);
                    }
                }
                for (String re : results) {
                    JSONObject result1 = new JSONObject();
                    result1.put("name", re);
                    result1.put("text", "");
                    resultList.add(result1);
                }
                gongshiJson.put("result", resultList);
                medicalIndicationDetail2.setContent(gongshiJson);
                medicalIndicationDetailList.add(medicalIndicationDetail1);
                medicalIndicationDetailList.add(medicalIndicationDetail2);
                medicalIndicationDetailList.add(medicalIndicationDetail3);
                medicalIndication.setDetails(medicalIndicationDetailList);
                medicalIndicationList.add(medicalIndication);
            }
        } else {
            medicalIndicationList = null;
        }
        CloseSession(session);
        return medicalIndicationList;
    }
   public Map<String,String> getIndLiang(Set<String> inds){
       Map<String,String> kk = new HashMap<>();
       String query = "";
       Session session = null;
       StatementResult result = null;
       for (String ind:inds){
           query = "match(i:Indicators)-[r:内容]->(c:Content) where i.name=\""+ind+"\" return c.name as name";
           session = driver.session(AccessMode.WRITE);
           result = session.run(query);
           while (result.hasNext()) {
               Record next1 = result.next();
               String name = next1.get("name").toString();
               kk.put(ind,name.replace("\"",""));
           }
       }
       CloseSession(session);
       return kk;
   }
    public MangementEvaluation pushMe(String[] webDiagsplits, Map<String, Double> lis_Result) {
        MangementEvaluation mangementEvaluation = new MangementEvaluation();
        Map<String, JSONObject> mangementMap = new HashMap<>();
        String query = "";
        Session session = null;
        StatementResult result = null;
        if (webDiagsplits != null && webDiagsplits.length > 0) {
            String diag = webDiagsplits[0];//慢病
//            if ("糖尿病".equals(diag)) {
                Map<String, LinkedList<String>> effCollect = new LinkedHashMap<>();
                query = "match(d:Disease)-[r1:管理评估]-(m:Management)-[r2:疗效评估]->(e:Effect)-[r3:结果]-(u:Result)\n" +
                        "where d.name='" + diag + "'\n" +
                        "return d.name as dis,e.name as eff,u.name as res order by r2.p,r3.p";
                logger.info(query);
                session = driver.session(AccessMode.WRITE);
                result = session.run(query);
                while (result.hasNext()) {
                    Record next = result.next();
                    String eff = next.get("eff").toString().replace("\"", "");//血压控制情况
                    String res = next.get("res").toString().replace("\"", "");//正常
                    //                    System.out.println(eff + "\t" + res);
                    if (effCollect.keySet().contains(eff)) {
                        if (!effCollect.get(eff).contains(res)) {
                            LinkedList<String> strings = effCollect.get(eff);
                            strings.add(res);
                            effCollect.put(eff, strings);
                        }
                    } else {
                        LinkedList<String> strings = new LinkedList<>();
                        strings.add(res);
                        effCollect.put(eff, strings);
                    }
                }
                //effCollect 存的:(血脂控制情况 : 正常,轻度,中度,重度)
                List<JSONObject> itemJson = new ArrayList<>();
                JSONObject curativeJson = new JSONObject();
                for (Map.Entry<String, LinkedList<String>> item : effCollect.entrySet()) {
                    String key = item.getKey();//血脂控制情况
                    LinkedList<String> value = item.getValue();//正常,轻度,中度,重度
                    JSONObject bloodPressure = new JSONObject();
                    bloodPressure.put("controltype", 0);
                    bloodPressure.put("name", key);
                    List<JSONObject> bloodPressureLevelList = new ArrayList<>();
                    for (String res : value) {
                        JSONObject iJson = new JSONObject();
                        iJson.put("detailName", res);
                        iJson.put("state", 0);
                        bloodPressureLevelList.add(iJson);
                    }
                    bloodPressure.put("details", bloodPressureLevelList);

                    if (bloodPressure.get("name").equals("血脂控制情况")) {
                        List<JSONObject> details = (List<JSONObject>) bloodPressure.get("details");
                        Map<String, String> idnRes = new HashMap<>();
                        //化验计算
                        String query1 = "match(e:Effect)-[r:指标]->(l:LIS)-[r1:计算结果]->(k:Result) where e.name='血脂控制情况'\n" +
                                "return l.name as name,r1.between as between ,k.name as res";
                        logger.info(query1);
                        StatementResult result1 = session.run(query1);
                        while (result1.hasNext()) {
                            Record next = result1.next();
                            String name = next.get("name").toString().replace("\"", "");
                            String between = next.get("between").toString().replace("\"", "");
                            String[] betweenSplit = between.split(",");
                            double min = Double.parseDouble(betweenSplit[0].replace("[", ""));
                            double max = Double.parseDouble(betweenSplit[1].replace("]", ""));
                            String res1 = next.get("res").toString().replace("\"", "");
                            if (lis_Result.keySet().contains(name)) {
                                Double aDouble = lis_Result.get(name);
                                if (min < aDouble && aDouble <= max) {
                                    idnRes.put(res1, "血脂控制情况");
                                } else {
                                    idnRes.put("", "血脂控制情况");
                                }
                            }
                        }
                        Collection<String> values = idnRes.keySet();
                        List<String> newValues = new ArrayList<>();
                        if (values.contains("重度")) {
                            newValues.clear();
                            newValues.add("重度");
                        } else if (!values.contains("重度") && values.contains("中度")) {
                            newValues.clear();
                            newValues.add("中度");
                        } else if (!values.contains("重度") && !values.contains("中度") && values.contains("轻度")) {
                            newValues.clear();
                            newValues.add("轻度");
                        } else if (!values.contains("重度") && !values.contains("中度") && !values.contains("轻度") && values.contains("正常")) {
                            newValues.clear();
                            newValues.add("正常");
                        } else {
                            newValues.clear();
                            newValues.add("");
                        }
                        for (String s : newValues) {
                            int i = 0;
                            if (!"".equals(s)) {
                                for (i = 0; i < details.size(); i++) {
                                    String detailName = (String) details.get(i).get("detailName");
                                    if (detailName.equals(s)) {
                                        details.remove(i);
                                        break;
                                    }
                                }
                                JSONObject k = new JSONObject();
                                k.put("detailName", s);
                                k.put("state", 1);
                                //                                details.add(k);
                                details.add(i, k);

                            }
                        }
                        bloodPressure.put("details", details);
                    }
                    itemJson.add(bloodPressure);
                }
                curativeJson.put("rows", itemJson);
                //分级管理
                JSONObject gradeJson = new JSONObject();
                List<JSONObject> gradItemJson = new ArrayList<>();
                JSONObject bigGrad = new JSONObject();
                bigGrad.put("name", "糖尿病控制情况");
                bigGrad.put("controltype", 0);
                List<JSONObject> gradItemJ = new ArrayList<>();
                String[] gradItem = {"常规管理", "强化管理"};
                for (String item : gradItem) {
                    JSONObject j = new JSONObject();
                    j.put("detailName", item);
                    j.put("state", 0);
                    gradItemJ.add(j);
                }
                bigGrad.put("details", gradItemJ);
                gradItemJson.add(bigGrad);
                gradeJson.put("rows", gradItemJson);
                mangementMap.put("疗效评估", curativeJson);
                mangementMap.put("糖尿病分级管理", gradeJson);
                mangementEvaluation.setMangementEvaluation(mangementMap);
//            }
        }
        CloseSession(session);
        return mangementEvaluation;

    }

    public Indicators getAdverse(Set<String> dis, String name) {
        List<Detail> detailList1 = new ArrayList<>();
        Indicators indicators1 = new Indicators();
        indicators1.setName(name);
        indicators1.setControlType(2);
        Detail detail1 = new Detail();
        detail1.setName("否");
        detail1.setValue(0);
        Detail detail2 = new Detail();
        detail2.setName("是");
        detail2.setValue(0);
        if (dis.contains(name)) {
            detail2.setValue(1);
        }
        logger.info("有" + name + " 标记为是!!!!");
        Detail detail3 = new Detail();
        detail3.setName("轻度");
        detail3.setValue(0);
        Detail detail4 = new Detail();
        detail4.setName("中度");
        detail4.setValue(0);
        Detail detail5 = new Detail();
        detail5.setName("重度");
        detail5.setValue(0);
        Detail detail6 = new Detail();
        detail6.setName("偶尔");
        detail6.setValue(0);
        Detail detail7 = new Detail();
        detail7.setName("频繁");
        detail7.setValue(0);
        detailList1.add(detail1);
        detailList1.add(detail2);
        detailList1.add(detail3);
        detailList1.add(detail4);
        detailList1.add(detail5);
        detailList1.add(detail6);
        detailList1.add(detail7);
        indicators1.setDetails(detailList1);
        return indicators1;
    }


    /**
     * 反推LIS,PACS
     *
     * @param diseases
     * @return
     */
    public Map<String, Set<String>> getLisPacs(List<String> diseases) {
        Session session = null;
        StatementResult result = null;
        String serchLisPacs = propertiesUtil.getProperty("serchLisPacs");
        String query = null;
        Map<String, Set<FeatureRate>> lisPacsMap = new HashMap<>();
        Map<String, Set<String>> lisPacsMap1 = new HashMap<>();
        List<String> diseaseList = new ArrayList<>();//诊断数组
        for (String dis : diseases) {
            diseaseList.add("\"" + dis + "\"");
        }
        try {
            session = driver.session(AccessMode.WRITE);
            List<FeatureRate> lisList = new ArrayList<>();
            List<FeatureRate> pacsList = new ArrayList<>();
            List<String> lisArray = new ArrayList<>();
            List<String> pacsArray = new ArrayList<>();
            query = serchLisPacs.replace("diseaseNmae", diseaseList.toString());
            result = session.run(query);
            while (result.hasNext()) {
                Record next = result.next();
                String lei = next.get("lei").toString().replaceAll("\"", "");
                String name = next.get("n").toString().replaceAll("\"", "");
                if ("LIS".equals(lei)) {
                    lisArray.add(name);
                } else if ("PACS".equals(lei)) {
                    pacsArray.add(name);
                }
            }
            lisPacsMap1.put("LIS", processList(lisArray));
            lisPacsMap1.put("PACS", processList(pacsArray));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            CloseSession(session);
            return lisPacsMap1;
        }
    }

    public Set<String> processList(List<String> list) {
        Set<String> resultSet = new LinkedHashSet<>();
        Map<String, Integer> featuerInt = new HashMap<String, Integer>();
        for (String d : list) {
            if (featuerInt.containsKey(d)) {
                featuerInt.put(d, featuerInt.get(d) + 1);
            } else {
                featuerInt.put(d, 1);
            }
        }
        List<Map.Entry<String, Integer>> reslist = new ArrayList<Map.Entry<String, Integer>>(featuerInt.entrySet());
        Collections.sort(reslist, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });
        for (Map.Entry<String, Integer> f : reslist
                ) {
            //排好序的set
            resultSet.add(f.getKey());
        }
        return resultSet;
    }

    /**
     * 化验结果文本化
     *
     * @param lisres
     * @return
     */
    public ArrayList<String> AnalysisLISResult(JSONArray lisres) {
        Session session = null;
        ArrayList<String> reslist = new ArrayList<>();
        JSONObject jobj = null;
        String jsonstr = "";
        String idx = "";

        String regnum = "^([0-9]+[.])*[0-9]+$";
        Pattern patnum = Pattern.compile(regnum);
        Matcher num_mat;

        String query = "with [";
        try {
            session = driver.session(AccessMode.READ);

            if (lisres != null || !lisres.isEmpty()) {
                for (int i = 0; i < lisres.size(); i++) {

                    jobj = lisres.getJSONObject(i);
                    jsonstr = "{";

                    for (String key : jobj.keySet()) {
                        jsonstr += key + ":";

                        String val = jobj.getString(key);

                        num_mat = patnum.matcher(val);
                        if (num_mat.find(0)) {
                            jsonstr += val + ", ";
                        } else {
                            jsonstr += "'" + val + "', ";
                        }
                    }
                    jsonstr = jsonstr.substring(0, jsonstr.length() - 2);

                    query += jsonstr + "},";
                }

                query = query.substring(0, query.length() - 1);

                query += "]\n" +
                        "as result_info\n" +
                        "unwind result_info as row\n" +
                        "match (n:LIS)-[:结果]->(m:LIS_Result)\n" +
                        "where n.name=row.uniqueName\n" +
                        "with m,\n" +
                        "case\n" +
                        "when m.判断1 is null or m.判断1 = '' then '未定义'\n" +
                        "when m.判断1 = \"位于\" then row.otherValue in m.判断系数1\n" +
                        "when m.判断1= \"升高\" and row.maxValue<>\"\" then row.value > row.maxValue\n" +
                        "when m.判断1= \"大于倍数\" and row.maxValue<>\"\" then (row.value/row.maxValue) > m.判断系数1\n" +
                        "when m.判断1= \"大于等于倍数\" and row.maxValue<>\"\" then (row.value/row.maxValue) >= m.判断系数1\n" +
                        "when m.判断1= \"小于倍数\" and row.maxValue<>\"\" then (row.value/row.maxValue) < m.判断系数1\n" +
                        "when m.判断1= \"小于等于倍数\" and row.maxValue<>\"\" then (row.value/row.maxValue) <= m.判断系数1\n" +
                        "when m.判断1= \"降低\" and row.minValue<>\"\" then row.value < row.minValue\n" +
                        "when m.判断1= \"大于\" and m.单位=row.units then row.value > m.判断系数1\n" +
                        "when m.判断1= \"大于等于\" and m.单位=row.units then row.value >= m.判断系数1\n" +
                        "when m.判断1= \"小于\" and m.单位=row.units then row.value < m.判断系数1\n" +
                        "when m.判断1= \"小于等于\" and m.单位=row.units then row.value <= m.判断系数1\n" +
                        //                        "when m.单位<>row.unit and m.单位 is not null then '单位不同'\n" +
                        "else 'Unknown'\n" +
                        "end as judgement1,\n" +
                        "case\n" +
                        "when m.判断2 is null or m.判断2 = '' then '未定义'\n" +
                        "when m.判断2 = \"位于\" then row.otherValue in m.判断系数2\n" +
                        "when m.判断2 = \"升高\" and row.maxValue<>\"\" then row.value > row.maxValue\n" +
                        "when m.判断2 = \"降低\" and row.minValue<>\"\" then row.value < row.minValue\n" +
                        "when m.判断2 = \"大于倍数\" and row.maxValue<>\"\" then (row.value/row.maxValue) > m.判断系数2\n" +
                        "when m.判断2 = \"大于等于倍数\" and row.maxValue<>\"\" then (row.value/row.maxValue) >= m.判断系数2\n" +
                        "when m.判断2 = \"小于倍数\" and row.maxValue<>\"\" then (row.value/row.maxValue) < m.判断系数2\n" +
                        "when m.判断2 = \"小于等于倍数\" and row.maxValue<>\"\" then (row.value/row.maxValue) <= m.判断系数2\n" +
                        "when m.判断2 = \"大于\" and m.单位=row.units then row.value > m.判断系数2\n" +
                        "when m.判断2 = \"大于等于\" and m.单位=row.units then row.value >= m.判断系数2\n" +
                        "when m.判断2 = \"小于\" and m.单位=row.units then row.value < m.判断系数2\n" +
                        "when m.判断2 = \"小于等于\" and m.单位=row.units then row.value <= m.判断系数2\n" +
                        //                        "when m.单位<>row.unit and m.单位 is not null then '单位不同'\n" +
                        "else 'Unknown'\n" +
                        "end as judgement2\n" +
                        "return m.name as LIS_Result,\n" +
                        "case \n" +
                        "when judgement1 = True and judgement2 = True then True\n" +
                        "when judgement1 = True and judgement2 = '未定义' then True\n" +
                        "when judgement2 = True and judgement1 = '未定义' then True\n" +
                        //                        "when judgement2 = '单位不同' or judgement1 = '单位不同' then 'Unknown'\n" +
                        //                        "when judgement2 = '未定义' and judgement1 = '未定义' then 'Unknown'\n" +
                        //                        "when judgement2 is null or judgement1 is null then 'Unknown'\n" +
                        //                        "when judgement2 = false or judgement1 = false then false\n" +
                        "else False end as judgement order by LIS_Result";

                //                System.out.println(query);

                StatementResult run = session.run(query);
                while (run.hasNext()) {
                    Record next = run.next();
                    idx = "";
                    for (String k : next.keys()) {
                        if (next.get(k).getClass().toString().indexOf("Boolean") == -1) {
                            idx = next.get(k).toString().replaceAll("\"", "");
                        }
                        if (next.get(k).isTrue()) {
                            reslist.add(idx);
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            CloseSession(session);
            return reslist;
        }
    }

    public static LinkedHashMap<String, String> mapSortByValue(HashMap<String, String> source) {
        LinkedList<Map.Entry<String, String>> entries = new LinkedList<>(source.entrySet());
        Collections.sort(entries, new Comparator<Map.Entry<String, String>>() {
            @Override
            public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });
        LinkedHashMap<String, String> sada = new LinkedHashMap<>();
        for (Iterator it = entries.iterator(); it.hasNext(); ) {
            Map.Entry<String, String> next = (Map.Entry<String, String>) it.next();
            sada.put(next.getKey(), next.getValue());
        }
        return sada;
    }

    public ArrayList<String> inputProcess(ArrayList<String> fildsList) {
        ArrayList<String> ssd = new ArrayList<>();
        for (String a : fildsList) {
            String start = "";
            String[] splits = a.split(":");
            switch (splits[1]) {
                case "Symptom":
                    start = "{label:" + "\"" + splits[1] + "\"," + "name:" + "\"" + splits[0] + "\"}";
                    ssd.add(start);
                    break;
                case "Vital":
                    start = "{label:" + "\"" + splits[1] + "\"," + "name:" + "\"" + splits[0] + "\"}";
                    ssd.add(start);
                    break;
                case "LIS_Result":
                    start = "{label:" + "\"" + splits[1] + "\"," + "name:" + "\"" + splits[0] + "\"}";
                    ssd.add(start);
                    break;
                case "PACS_Result":
                    start = "{label:" + "\"" + splits[1] + "\"," + "name:" + "\"" + splits[0] + "\"}";
                    ssd.add(start);
                    break;
                case "History":
                    start = "{label:" + "\"" + splits[1] + "\"," + "name:" + "\"" + splits[0] + "\"}";
                    ssd.add(start);
                    break;
                default:
                    break;
            }
        }
        return ssd;
    }

    /**
     * 记录操作日志
     *
     * @param query 查询语句
     * @return
     */
    public void writeLog(String query) {
        FileWriter fw;
        try {
            int DD = calendar.get(Calendar.DATE);
            String stamp = String.valueOf(YY) + "-" +
                    ((String.valueOf(MM).length() == 1) ? "0" : "") + String.valueOf(MM) + "-" +
                    ((String.valueOf(DD).length() == 1) ? "0" : "") + String.valueOf(DD) + ".log";

            fw = new FileWriter(stamp, true);

            String time = format.format(new Date());
            fw.write(time + " " + query + "\r\n");

            fw.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void CloseSession(Session session) {
        if (session != null) {
            session.close();
        }
    }

    public void CloseDriver() {
        if (driver != null) {
            driver.close();
        }
    }

    /**
     * 根据是否需要计算调取相应返回量表的方法
     *
     * @param scaleName
     * @return
     */
    public Map<String, Object> getScale(String[] scaleItems, String scaleName) {
        Session session = driver.session(AccessMode.READ);
        StatementResult Rset;

        Map<String, Object> scale = new LinkedHashMap<>();

        try {
            String query = "match (m:Scale) WHERE m.name='" + scaleName + "' return m.type";
            Rset = session.run(query);
            String type = Rset.next().get("m.type").toString().replace("\"", "");
            if (Integer.valueOf(type) == 1) {
                scale = this.getScaleCalc2(scaleItems, scaleName);
            } else {
                scale = this.getScaleNoCalc(scaleName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("调量表方法时出了问题！");
        } finally {
            CloseSession(session);
            return scale;
        }

    }

    /**
     * 返回带得分需要计算的量表
     *
     * @param scaleName
     * @return
     */
    public Map<String, Object> getScaleCalc(String scaleName) {
        Session session = driver.session(AccessMode.READ);
        StatementResult Rset = null;
        Record rec;
        scaleName = scaleName.toUpperCase();

        Map<String, Object> threeLevelItems = new LinkedHashMap<>();
        //<<=44,0>

        Map<String, Object> result = null;
        Map<String, Object> title = new LinkedHashMap<>();
        List<Map<String, Object>> results = new ArrayList<>();

        List<Object> titles;
        Map<String, Object> calculate = new HashMap<>();

        Map<String, List<Map<String, String>>> nameDetails = new HashMap<>();


        threeLevelItems.put("scaleType", "");

        try {
            String query = "match (m:Scale)-[r1]->(n1)-[r2]->(n2)-[r3]->(n3) WHERE m.name=~'.*" + scaleName + ".*' " +
                    "return n1.name, n1.method, r1.score, n2.name, r2.score,n2.type, r2.p,n3.name as n3name,r3.score as r3score, r3.p as r3p, n3.type as n3type order by toInt(r2.p),n2.type " +
                    "union match (m:Scale)-[r1]->(n1)-[r2]->(n2)  WHERE m.name=~'.*" + scaleName + ".*' return n1.name,n1.method, r1.score,n2.name,r2.score,n2.type,r2.p, null as n3name, null as r3score, null as r3p, null as n3type order by toInt(r2.p),n2.type";

            Rset = session.run(query);

            String name = "";
            String method = "";
            String optionOrIndex = "";
            String pacsResult = "";
            String score1 = "";
            String score2 = "";
            String priority = "";

            while (Rset.hasNext()) {
                rec = Rset.next();
                //临床体格检查
                name = rec.get("n1.name").toString().replace("\"", "");
                method = rec.get("n1.method").toString().replace("\"", "");
                //轻度 右拇指振动觉
                optionOrIndex = rec.get("n2.name").toString().replace("\"", "");
                //正常 异常
                pacsResult = rec.get("n3name").toString().replace("\"", "");
                //range区间
                score1 = rec.get("r2.score").toString().replace("\"", "");
                //正常异常得分
                score2 = rec.get("r3score").toString().replace("\"", "");
                //右拇指振动觉权重
                priority = rec.get("r2.p").toString().replace("\"", "");
                //正常异常权重

                if (name.contains("计算方法")) {
                    String[] score = score1.split("~|-");
                    String min = score[0];
                    String max = score[1];
                    result = new TreeMap<>();
                    result.put("min", min);
                    result.put("max", max);
                    result.put("text", optionOrIndex);
                    result.put("priority", priority);
                    results.add(result);
                }

                titles = new ArrayList<>();
                title.put("name", name);
                title.put("column", "name");
                titles.add(title);
                title = new LinkedHashMap<>();
                title.put("name", "临床症状");
                title.put("column", "detailName");
                titles.add(title);
                title = new LinkedHashMap<>();
                title.put("name", "得分");
                title.put("column", "score");
                titles.add(title);
                threeLevelItems.put("title", titles);

                if ("NULL".equals(method) && !"NULL".equals(pacsResult)) {
                    optionOrIndex = optionOrIndex + "_" + priority;

                    Map<String, String> detailInfo = new LinkedHashMap<>();
                    detailInfo.put("detailName", pacsResult);
                    detailInfo.put("score", score2);
                    detailInfo.put("state", "0");
                    detailInfo.put("priority", priority);

                    if (nameDetails.containsKey(optionOrIndex)) {
                        nameDetails.get(optionOrIndex).add(detailInfo);
                    } else {
                        nameDetails.put(optionOrIndex, new ArrayList<>());
                        nameDetails.get(optionOrIndex).add(detailInfo);
                    }
                }
            }
            Collections.sort(results, new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    Integer priorityo1 = Integer.valueOf(o1.get("priority").toString());
                    Integer priorityo2 = Integer.valueOf(o2.get("priority").toString());
                    return priorityo1.compareTo(priorityo2);
                }
            });
            for (Map<String, Object> resMap : results) {
                resMap.remove("priority");
            }
            calculate.put("range", results);
            calculate.put("formula", "");
            Map<String, String> calcResult = new HashMap<>();
            calcResult.put("score", "");
            calcResult.put("text", "");
            calculate.put("result", calcResult);
            threeLevelItems.put("calculate", calculate);

            List<Map<String, Object>> finalResult = new ArrayList<>();
            for (Map.Entry<String, List<Map<String, String>>> nameDetailEntry : nameDetails.entrySet()) {
                String key = nameDetailEntry.getKey();
                List<Map<String, String>> value = nameDetailEntry.getValue();
                Map<String, Object> detailsResult = new TreeMap<>();

                Collections.sort(value, new Comparator<Map<String, String>>() {
                    @Override
                    public int compare(Map<String, String> o1, Map<String, String> o2) {
                        Integer priorityo1 = Integer.valueOf(o1.get("priority"));
                        Integer priorityo2 = Integer.valueOf(o2.get("priority"));
                        return priorityo1.compareTo(priorityo2);
                    }
                });

                for (Map<String, String> map : value) {
                    map.remove("priority");
                }

                detailsResult.put("name", key.split("_")[0]);
                detailsResult.put("details", value);
                detailsResult.put("controltype", 0);
                detailsResult.put("priority", key.split("_")[1]);
                finalResult.add(detailsResult);
            }
            Collections.sort(finalResult, new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    Integer priorityo1 = Integer.valueOf(o1.get("priority").toString());
                    Integer priorityo2 = Integer.valueOf(o2.get("priority").toString());
                    return priorityo1.compareTo(priorityo2);
                }
            });
            for (Map<String, Object> map : finalResult) {
                map.remove("priority");
            }
            threeLevelItems.put("rows", finalResult);
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("返回带得分需要计算的量表时出了问题！---->getScaleCalc");
        } finally {
            CloseSession(session);
            return threeLevelItems;
        }
    }

    /**
     * 获取量表
     *
     * @param scaleName
     * @return
     */
    public Map<String, Object> getScaleCalc2(String[] scaleItems, String scaleName) {
        Session session = driver.session(AccessMode.READ);
        StatementResult Rset = null;
        Record rec;
//        scaleName = scaleName.toUpperCase();

        Map<String, Object> scaleStructure = new LinkedHashMap<>();
        Map<String, Object> result = null;

        List<Map<String, Object>> results = new ArrayList<>();

        Map<String, Object> calculate = new HashMap<>();

        try {
            String query = "match (m:Scale)-[r1]->(n1)-[r2]->(n2)-[r3]->(n3)-[r4]->(n4) " +
                    "WHERE m.name='" + scaleName + "'" +
                    "return m.name,m.calc,m.type,m.titleName,n1.name,n1.isShow,r2.mutex as r2mutex,n2.name," +
                    "n2.required as n2required,n3.name as n3name,n3.coefficient as n3coefficient," +
                    "n3.constant as n3constant,n3.controlType as n3controlType,n3.indexId as n3indexId, r4.score as r4score," +
                    "n4.name as n4name order by toInt(r1.p),toInt(r2.p),toInt(r3.p) desc,toInt(r4.p) " +
                    "union " +
                    "match (m:Scale)-[r1]->(n1:Method)-[r2]->(n2) WHERE m.name='" + scaleName + "' " +
                    "return m.name,m.calc,m.type,m.titleName,n1.name,n1.isShow,r2.score as r2mutex,n2.name,null as n2required," +
                    "null as n3name,null as n3coefficient,null as n3constant,null as n3controlType,null as n3indexId,null as r4score, " +
                    "null as n4name order by toInt(r2.p)";
            Rset = session.run(query);

            String calc = "";
            String type = "";
            String group = "";
            String isShow = "";
            String text = "";
            String mutex = "";
            String required = "";
            String coefficient = "";
            String constant = "";
            String controlType = "";
            String indexId = "";
            String score = "";
            String option = "";
            String index = "";

            while (Rset.hasNext()) {
                rec = Rset.next();
                scaleName = rec.get("m.name").toString().replace("\"", "");
                calc = rec.get("m.calc").toString().replace("\"", "");
                type = rec.get("m.type").toString().replace("\"", "");
                group = rec.get("n1.name").toString().replace("\"", "");
                isShow = rec.get("n1.isShow").toString().replace("\"", "");
                text = rec.get("n2.name").toString().replace("\"", "");
                mutex = rec.get("r2mutex").toString().replace("\"", "");
                required = rec.get("n2required").toString().replace("\"", "");
                index = rec.get("n3name").toString().replaceAll("(\"|_)", "");
                coefficient = rec.get("n3coefficient").toString().replace("\"", "");//系数
                constant = rec.get("n3constant").toString().replace("\"", "");//常数
                controlType = rec.get("n3controlType").toString().replace("\"", "");
                indexId = rec.get("n3indexId").toString().replace("\"", "");
                score = rec.get("r4score").toString().replace("\"", "");
                option = rec.get("n4name").toString().replace("\"", "");

                //分组计算结果
                JSONObject groupCalcJson = new JSONObject();
                JSONObject groupCalcResult = new JSONObject();
                groupCalcResult.put("value", "");
                groupCalcResult.put("unit", "");
                groupCalcResult.put("text", "");
                groupCalcJson.put("result", groupCalcResult);
                groupCalcJson.put("isShow", isShow);
                if (!scaleStructure.containsKey("scaleType")) {
                    scaleStructure.put("scaleType", Integer.valueOf(type));
                }
                if (!scaleStructure.containsKey("scaleName")) {
                    scaleStructure.put("scaleName", scaleName);
                }
                if (!scaleStructure.containsKey("group")) {
                    scaleStructure.put("group", new JSONArray());
                }
                if (!scaleStructure.containsKey("Calc")) {
                    scaleStructure.put("Calc", Integer.valueOf(calc));
                }

                if (group.contains("-")) {
                    group = group.split("-")[0];
                }

                if (index.contains("-")) {
                    index = index.split("-")[0];
                }

                if (group.contains("计算方法")) {
                    String[] range = mutex.split("~|-");
                    String min = range[0];
                    String max = range[1];
                    result = new TreeMap<>();
                    result.put("min", min);
                    result.put("max", max);
                    result.put("text", text);
                    results.add(result);
                    continue;
                }

                //分组匹配
                JSONObject groupItem = new JSONObject();
                Boolean existGroup = false;
                JSONArray groupList = (JSONArray) scaleStructure.get("group");
                if (groupList.size() > 0) {
                    for (int i = 0; i < groupList.size(); i++) {
                        if (groupList.getJSONObject(i).containsKey("groupName") && groupList.getJSONObject(i).get("groupName").equals(group)) {
                            groupItem = groupList.getJSONObject(i);
                            groupList.remove(i);
                            existGroup = true;
                            break;
                        }
                    }
                }
                if (groupList.size() == 0 || existGroup == false) {
                    groupItem.put("groupName", group);
                    groupItem.put("groupCalculate", groupCalcJson);
                }

                JSONArray rowsList = new JSONArray();
                if (!groupItem.containsKey("rows") || groupItem.get("rows") == null) {
                    groupItem.put("rows", rowsList);
                } else {
                    rowsList = JSONArray.parseArray(groupItem.get("rows").toString());
                }


                Boolean existRow = false;

                for (int j = 0; j < rowsList.size(); j++) {
                    JSONObject rowJson = rowsList.getJSONObject(j);
                    JSONArray rowList = new JSONArray();
                    if (rowJson.containsKey("row")) {
                        rowList = JSONArray.parseArray(rowJson.get("row").toString());
                    } else {
                        rowJson.put("metux", Integer.valueOf(mutex));
                        rowJson.put("required", Integer.valueOf(required));
                        rowJson.put("indexId", Integer.valueOf(indexId));
                        rowJson.put("row", rowList);
                    }
                    for (int i = 0; i < rowList.size(); i++) {

                        JSONObject row = rowList.getJSONObject(i);
                        if (row.containsKey("name") && row.get("name").equals(index)) {
                            JSONArray details = JSON.parseArray(row.get("details").toString());
                            if (!"NULL".equals(option)) {
                                JSONObject rowDetail = new JSONObject();
                                rowDetail.put("detailName", option);
                                rowDetail.put("score", Float.valueOf(score));
                                if (scaleItems.length > 0) {
                                    JSONArray scaleItem = (JSONArray) JSONArray.toJSON(scaleItems);
                                    for (int k = 0; k < scaleItem.size(); k++) {
                                        if (scaleItem.get(k).toString().contains(row.getString("name"))) {
                                            if (scaleItem.get(k).toString().contains(option)) {
                                                rowDetail.put("state", 1);
                                                scaleItem.remove(k);
                                                break;
                                            } else {
                                                rowDetail.put("state", 0);
                                            }
                                        } else {
                                            rowDetail.put("state", 0);
                                        }
                                    }
                                } else {
                                    rowDetail.put("state", 0);
                                }
                                details.add(rowDetail);
                                row.put("details", details);
                            }
                            rowsList.remove(j);
                            rowJson.put("row", rowList);
                            rowsList.add(rowJson);
                            existRow = true;
                            break;
                        }
                    }
                    if (indexId.equals(rowJson.get("indexId").toString()) && existRow == false) {
                        JSONObject row = new JSONObject();
                        row.put("name", index);
                        row.put("coefficient", Integer.valueOf(coefficient));
                        row.put("constant", Integer.valueOf(constant));
                        row.put("controlType", Integer.valueOf(controlType));
                        if (!"NULL".equals(option)) {
                            JSONObject rowDetail = new JSONObject();
                            rowDetail.put("detailName", option);
                            rowDetail.put("score", Float.valueOf(score));
                            if (scaleItems.length > 0) {
                                JSONArray scaleItem = (JSONArray) JSONArray.toJSON(scaleItems);
                                for (int k = 0; k < scaleItem.size(); k++) {
                                    if (scaleItem.get(k).toString().contains(row.getString("name"))) {
                                        if (scaleItem.get(k).toString().contains(option)) {
                                            rowDetail.put("state", 1);
                                            scaleItem.remove(k);
                                            break;
                                        } else {
                                            rowDetail.put("state", 0);
                                        }
                                    } else {
                                        rowDetail.put("state", 0);
                                    }
                                }
                            } else {
                                rowDetail.put("state", 0);
                            }
                            JSONArray details = new JSONArray();
                            details.add(rowDetail);
                            row.put("details", details);
                        }
                        rowList.add(row);
                        rowsList.remove(j);
                        rowJson.put("row", rowList);
                        rowsList.add(rowJson);
                        existRow = true;
                        break;
                    }
                }
                if (rowsList.size() == 0 || existRow == false) {
                    JSONObject rowJson = new JSONObject();
                    rowJson.put("metux", Integer.valueOf(mutex));
                    rowJson.put("required", Integer.valueOf(required));
                    rowJson.put("indexId", Integer.valueOf(indexId));

                    JSONArray rowList = new JSONArray();
                    JSONObject row = new JSONObject();
                    row.put("name", index);
                    row.put("coefficient", Integer.valueOf(coefficient));
                    row.put("constant", Integer.valueOf(constant));
                    row.put("controlType", Integer.valueOf(controlType));
                    if (!"NULL".equals(option)) {
                        JSONObject rowDetail = new JSONObject();
                        rowDetail.put("detailName", option);
                        rowDetail.put("score", Float.valueOf(score));
                        if (scaleItems.length > 0) {
                            JSONArray scaleItem = (JSONArray) JSONArray.toJSON(scaleItems);
                            for (int k = 0; k < scaleItem.size(); k++) {
                                if (scaleItem.get(k).toString().contains(row.getString("name"))) {
                                    if (scaleItem.get(k).toString().contains(option)) {
                                        rowDetail.put("state", 1);
                                        scaleItem.remove(k);
                                        break;
                                    } else {
                                        rowDetail.put("state", 0);
                                    }
                                } else {
                                    rowDetail.put("state", 0);
                                }
                            }
                        } else {
                            rowDetail.put("state", 0);
                        }
                        JSONArray details = new JSONArray();
                        details.add(rowDetail);
                        row.put("details", details);
                    }
                    rowList.add(row);
                    rowJson.put("row", rowList);
                    rowsList.add(rowJson);
                }
                groupItem.put("rows", rowsList);
                groupList.add(groupItem);
                scaleStructure.put("group", groupList);
            }

            calculate.put("range", results);
            calculate.put("formula", "");
            Map<String, String> calcResult = new HashMap<>();
            calcResult.put("value", "");
            calcResult.put("text", "");
            calcResult.put("unit", "");
            calculate.put("result", calcResult);
            scaleStructure.put("calculate", calculate);

        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error("返回带得分需要计算的量表出了问题！---->getScaleCalc2");
        } finally {
            CloseSession(session);
            return scaleStructure;
        }
    }

    /**
     * 返回不带得分不需要计算的量表
     *
     * @param scaleName
     * @return
     */
    public JSONObject getScaleNoCalc(String scaleName) {
        Session session = driver.session(AccessMode.READ);
        StatementResult Rset = null;
        Record rec;
        //scaleName = scaleName.toUpperCase();

        JSONObject scaleStructure = new JSONObject();
        JSONArray rows = new JSONArray();
        JSONObject row = new JSONObject();
        try {
            String query = "match (m:Scale)-[r1]->(n1)-[r2]->(n2)-[r3]->(n3) WHERE m.name='" + scaleName + "' " +
                    "return m.name,m.calc,m.type,n1.name,n1.indexId,n1.required,n1.controlType,n2.name,n3.name " +
                    "order by toInt(r1.p),toInt(r2.p),toInt(r3.p)";

            Rset = session.run(query);

            String calc = "";
            String type = "";
            String index = "";
            String indexId = "";
            String required = "";
            String controlType = "";
            String feature = "";
            String result = "";
            while (Rset.hasNext()) {
                rec = Rset.next();
                scaleName = rec.get("m.name").toString().replace("\"", "");
                calc = rec.get("m.calc").toString().replace("\"", "");
                type = rec.get("m.type").toString().replace("\"", "");
                index = rec.get("n1.name").toString().replaceAll("(\"|_)", "");
                indexId = rec.get("n1.indexId").toString().replace("\"", "");
                required = rec.get("n1.required").toString().replace("\"", "");
                controlType = rec.get("n1.controlType").toString().replace("\"", "");
                feature = rec.get("n2.name").toString().replace("\"", "");
                result = rec.get("n3.name").toString().replace("\"", "");

                if (!scaleStructure.containsKey("scaleType")) {
                    scaleStructure.put("scaleType", Integer.valueOf(type));
                }
                if (!scaleStructure.containsKey("Calc")) {
                    scaleStructure.put("Calc", Integer.valueOf(calc));
                }
                if (!scaleStructure.containsKey("scaleName")) {
                    scaleStructure.put("scaleName", scaleName);
                }

                if (index.contains("-")) {
                    index = index.split("-")[0];
                }

                JSONObject detail = new JSONObject();
                detail.put("detailName", feature);
                detail.put("state", 0);
                detail.put("result", result);
                if (scaleStructure.containsKey("rows")) {
                    JSONArray rowsList = scaleStructure.getJSONArray("rows");
                    if (index.equals(rowsList.getJSONObject(rowsList.size() - 1).getString("name"))) {
                        rowsList.getJSONObject(rowsList.size() - 1).getJSONArray("details").add(detail);
                    } else {
                        row = new JSONObject();
                        JSONArray details = new JSONArray();
                        details.add(detail);
                        row.put("name", index);
                        row.put("indexId", Integer.valueOf(indexId));
                        row.put("required", Integer.valueOf(required));
                        row.put("controlType", Integer.valueOf(controlType));
                        row.put("details", details);
                        rowsList.add(row);
                    }
                } else {
                    JSONArray details = new JSONArray();
                    details.add(detail);
                    row.put("name", index);
                    row.put("indexId", Integer.valueOf(indexId));
                    row.put("required", Integer.valueOf(required));
                    row.put("controlType", Integer.valueOf(controlType));
                    row.put("details", details);
                    rows.add(row);
                    scaleStructure.put("rows", rows);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error("返回不带得分不需要计算的量表出了问题！---->getScaleNoCalc");
        } finally {
            CloseSession(session);
            return scaleStructure;
        }
    }

    /**
     * 查询需要排除的疾病
     * @param info
     * @return
     */
    public Map<String, Map<String, String>> getExcludeDiag(List<String> info) {
        Session session = null;
        String infostr = Pattern.compile("([,*])").matcher(info.toString()).replaceAll("\"$0\"");
        infostr = infostr.replace("[", "[\"");
        infostr = infostr.replace("]", "\"]");
        infostr = infostr.replaceAll(" ", "");

        Map<String, Map<String, String>> diaglist = new HashMap<>();
        try{
            session = driver.session(AccessMode.READ);

            String query = propertiesUtil.getProperty("excludeDiag").replace("infostr",infostr);
            System.out.println(query);
            StatementResult dlist = session.run(query);

            while (dlist.hasNext()) {
                Record rec = dlist.next();
                Node nd = rec.get("d").asNode();
                String name = nd.get("name").toString().replaceAll("\"","");
                diaglist.put(name, new HashMap<>());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            CloseSession(session);
            return diaglist;
        }
    }
    /**
     * 根据年龄和性别排除的疾病
     */
    public Set<String> filterDisFromSexAge(List<String> dis,String sexIn,Integer ageIn){
        Set<String> filterDisList = new HashSet<>();
        Session session = null;
        try {
            session = driver.session(AccessMode.READ);
            String query = "match(d:Disease) where d.name in "+dis+" return d.name as dis,d.sex as sex,d.minAge as minAge,d.maxAge as maxAge";
            StatementResult dlist = session.run(query);
            while (dlist.hasNext()) {
                Record rec = dlist.next();
                String disName = rec.get("dis").toString().replace("\"", "");
                String sex = rec.get("sex").toString();
                int minAge = rec.get("minAge").asInt();
                int maxAge = rec.get("maxAge").asInt();
                if("1".equals(sex) || "2".equals(sex)){
                    if(!sexIn.equals(sex)){
                        filterDisList.add(disName);
                    }
                }
                if(ageIn < minAge || ageIn >maxAge){
                    filterDisList.add(disName);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            CloseSession(session);
            return filterDisList;
        }

    }
}
