package org.diagbot.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.diagbot.entity.node.LIS;
import org.diagbot.entity.node.Symptom;
import org.diagbot.mapper.KnowledgeMapper;
import org.diagbot.pub.Ciku;
import org.diagbot.pub.Label;
import org.diagbot.pub.Type;
import org.diagbot.pub.jdbc.MysqlJdbc;
import org.diagbot.service.KnowledgeService;
import org.diagbot.vo.*;
import org.diagbot.entity.node.Disease;
import org.diagbot.entity.node.base.BaseNode;
import org.apache.commons.collections4.IteratorUtils;
import org.diagbot.repository.*;
import org.diagbot.vo.domain.*;
import org.neo4j.driver.v1.types.Node;
import org.neo4j.driver.v1.types.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.math.RoundingMode;
import java.sql.*;
import java.text.NumberFormat;
import java.util.*;


@Service
public class    KnowledgeServiceImpl implements KnowledgeService {
    Logger logger = LoggerFactory.getLogger(KnowledgeServiceImpl.class);
    @Autowired
    private SymptomRepository symptomRepository;
    @Autowired
    private DiseaseRepository diseaseRepository;
    @Autowired
    private LISRepository lisRepository;
    @Autowired
    private BaseNodeRepository baseNodeRepository;
    @Autowired
    private RelationRepository relationRepository;
    @Autowired
    private ScaleRepository scaleRepository;
    @Autowired
    private KnowledgeMapper knowledgeMapper;
    @Autowired
    private BiRepository biRepository;
    private List<BaseNode> baseNodes;
    private String user = "teamdata";
    private String password = "jiO2rfnYhg";
    private String url = "jdbc:mysql://192.168.2.121:3306/med?useUnicode=true&characterEncoding=UTF-8";
    private Pageable pageable;
    /**
     * 处理症状节点相关的申请
     */
    @Override
    public Symptom addSymptom(Symptom symptom) {
        return symptomRepository.save(symptom);
    }

    @Override
    public Symptom findOneSymptom(long id) {
        return symptomRepository.findById(id).get();
    }

    @Override
    public List<Symptom> findSymptoms(String name) {
        return symptomRepository.findByNameContaining(name);
    }

    @Override
    public void deleteOneSymptom(long id) {
        symptomRepository.deleteById(id);
    }

    @Override
    public List<Symptom> selectAllSymptom(PageVo pageVo) {
        pageable = getPageable(pageVo);
        return IteratorUtils.toList(symptomRepository.findAll().iterator());
    }


    /**
     * 处理疾病节点相关的申请
     */
    @Override
    public Disease addDisease(Disease disease) {
        return diseaseRepository.save(disease);
    }

    @Override
    public Disease findOneDisease(long id) {
        return diseaseRepository.findById(id).get();
    }

    @Override
    public List<Disease> findDisease(String name) {
        return diseaseRepository.findByNameContaining(name);
    }

    @Override
    public void deleteOneDisease(long id) {
        diseaseRepository.deleteById(id);
    }

    @Override
    public List<Disease> selectAllDisease(PageVo pageVo) {
        pageable = getPageable(pageVo);
        return IteratorUtils.toList(diseaseRepository.findAll(pageable).iterator());
    }


    /**
     * 处理化验节点相关的申请
     */
    @Override
    public LIS addLIS(LIS lis) {
        return lisRepository.save(lis);
    }

    @Override
    public LIS findOneLIS(long id) {
        return lisRepository.findById(id).get();
    }

    @Override
    public List<LIS> findLIS(String name) {
        return lisRepository.findByNameContaining(name);
    }

    @Override
    public void deleteOneLIS(long id) {
        lisRepository.deleteById(id);
    }

    @Override
    public List<LIS> selectAllLIS(PageVo pageVo) {
        pageable = getPageable(pageVo);
        return IteratorUtils.toList(lisRepository.findAll().iterator());
    }


    @Override
    public List<Map<String, Object>> getRelationByNodes(RelationVo relationVo) {
        String s_name = relationVo.getStart_name();
        String s_type = relationVo.getStart_type();
        String e_name = relationVo.getEnd_name();
        String e_type = relationVo.getEnd_type();

        List<Map<String, Object>> list = extractPath(relationRepository.getRelationByNodes(s_name, s_type, e_name, e_type));
        return list;
    }

    @Override
    public List<Map<String, Object>> getOneLevelRelationByEndNode(RelationVo relationVo) {
        String e_name = relationVo.getEnd_name();
        String e_type = relationVo.getEnd_type();

        List<Map<String, Object>> list = extractPath(relationRepository.getOneLevelRelationByEndNode(e_name, e_type));
        return list;
    }

    @Override
    public Iterable<Map<String, Object>> getNodeByRelation(RelationVo relationVo) {
        String s_name = relationVo.getStart_name();
        String s_type = relationVo.getStart_type();
        String rel = relationVo.getRel_name();

        return relationRepository.getNodeByRelation(s_name, s_type, rel);
    }

    @Override
    public BaseNode updateNodeByName(AmendRelationVo amendRelationVo) {
        int id = amendRelationVo.getId();
        String old_name = amendRelationVo.getOld_start_name();
        String new_name = amendRelationVo.getNew_start_name();

        return baseNodeRepository.updateNodeByName(id, old_name, new_name);
    }

    @Override
    public List<Map<String, Object>> updateRelation(AmendRelationVo amendRelationVo) {
        List<Map<String, Object>> path = extractPath(knowledgeMapper.updateRelation(amendRelationVo));
        return path;
    }

    @Override
    public List<Map<String, Object>> getAllNode() {
        List<Map<String, Object>> ndlist = baseNodeRepository.getAllNode();
        return ndlist;
    }

    @Override
    public Map<String, Object> getHighRiskDisease(SearchData searchData) {
        Map<String, Object> map = new HashMap<>();
        String diag = searchData.getDiag();
        if (diag != null && diag != "") {
            String[] splitsDiag = searchData.getDiag().split(",|，|、");
            List<String> diseaseNameList = Arrays.asList(splitsDiag);
            List<Map<String, Object>> list = baseNodeRepository.getHighRisk(diseaseNameList);
            for (Map hrmap : list) {
                String name = hrmap.get("name").toString();
                String risk = hrmap.get("risk").toString();
                map.put(name, risk);
            }
        }
        return map;
    }

    /**
     * 推送疑诊,鉴别诊断,急诊,指标推送,不良反应,管理评估
     *
     * @param searchData
     * @return
     */
    @Override
    public ResponseData getDis(SearchData searchData) {
        ResponseData responseData = new ResponseData();
        Set<String> queZhen = new HashSet<>();
        Map<String, Map<String, String>> diseaseCondition = new LinkedHashMap<>();
        String webDiag = searchData.getDiag();
        String[] featureTypes = searchData.getFeatureType().split(",");
        List<String> featureTypeList = Arrays.asList(featureTypes);
        logger.info("前端传来的features :" + featureTypeList);
        Map<String, Map<String, String>> inputs = searchData.getGraphInputs();
        Integer diseaseType = searchData.getDisType();
        logger.info("diseaseType为 :" + diseaseType);
        Set<String> ss = new HashSet<>();
        if(inputs.size()>0){
            for (Map.Entry<String, Map<String, String>> input:inputs.entrySet()) {
                Map<String, String> value = input.getValue();
                String concept = value.get("concept");
                String[] splits = StringUtils.split(concept, ",");
                for (String s:splits) {
                    ss.add(s);
                }
            }
        }
        logger.info("分词系统传来的词: " + ss);
        logger.info("图谱开始根据传来的分词计算诊断.....");
        //开始推送诊断逻辑,包括推送疑诊,急诊,鉴别诊断
        if (featureTypeList != null && featureTypeList.contains("2")) {
            //第一,二步查询输入的词所在number
            Set<String> fildInNumber = this.getNumber(ss);
            //第三步查找疑诊
            List<Map<String, Object>> fildDis = baseNodeRepository.getFildDis(fildInNumber);
            if (fildDis != null && fildDis.size() > 0) {
                for (Map<String, Object> disMap : fildDis) {
                    String relationType = disMap.get("relationType").toString();
                    String name = disMap.get("name").toString();
                    if ("确诊".equals(relationType)) {
                        queZhen.add(name);
                    } else if ("拟诊".equals(relationType)) {
                        queZhen.add(name);
                    }
                }
            }
            logger.info("图谱推出的疑诊为: " + queZhen);
            for (String que : queZhen) {
                Map<String, String> titleMap = new HashMap<>();
                titleMap.put("确诊", "");
                diseaseCondition.put(que, titleMap);
            }
            //第四步查找鉴别诊断
            String mainDiag = null;//主诊断
            if (webDiag != null && !"".equals(webDiag)) {
                String[] webDiagSplits = webDiag.split(",");
                mainDiag = webDiagSplits[0];
            }
            if (mainDiag != null) {
                //走鉴别诊断逻辑
                List<String> diffDis = baseNodeRepository.getDiffDis(mainDiag);
                if (diffDis != null && diffDis.size() > 0) {
                    for (String diff : diffDis) {
                        if (queZhen.contains(diff)) {
                            Map<String, String> stringStringMap = diseaseCondition.get(diff);
                            stringStringMap.put("鉴别诊断", "");
                            diseaseCondition.put(diff, stringStringMap);
                        } else {
                            Map<String, String> diffMap = new HashMap<>();
                            diffMap.put("鉴别诊断", "");
                            diseaseCondition.put(diff, diffMap);
                        }
                    }
                }
            }
            //急诊逻辑
            List<String> emergency = baseNodeRepository.getEmergency(diseaseCondition.keySet());
            if (emergency != null && emergency.size() > 0) {
                for (String em : emergency) {
                    Map<String, String> stringStringMap = diseaseCondition.get(em);
                    stringStringMap.put("急诊", "");
                    diseaseCondition.put(em, stringStringMap);
                }
            }
            List<FeatureRate> featureRates = new ArrayList<>();
            if (diseaseCondition != null) {
                for (Map.Entry<String, Map<String, String>> d : diseaseCondition.entrySet()) {
                    FeatureRate featureRate = new FeatureRate();
                    featureRate.setFeatureName(d.getKey());
                    featureRate.setExtraProperty("neo4j");
                    Map<String, String> value = d.getValue();
                    String s = JSON.toJSONString(value);
                    featureRate.setDesc(s);
//                    featureRate.setRate("neo4j");
                    featureRates.add(featureRate);
                }
            }
            responseData.setDis(featureRates);
        }
        Set<String> que = diseaseCondition.keySet();
        logger.info("图谱计算出来的诊断(包含疑诊,急诊,鉴别诊断)为: " + que);

        //推送治疗,包含不良反应
        if (webDiag != null && webDiag.trim() != "" && featureTypeList.contains("6")) {
            logger.info("界面有诊断,并且features包含8,可以走治疗方案");
            //查找页面诊断里是否有不良反应(慢病的情况下)
            Map<String, List<String>> disUE = new HashMap<>();
            String[] webDiagList = webDiag.split(",|，|、|;|:|；");
            List<Map<String, Object>> untowardEffect = baseNodeRepository.getUntowardEffect(webDiagList);
            if (untowardEffect.size() > 0) {
                for (Map<String, Object> ue : untowardEffect) {
                    String dis = ue.get("dis").toString();
                    String[] ueCollect = (String[]) ue.get("ueCollect");
                    List<String> ueList = Arrays.asList(ueCollect);
                    disUE.put(dis, ueList);
                }
            }
            //根据页面输入内容推出的不良反应集合
            Set<String> ue = this.getUe(ss);
            // webDiag:界面诊断,ss:分词,diseaseType:疾病类型,que:疑诊,鉴别诊断,急诊集合
            Map<String, Filnlly> mulDiseaseTreat = processTreat(webDiag, ss, diseaseType, que, disUE, ue);
            responseData.setTreat(mulDiseaseTreat);
        }
        int age = searchData.getAge();
        String sex = searchData.getSex();
        //指标推送
        if (featureTypeList.contains("22")) {
            logger.info("图谱推送有疑诊,并且features包含22,可以走右侧推送");
            //根据传来的词推送指标
            Set<String> ind = this.getInd(ss);
            logger.info("图谱推出的指标为: " + ind);
            List<MedicalIndication> medicalIndications = this.indProcess(ind, sex, age);
            responseData.setMedicalIndications(medicalIndications);
        }

        List<LisDetail> lisArr = searchData.getLisArr();
        Set<String> lisSet = new HashSet<>();
        Map<String, Double> lis_Result = new HashMap<>();
        if (lisArr != null && lisArr.size() > 0) {
            for (LisDetail lis : lisArr) {
                String detailName = lis.getUniqueName();
                logger.info("公表名为  :" + detailName);
                Double value = lis.getValue();
                lis_Result.put(detailName, value);
                lisSet.add(detailName);
            }
        }
        logger.info("页面导入的所有化验项为 :" + lisSet);
        //推送管理评估
        if (featureTypeList.contains("11") && diseaseType == 1 && diseaseType != null) {
            logger.info("featureTypeList 包含11,走管理评估!!!");
            if (webDiag != null && !"".equals(webDiag)) {
                String[] webDiagsplits = webDiag.split(",|，|、|;|:|；");
                MangementEvaluation mangementEvaluation = this.pushMe(webDiagsplits, lis_Result);
                Map<String, JSONObject> mangementEvaluation1 = mangementEvaluation.getMangementEvaluation();
                responseData.setManagementEvaluation(mangementEvaluation1);
            }
        }
        return responseData;
    }

    /**
     * 获取化验和辅检,体征结果
     * @param searchData
     * @return
     */
    @Override
    public Map<String, List<FeatureRate>> getLisPacs(SearchData searchData) {
        String[] featureArray = StringUtils.split(searchData.getFeatureType(), ",");
        List<String> featureList = Arrays.asList(searchData.getFeatureTypes());
        Map<String, List<FeatureRate>> lisPacsFeature = new HashMap<>();
        String webDiag = searchData.getDiag();
        List<String> webDiagList = null;
        if (webDiag != null && webDiag != "") {
            webDiagList = Arrays.asList(webDiag.split(",|，|、"));
        }
        List<FeatureRate> bigdataDiagFeature = searchData.getPushDiags();
        List<String> neo4jDiagList = new LinkedList<>();//疑似诊断
        List<String> bigdataDiagList = new LinkedList<>();//大数据诊断
        if (bigdataDiagFeature.size() > 0) {
            for (FeatureRate fe : bigdataDiagFeature) {
                if ("neo4j".equals(fe.getSource()) && (fe.getDesc().contains("确诊") || fe.getDesc().contains("拟诊"))) {
                    neo4jDiagList.add(fe.getFeatureName());
                } else if (fe.getDesc() == null) {
                    bigdataDiagList.add(fe.getFeatureName());
                }
            }
        }
        logger.info("图谱推出的诊断为: " + neo4jDiagList);
        logger.info("大数据推出的诊断为: " + bigdataDiagList);
        if (webDiagList != null) {
            for (String web : webDiagList) {
                for (int i = 0; i < bigdataDiagList.size(); i++) {
                    if (bigdataDiagList.get(i).equals(web)) {
                        bigdataDiagList.remove(bigdataDiagList.get(i));
                    }
                }
                for (int i = 0; i < neo4jDiagList.size(); i++) {
                    if (neo4jDiagList.get(i).equals(web)) {
                        neo4jDiagList.remove(neo4jDiagList.get(i));
                    }
                }
            }
        }
        logger.info("界面诊断为: " + webDiagList);
        Map<String, LinkedHashSet<String>> weblisPacs = null,webVital = null;
        Map<String, LinkedHashSet<String>> neo4jlisPacs = null,neo4jVital = null;
        Map<String, LinkedHashSet<String>> biglisPacs = null,bigVital = null;
        if (webDiagList != null && webDiagList.size() > 0) {
            weblisPacs = processLisPacs(webDiagList);
            webVital = processVital(webDiagList);
        }
        if (neo4jDiagList != null && neo4jDiagList.size() > 0) {
            neo4jlisPacs = processLisPacs(neo4jDiagList);
            neo4jVital = processVital(neo4jDiagList);
        }
        if (bigdataDiagList != null && bigdataDiagList.size() > 0) {
            biglisPacs = processLisPacs(bigdataDiagList);
            bigVital = processVital(bigdataDiagList);
        }
        Set<String> lis = new LinkedHashSet<>();
        Set<String> pacs = new LinkedHashSet<>();
        Set<String> vitalReultSet = new LinkedHashSet<>();
        Set<String> webLis = null;
        Set<String> webPacs = null;
        Set<String> neoLis = null;
        Set<String> neoPacs = null;
        Set<String> bigLis = null;
        Set<String> bigPacs = null;
        //如果界面有诊断
        if (weblisPacs != null && weblisPacs.values().size() > 0) {
            webLis = weblisPacs.get("LIS");
            webPacs = weblisPacs.get("PACS");
            logger.info("界面有诊断的情况下,界面诊断推出的lis为: " + webLis);
            logger.info("界面有诊断的情况下,界面诊断推出的pacs为: " + webPacs);
            if(webLis != null){
               lis.addAll(webLis);
            }
            if(webPacs != null){
                pacs.addAll(webPacs);
            }
            vitalReultSet.addAll(webVital.get("VITAL_RESULT"));
        }
        if(neo4jlisPacs != null){
            neoLis = neo4jlisPacs.get("LIS");
            neoPacs =  neo4jlisPacs.get("PACS");
            if(neoLis != null){
                lis.addAll(neoLis);
            }
            if(neoPacs != null){
                pacs.addAll(neoPacs);
            }
            vitalReultSet.addAll(neo4jVital.get("VITAL_RESULT"));
        }
        if(biglisPacs != null){
            bigLis = biglisPacs.get("LIS");
            bigPacs = biglisPacs.get("PACS");
            if(bigLis != null){
                lis.addAll(bigLis);
            }
            if(bigPacs != null){
                pacs.addAll(bigPacs);
            }
            vitalReultSet.addAll(bigVital.get("VITAL_RESULT"));
        }
        logger.info("推出的合并lis为: " + lis);
        logger.info("推出的合并pacs为: " + pacs);
        logger.info("推出的合并体征结果为: " + vitalReultSet);
        ArrayList<FeatureRate> lisFeature = new ArrayList<>();
        ArrayList<FeatureRate> pacsFeature = new ArrayList<>();
        ArrayList<FeatureRate> vitalFeature = new ArrayList<>();
        if (lis != null && lis.size() > 0 && featureList.contains("4")) {
            List<String> newLis = new ArrayList<>();
            if(lis.size()>searchData.getLength()){
                for (String l:lis) {
                   if(newLis.size()<searchData.getLength()){
                       newLis.add(l);
                   }
                }
            }else {
                newLis.addAll(lis);
            }
            for (String l : newLis) {
                FeatureRate featureRate = new FeatureRate();
                featureRate.setFeatureName(l);
                lisFeature.add(featureRate);
            }
        }
        if (pacs != null && pacs.size() > 0 && featureList.contains("5")) {
            List<String> newPacs = new ArrayList<>();
            if(pacs.size()>searchData.getLength()){
                for (String l:pacs) {
                    if(newPacs.size()<searchData.getLength()){
                        newPacs.add(l);
                    }
                }
            }else {
                newPacs.addAll(pacs);
            }
            for (String p : newPacs) {
                FeatureRate featureRate = new FeatureRate();
                featureRate.setFeatureName(p);
                pacsFeature.add(featureRate);
            }
        }
        if(vitalReultSet.size() > 0){
            List<String> newVitalRes = new ArrayList<>();
            if(vitalReultSet.size()>searchData.getLength()){
                for (String l:vitalReultSet) {
                    if(newVitalRes.size()<searchData.getLength()){
                        newVitalRes.add(l);
                    }
                }
            }else {
                newVitalRes.addAll(vitalReultSet);
            }
            for (String p : newVitalRes) {
                FeatureRate featureRate = new FeatureRate();
                featureRate.setFeatureName(p);
                vitalFeature.add(featureRate);
            }
        }
        lisPacsFeature.put("lisList", lisFeature);
        lisPacsFeature.put("pacsList", pacsFeature);
        lisPacsFeature.put("vitalResultList",vitalFeature);

        return lisPacsFeature;
    }

    //查询词所在number,及有用的condition
    public Set<String> getNumber(Set<String> ss) {
        List<String> newList = new ArrayList<>();
        Set<String> fildInNumber = baseNodeRepository.getFildInNumber(ss);
        newList.addAll(fildInNumber);
        //第二步查询符合的condition4
        while (newList.size() > 0) {
            List<String> fildInCondition = baseNodeRepository.getFildInCondition(newList, fildInNumber);
            newList.clear();
            if (fildInCondition != null && fildInCondition.size() > 0) {
                for (String condition : fildInCondition) {
                    newList.add(condition);
                    fildInNumber.add(condition);
                }
            }
        }
        return fildInNumber;
    }

    /**
     * 查询体征
     * @param webDiagList
     * @return
     */
    public Map<String, LinkedHashSet<String>> processVital(List<String> webDiagList) {
        Map<String, LinkedHashSet<String>> vitalMap = new HashMap<>();
        LinkedHashSet<String> vitalResultArray = new LinkedHashSet<>();//体征结果
        List<Map<String, Object>> vitalList = baseNodeRepository.getVitalList(webDiagList);
        if (vitalList != null && vitalList.size() > 0) {
            for (Map<String, Object> f : vitalList) {
                String name = f.get("name").toString();
                vitalResultArray.add(name);
            }
        }
        vitalMap.put("VITAL_RESULT", vitalResultArray);
        return vitalMap;
    }
    /**
     * 根据内容推出不良反应集合
     *
     * @param ss 分词
     * @return
     */
    public Set<String> getUe(Set<String> ss) {
        Set<String> number = getNumber(ss);
        Set<String> ueSet = baseNodeRepository.pushUntowardEffects(number);
        return ueSet;
    }

    /**
     * 根据传来的词推送指标
     *
     * @param ss
     * @return
     */
    public Set<String> getInd(Set<String> ss) {
        Set<String> number = getNumber(ss);
        Set<String> indSet = baseNodeRepository.pushInd(number);
        return indSet;
    }

    /**
     * 指标推送处理
     *
     * @param indSet 指标集合
     * @param sex    性别
     * @param age    年龄
     * @return
     */
    public List<MedicalIndication> indProcess(Set<String> indSet, String sex, Integer age) {
        List<MedicalIndication> medicalIndicationList = new ArrayList<>();
        if (indSet != null && indSet.size() > 0) {
            for (String s : indSet) {
                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<>();
                List<Map<String, Object>> allSortMaps = baseNodeRepository.allSort(s);
                if (allSortMaps != null && allSortMaps.size() > 0) {
                    for (Map<String, Object> asm : allSortMaps) {
                        Integer sort1 = Integer.parseInt(asm.get("sort1").toString());
                        String conten = asm.get("conten").toString();
                        Object item = asm.get("item");
                        if (item == null) {
                            item = "null";
                        }
                        Object controlType = asm.get("controlType");
                        if (controlType == null) {
                            controlType = 20;
                        }
                        Object value = asm.get("value");
                        if (value == null) {
                            value = "null";
                        }
                        Object uint = asm.get("uint");
                        if (uint == null) {
                            uint = "null";
                        }
                        Object state1 = asm.get("state");
                        if (state1 == null) {
                            state1 = "20";
                        }
                        Object details = asm.get("details");
                        if (details == null) {
                            details = "null";
                        }
                        if (1 == sort1) {
                            if (medicalIndicationDetail1 == null) {
                                medicalIndicationDetail1 = new MedicalIndicationDetail();
                            }
                            medicalIndicationDetail1.setType(sort1);
                            JSONObject liangJson = new JSONObject();
                            liangJson.put("name", conten);
                            medicalIndicationDetail1.setContent(liangJson);
                        } else if (2 == sort1) {
                            if (medicalIndicationDetail2 == null) {
                                medicalIndicationDetail2 = new MedicalIndicationDetail();
                            }
                            medicalIndicationDetail2.setType(sort1);
                            if (gongshiJson == null) {
                                gongshiJson = new JSONObject();
                            }
                            gongshiJson.put("name", conten);
                            if (detailList == null) {
                                detailList = new ArrayList<>();
                            }
                            JSONObject ageJsonObject = new JSONObject();
                            ageJsonObject.put("controlType", Integer.parseInt(controlType.toString()));
                            ageJsonObject.put("name", item);
                            ageJsonObject.put("value", value);
                            ageJsonObject.put("uint", uint);
                            if ("年龄".equals(item)) {
                                ageJsonObject.put("value", age);
                            }
                            if (0 != Integer.parseInt(controlType.toString())) {
                                ageJsonObject.put("details", details);
                            } else {
                                if (sexList == null) {
                                    sexList = new ArrayList<>();
                                }
                                List<Map<String, Object>> itemMaps = baseNodeRepository.indItemDetail(item.toString());
                                if (itemMaps != null && itemMaps.size() > 0) {
                                    for (Map<String, Object> items : itemMaps) {
                                        String name = items.get("name").toString();
                                        int state = Integer.parseInt(items.get("state").toString());
                                        String value1 = items.get("value").toString();
                                        JSONObject manJson = new JSONObject();
                                        manJson.put("detailName", name);
                                        manJson.put("value", value1);
                                        manJson.put("state", state);
                                        if ("男".equals(name) && "M".equals(sex)) {
                                            manJson.put("state", 1);
                                        } else if ("女".equals(name) && "F".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<>();
                            }
                            List<Map<String, Object>> indcontent = baseNodeRepository.indcontent(conten);
                            if (indcontent.size() > 0 && indcontent != null) {
                                for (Map<String, Object> con : indcontent) {
                                    String name = con.get("name").toString();
                                    results.add(name);
                                }
                            }
                        } 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);
                            shiJsonObject.put("state", Integer.parseInt(state1.toString()));
                            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;
        }
        return medicalIndicationList;
    }

    /**
     * 推送管理评估
     *
     * @param webDiagsplits
     * @param lis_Result
     * @return
     */
    public MangementEvaluation pushMe(String[] webDiagsplits, Map<String, Double> lis_Result) {
        MangementEvaluation mangementEvaluation = new MangementEvaluation();
        Map<String, JSONObject> mangementMap = new HashMap<>();
        if (webDiagsplits != null && webDiagsplits.length > 0) {
            String diag = webDiagsplits[0];//慢病
            if ("糖尿病".equals(diag)) {
                Map<String, LinkedList<String>> effCollect = new LinkedHashMap<>();
                List<Map<String, Object>> allMaps = baseNodeRepository.meAllQuery(diag);
                if (allMaps != null && allMaps.size() > 0) {
                    for (Map<String, Object> am : allMaps) {
                        String eff = am.get("eff").toString();//血压控制情况
                        String res = am.get("res").toString();//正常
                        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<>();
                        //化验计算
                        List<Map<String, Object>> calXueMap = baseNodeRepository.culXuezhi(key);
                        if (calXueMap != null && calXueMap.size() > 0) {
                            for (Map<String, Object> cal : calXueMap) {
                                String name = cal.get("name").toString();
                                String between = cal.get("between").toString();
                                String[] betweenSplit = between.split(",");
                                double min = Double.parseDouble(betweenSplit[0].replace("[", ""));
                                double max = Double.parseDouble(betweenSplit[1].replace("]", ""));
                                String res1 = cal.get("res").toString();
                                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(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);
            }
        }
        return mangementEvaluation;
    }


    public Map<String, LinkedHashSet<String>> processLisPacs(List<String> webDiagList) {
        Map<String, LinkedHashSet<String>> lisPacsMap = new HashMap<>();
        LinkedHashSet<String> lisArray = new LinkedHashSet<>();
        LinkedHashSet<String> pacsArray = new LinkedHashSet<>();
        List<Map<String, Object>> lisPacsList = baseNodeRepository.getLisPacsList(webDiagList);
        if (lisPacsList != null && lisPacsList.size() > 0) {
            for (Map<String, Object> f : lisPacsList) {
                String label = f.get("label").toString();
                String name = f.get("name").toString();
                if ("LIS".equals(label)) {
                    lisArray.add(name);
                } else if ("PACS".equals(label)) {
                    pacsArray.add(name);
                }
            }
        }
//        lisPacsMap.put("LIS", processList(lisArray));
//        lisPacsMap.put("PACS", processList(pacsArray));
        lisPacsMap.put("LIS", lisArray);
        lisPacsMap.put("PACS", pacsArray);
        return lisPacsMap;
    }

    /**
     * 处理治疗
     *
     * @param
     */
    public Map<String, Filnlly> processTreat(String webDisease, Set<String> inputFilds, Integer
            disType, Set<String> que, Map<String, List<String>> disUE, Set<String> ue) {
        Map<String, Filnlly> diagTreat = new HashMap<>();
        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMinimumFractionDigits(0);//设置该百分比数字，保留2位小数;
        nf.setRoundingMode(RoundingMode.HALF_UP); //设置满5向上进位，即四舍五入;
        String[] diseaseArray = webDisease.split(",|，|、|;|:|；");
        List<String> diseaseList = Arrays.asList(diseaseArray);
        Map<String, List> diseFilds = new HashMap<>();
        for (int i = 0; i < diseaseList.size(); i++) {
            List<String> fildsList = new ArrayList<>();//其他条件数组
            for (String fild : inputFilds) {
                fildsList.add(fild);
            }
            if (que != null && que.size() > 0) {
                for (String yizhen : que) {
                    fildsList.add(yizhen);
                }
            }
            for (String h : ue) {
                fildsList.add(h);
            }
            for (int j = 0; j < diseaseList.size(); j++) {
                if (i != j) {
                    fildsList.add(diseaseList.get(j));
                }
            }
            diseFilds.put(diseaseList.get(i), fildsList);
        }
        for (Map.Entry<String, List> disFild : diseFilds.entrySet()) {
            //获取诊断的药类和用药(排序好的)
            List<Map<String, Object>> treatMedicaton = baseNodeRepository.getTreatMedicaton(disFild.getKey());
            Map<String, LinkedHashMap<String, String>> contentMap = new LinkedHashMap<>();
            if (treatMedicaton != null && treatMedicaton.size() > 0) {
                for (Map<String, Object> tm : treatMedicaton) {
                    String drugs = tm.get("drugs").toString();
                    String medication = tm.get("medication").toString();
                    String rate = tm.get("rate").toString();
                    if (contentMap.containsKey(drugs)) {
                        LinkedHashMap<String, String> drugsMedicationLinkedHashMap = contentMap.get(drugs);
                        drugsMedicationLinkedHashMap.put(medication, rate);
                        contentMap.put(drugs, drugsMedicationLinkedHashMap);
                    } else {
                        LinkedHashMap<String, String> sa = new LinkedHashMap<>();
                        sa.put(medication, rate);
                        contentMap.put(drugs, sa);
                    }
                }
            }
            //药所属类型的大小类合并
            Map<String, String> shortLargeMap = new HashMap<>();
            List<Map<String, Object>> shortLarge = baseNodeRepository.getShortLarge(disFild.getKey());
            if (shortLarge != null && shortLarge.size() > 0) {
                for (Map<String, Object> sl : shortLarge) {
                    String aShort = sl.get("short").toString();
                    String large = sl.get("large").toString();
                    shortLargeMap.put(aShort, large + "(" + aShort + ")");
                }
            }
            //小类替换成大类
            Map<String, LinkedHashMap<String, String>> shortLargeMapConcat = new LinkedHashMap<>();
            for (Map.Entry<String, LinkedHashMap<String, String>> f : contentMap.entrySet()) {
                String drugs = f.getKey();
                if (shortLargeMap.get(drugs) != null) {
                    shortLargeMapConcat.put(shortLargeMap.get(drugs), contentMap.get(drugs));
                } else {
                    shortLargeMapConcat.put(drugs, contentMap.get(drugs));
                }
            }
            //处理慎用,忌用
            Map<String, String> medicationUseMap = new HashMap<>();//key:药名 value:禁忌(慎用)
            List<Map<String, Object>> shenJi = baseNodeRepository.getShenJiDrugsMedication(disFild.getKey(), disFild.getValue());
            if (shenJi != null && shenJi.size() > 0) {
                for (Map<String, Object> sj : shenJi) {
                    String name = sj.get("name").toString();
                    String type = sj.get("type").toString();
                    medicationUseMap.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;
                int forbidden = 0;
                Drugs drugs = new Drugs();
                String drugsName = w.getKey();
                Map<String, String> bigSubDrugs = drugsPattern.bigSubDrugs(drugsName);
                drugs.setBigdrugsName(bigSubDrugs.get("big"));
                drugs.setSubdrugsName(bigSubDrugs.get("sub"));
                LinkedList<Medicition> medicitionsList = new LinkedList<>();
                LinkedHashMap<String, String> meditionRate = w.getValue();
                if ("忌用".equals(medicationUseMap.get(bigSubDrugs.get("big"))) || "忌用".equals(medicationUseMap.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(medicationUseMap.get(bigSubDrugs.get("big"))) || "慎用".equals(medicationUseMap.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 (disType != null && 1 == disType) {
                logger.info("disType=1,可以走不良反应!!");
                List<String> diseUeList = disUE.get(disFild.getKey());
                if (diseUeList != null && diseUeList.size() > 0) {
                    List<Indicators> indicatorsList1 = new ArrayList<>();
                    for (String de : diseUeList) {
                        Indicators indicators1 = getAdverse(ue, de);
                        indicatorsList1.add(indicators1);
                    }
                    filnlly.setAdverseEvent(indicatorsList1);
                }
            }
            filnlly.setTreatment(drugsList);
            diagTreat.put(disFild.getKey(), filnlly);
        }
        return diagTreat;
    }

    /**
     * 量表和指标
     *
     * @param diseaseSet 图谱推出的诊断
     * @return
     */
    public MedicalIndication getMedicalIndication(Set<String> diseaseSet) {
        MedicalIndication medicalIndication = new MedicalIndication();
        if (diseaseSet.contains("肾功能不全")) {
            logger.info("diseaseSet中包含肾功能不全");
            //推送指标
            medicalIndication.setName("肾功能不全");
            List<MedicalIndicationDetail> medicalIndicationDetailList = new ArrayList<>();
            //量表
            MedicalIndicationDetail medicalIndicationDetail1 = new MedicalIndicationDetail();
            medicalIndicationDetail1.setType(1);
            JSONObject liangJson = new JSONObject();
            liangJson.put("name", "密西根糖尿病周围神经病评分（MDNS）");
            medicalIndicationDetail1.setContent(liangJson);
            //公式
            MedicalIndicationDetail medicalIndicationDetail2 = new MedicalIndicationDetail();
            medicalIndicationDetail2.setType(2);
            JSONObject gongshiJson = new JSONObject();
            gongshiJson.put("name", "肾小球滤过率");
            List<JSONObject> detailList = new ArrayList<>();
            JSONObject ageJsonObject = new JSONObject();
            ageJsonObject.put("controlType", 2);
            ageJsonObject.put("name", "年龄");
            ageJsonObject.put("value", "");
            ageJsonObject.put("uint", "");
            ageJsonObject.put("details", new ArrayList<>());
            JSONObject indicationJsonObject = new JSONObject();
            indicationJsonObject.put("controlType", 2);
            indicationJsonObject.put("name", "血肌酐");
            indicationJsonObject.put("value", "");
            indicationJsonObject.put("uint", "mg/dL");
            indicationJsonObject.put("details", new ArrayList<>());
            JSONObject sexJson = new JSONObject();
            sexJson.put("controlType", 1);
            sexJson.put("name", "性别");
            sexJson.put("value", "");
            sexJson.put("uint", "");
            List<JSONObject> sexList = new ArrayList<>();
            JSONObject manJson = new JSONObject();
            manJson.put("detailName", "男");
            manJson.put("value", 1);
            manJson.put("state", 0);
            JSONObject womanJson = new JSONObject();
            womanJson.put("detailName", "女");
            womanJson.put("value", 1.018);
            womanJson.put("state", 1);
            sexList.add(manJson);
            sexList.add(womanJson);
            sexJson.put("details", sexList);
            detailList.add(ageJsonObject);
            detailList.add(indicationJsonObject);
            detailList.add(sexJson);
            gongshiJson.put("details", detailList);
            JSONObject resultJson = new JSONObject();
            resultJson.put("value", "");
            resultJson.put("unit", "");
            resultJson.put("text", "");
            gongshiJson.put("result", resultJson);
            medicalIndicationDetail2.setContent(gongshiJson);
            //其他
            MedicalIndicationDetail medicalIndicationDetail3 = new MedicalIndicationDetail();
            medicalIndicationDetail3.setType(3);
            JSONObject shiFouJson = new JSONObject();
            shiFouJson.put("name", "是否");
            shiFouJson.put("controlType", 0);
            List<JSONObject> shiFouList = new ArrayList<>();
            JSONObject shiJsonObject = new JSONObject();
            shiJsonObject.put("detailName", "是");
            shiJsonObject.put("state", 0);
            JSONObject fouJsonObject = new JSONObject();
            fouJsonObject.put("detailName", "否");
            fouJsonObject.put("state", 1);
            shiFouList.add(shiJsonObject);
            shiFouList.add(fouJsonObject);
            shiFouJson.put("details", shiFouList);
            medicalIndicationDetail3.setContent(shiFouJson);
            medicalIndicationDetailList.add(medicalIndicationDetail1);
            medicalIndicationDetailList.add(medicalIndicationDetail2);
            medicalIndicationDetailList.add(medicalIndicationDetail3);
            medicalIndication.setDetails(medicalIndicationDetailList);
        }
        return medicalIndication;
    }

    /**
     * 管理评估
     *
     * @return
     */
    public MangementEvaluation getMangementEvaluation() {
        MangementEvaluation mangementEvaluation = new MangementEvaluation();
        Map<String, JSONObject> mangementMap = new HashMap<>();
        JSONObject curativeJson = new JSONObject();
        List<JSONObject> itemJson = new ArrayList<>();
        JSONObject bloodPressure = new JSONObject();
        bloodPressure.put("controltype", 0);
        bloodPressure.put("name", "血压控制情况");
        List<JSONObject> bloodPressureLevelList = new ArrayList<>();
        String[] items = {"正常", "1级", "2级", "3级"};
        for (String item : items) {
            JSONObject iJson = new JSONObject();
            iJson.put("detailName", item);
            iJson.put("state", 0);
            bloodPressureLevelList.add(iJson);
        }
        bloodPressure.put("details", bloodPressureLevelList);
        itemJson.add(bloodPressure);

        JSONObject bmiControl = new JSONObject();
        bmiControl.put("controltype", 0);
        bmiControl.put("name", "BMI控制情况");
        List<JSONObject> bmiControlLevelList = new ArrayList<>();
        String[] bmiControlitems = {"体重过低", "体重达标", "肥胖前期", "肥胖"};
        for (String item : bmiControlitems) {
            JSONObject iJson = new JSONObject();
            iJson.put("detailName", item);
            iJson.put("state", 0);
            bmiControlLevelList.add(iJson);
        }
        bmiControl.put("details", bmiControlLevelList);
        itemJson.add(bmiControl);

        JSONObject bloodFatControl = new JSONObject();
        bloodFatControl.put("controltype", 0);
        bloodFatControl.put("name", "血脂控制情况");
        List<JSONObject> bloodFatControlLevelList = new ArrayList<>();
        String[] bloodFatControlitems = {"高血脂"};
        for (String item : bloodFatControlitems) {
            JSONObject iJson = new JSONObject();
            iJson.put("detailName", item);
            iJson.put("state", 0);
            bloodFatControlLevelList.add(iJson);
        }
        bloodFatControl.put("details", bmiControlLevelList);
        itemJson.add(bloodFatControl);
        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);
        return mangementEvaluation;
    }

    public Map getTest() {
        Map result = new HashMap();
        //疗效评估
        Map liaoXiaoMap = new HashMap();
        List<Map> rowList = new ArrayList<>();
        Map item1 = new HashMap();
        item1.put("controltype", 0);
        item1.put("name", "血压控制情况");
        List<Map> item1DetailList = new ArrayList<>();
        Map de1 = new HashMap();
        de1.put("detailName", "正常");
        de1.put("state", 1);
        Map de2 = new HashMap();
        de2.put("detailName", "1级");
        de2.put("state", 0);
        Map de3 = new HashMap();
        de3.put("detailName", "2级");
        de3.put("state", 0);
        Map de4 = new HashMap();
        de4.put("detailName", "3级");
        de4.put("state", 0);
        item1DetailList.add(de1);
        item1DetailList.add(de2);
        item1DetailList.add(de3);
        item1DetailList.add(de4);
        item1.put("details", item1DetailList);

        Map item2 = new HashMap();
        item2.put("controltype", 1);
        item2.put("name", "BMI控制情况");
        List<Map> item2DetailList = new ArrayList<>();
        Map be1 = new HashMap();
        be1.put("detailName", "体重过低");
        be1.put("state", 1);
        Map be2 = new HashMap();
        be2.put("detailName", "体重达标");
        be2.put("state", 0);
        Map be3 = new HashMap();
        be3.put("detailName", "肥胖前期");
        be3.put("state", 0);
        Map be4 = new HashMap();
        be4.put("detailName", "肥胖");
        be4.put("state", 0);
        item2DetailList.add(be1);
        item2DetailList.add(be2);
        item2DetailList.add(be3);
        item2DetailList.add(be4);
        item2.put("details", item2DetailList);

        Map item3 = new HashMap();
        item3.put("controltype", 0);
        item3.put("name", "血脂控制情况");
        List<Map> item3DetailList = new ArrayList<>();
        Map xe1 = new HashMap();
        xe1.put("detailName", "高血脂");
        xe1.put("state", 1);
        item3DetailList.add(xe1);
        item3.put("details", item3DetailList);

        rowList.add(item1);
        rowList.add(item2);
        rowList.add(item3);
        liaoXiaoMap.put("rows", rowList);
        //分级管理
        Map fenjiMap = new HashMap();
        List<Map> ferowList = new ArrayList<>();
        Map feitem1 = new HashMap();
        feitem1.put("controltype", 0);
        feitem1.put("name", "血压控制情况");
        List<Map> feDetailList = new ArrayList<>();
        Map fe1 = new HashMap();
        fe1.put("detailName", "常规管理");
        fe1.put("state", 1);
        Map fe2 = new HashMap();
        fe2.put("detailName", "强化管理");
        fe2.put("state", 0);
        feDetailList.add(fe1);
        feDetailList.add(fe2);
        feitem1.put("details", feDetailList);
        ferowList.add(feitem1);
        fenjiMap.put("rows", ferowList);

        result.put("疗效评估", liaoXiaoMap);
        result.put("糖尿病分级管理", fenjiMap);

        return result;
    }

    /**
     * 不良反应
     *
     * @param dis
     * @param name
     * @return
     */
    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);
        }
        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;
    }
    //获取mysql链接
    public Connection getConnect(){
        MysqlJdbc mysqlJdbc = new MysqlJdbc(user, password, url);
        Connection connect = mysqlJdbc.connect();
        return connect;
    }

    /**
     * 更新图谱
     * @param singleDisease
     * @return
     * 类型(1：症状，2：体征，3：化验，4：辅检，5：鉴别诊断，6：病史，7：诱因，8：病程，9：其他，91：确诊，92：拟诊，93：警惕)
     */
    @Override
    public RespDTO updateNeoDisease(NeoParamVO singleDisease) {
        RespDTO respDTO = RespDTO.onSuc(true);
        RespDTO respDTO1 = null;
        try {
        Connection connect = getConnect();
        Long disId = singleDisease.getId();
            //把数据库中的所有词读进map缓存
        Map<String, Map<String, String>> ciKu = this.allStandWord2Map(connect);
        respDTO1 = this.updateNeo(respDTO, disId,connect,ciKu);
        connect.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return respDTO1;
    }

    public RespDTO updateNeo(RespDTO respDTO,Long disId,Connection connection, Map<String, Map<String, String>> ciKu){
        //先删除
        this.neo4jDelete(disId,connection);
        String disName = this.getDisName(disId,connection);
        if(StringUtils.isNotEmpty(disName)){
            diseaseRepository.mergeDis(disName,disId,0);
        }else {
            respDTO = RespDTO.onError("在数据库中没有找到这个疾病！！");
        }

        //获取每个诊断依据的全部数据
        List<Map<String, String>> allData = this.getAllData(disId,connection);
        //获取拟诊，确诊，警惕组合
        Map<String, List<String>> allNiQueZhenCollection = this.getAllNiQueZhenCollection(disId,connection);
        this.saveNiQue2Neo(allData,allNiQueZhenCollection,disName,disId);
        this.saveData2Neo4j(allData,disId,disName,ciKu);
        return respDTO;
    }

    /**
     * 把一个完整的诊断依据封装到list中，list中存的是map,一行一个map
     * @param disId
     * @return
     */
    public List<Map<String,String>> getAllData(Long disId,Connection connection){
        List<Map<String,String>> contentList = new ArrayList<>();
        Statement st = null;
        ResultSet rs = null;
        try {
            String type, code ,standard,relation,unique_name,result,formula,name;
            String sql = "SELECT diagnose_id,dis_name,`type`,`code`,standard,relation,unique_name,result,formula FROM `kl_diagnose_detail` where diagnose_id = "+disId+"  and is_deleted = 'N'";
            st = connection.createStatement();
            rs = st.executeQuery(sql);
            while (rs.next()){
                Map<String,String> content = new HashMap<>();
                type = rs.getString(3);
                code = rs.getString("code");
                standard = rs.getString("standard");
                relation = rs.getString("relation");
                unique_name = rs.getString("unique_name");
                result = rs.getString("result");
                formula = rs.getString("formula");
                name = Type.getName(Integer.parseInt(type));
                content.put("type",type);
                content.put("typeName",name);
                content.put("code",code);
                content.put("standard",standard);
                content.put("relation",relation);
                content.put("unique_name",unique_name);
                content.put("result",result);
                content.put("formula",formula);
                contentList.add(content);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return contentList;
    }

    /**
     * 获取一个诊断依据的确诊，拟诊，警惕集合
     * @param disId
     * @return
     */
    public Map<String,List<String>> getAllNiQueZhenCollection(Long disId,Connection connection)  {
        Map<String,List<String>> queNiMap = new HashMap<>();
        Statement st = null;
        ResultSet rs = null;
        List<String> queList = new ArrayList<>();
        List<String> niList = new ArrayList<>();
        List<String> highList = new ArrayList<>();
        try {
            String type, formula,  label,name;
            String sql = "SELECT type,formula FROM `kl_diagnose_detail` where diagnose_id = "+disId+" and type in (91,92,93)";
            st = connection.createStatement();
            rs = st.executeQuery(sql);
            while (rs.next()) {
                type = rs.getString(1);
                formula = rs.getString(2);
                name = Type.getName(Integer.parseInt(type));
                if ("拟诊".equals(name)) {
                    niList.add(formula);
                } else if ("确诊".equals(name)) {
                    queList.add(formula);
                } else if ("警惕".equals(name)) {
                    highList.add(formula);
                }
            }
            List<String> newQueList = new ArrayList<>();
            if(queList.size()>0){
                for (String que:queList) {
                    if(que.contains("拟诊")){
                        for (String ni:niList
                             ) {
                            newQueList.add(que.replaceAll("拟诊",ni));
                        }
                    }else {
                        newQueList.add(que);
                    }
                }
            }
            queNiMap.put("拟诊",niList);
            queNiMap.put("确诊",newQueList);
            queNiMap.put("警惕",highList);
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return queNiMap;
    }

    /**
     * 加载所有词库
     * @return
     */
    public  Map<String,Map<String,String>> allStandWord2Map(Connection connection){
        Map<String,Map<String,String>> ciKu = new HashMap<>();
        Statement st = null;
        ResultSet rs = null;
        try {
            String tongName, type,  isConcept,stand;
            String sql = "SELECT name, type_id,is_concept,IF(is_concept=1,a.name,(select lib_name from kl_concept b where b.id = a.concept_id) ) lib_name \n" +
                    "from kl_library_info a where  a.is_deleted = 'N'\n" +
                    "and type_id in (1,5,12,13,14,16,17,18,35,70)";
            st = connection.createStatement();
            rs = st.executeQuery(sql);
            Map<String,String> detail =null;
            while (rs.next()) {
                tongName = rs.getString(1);
                type = rs.getString(2);
                isConcept = rs.getString(3);
                stand = rs.getString(4);
                detail = new HashMap<>();
                detail.put("isConcept",isConcept);
                detail.put("stand",stand);
                ciKu.put(tongName+","+type,detail);
            }
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return ciKu;
        }
    }

    /**
     * 获取疾病名
     * @param disId
     * @return
     */
    public String getDisName(Long disId,Connection connection){
        Statement st = null;
        ResultSet rs = null;
        String name="";
        try {
            String sql = "SELECT dis_name FROM `kl_diagnose_detail` where diagnose_id = "+disId+" and is_deleted = 'N'";
            st = connection.createStatement();
            rs = st.executeQuery(sql);
            while (rs.next()) {
                name = rs.getString(1);
            }
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return name;
        }
    }
    /**
     * 把确诊，拟诊，警惕存入图谱
     */
    public void saveNiQue2Neo(List<Map<String, String>> allData,Map<String, List<String>> allNiQueZhenCollection,String disName,Long disId){
        List<String> stringList =null;
        String[] types = {"确诊","拟诊","警惕"};
        Integer path = 1;
        String[] nisplits;
        for (String type:types) {
            if("确诊".equals(type)){
                stringList = allNiQueZhenCollection.get(type);
                if(stringList != null){
                    for(int i =0;i<stringList.size();i++){
                        nisplits = stringList.get(i).split("\\+");
                        path = nisplits.length;
                        diseaseRepository.mergeCondition(disName+"-"+type+"组块"+(i+1),path);
                        diseaseRepository.mergeQueNiHigh(disName+"-"+type+"组块"+(i+1),disId);
                        this.splitConditionContent(nisplits,disName,disName+"-"+type+"组块"+(i+1),allData);
                    }
                }
            }else if("拟诊".equals(type)){
                stringList = allNiQueZhenCollection.get(type);
                if(stringList != null){
                    for(int i =0;i<stringList.size();i++){
                        nisplits = stringList.get(i).split("\\+");
                        path = nisplits.length;
                        diseaseRepository.mergeCondition(disName+"-"+type+"组块"+(i+1),path);
                        diseaseRepository.mergeNiHigh(disName+"-"+type+"组块"+(i+1),disId);
                        this.splitConditionContent(nisplits,disName,disName+"-"+type+"组块"+(i+1),allData);
                    }
                }
            }else if("警惕".equals(type)){
                stringList = allNiQueZhenCollection.get(type);
                if(stringList != null){
                    for(int i =0;i<stringList.size();i++){
                        nisplits = stringList.get(i).split("\\+");
                        path = nisplits.length;
                        diseaseRepository.mergeCondition(disName+"-"+type+"组块"+(i+1),path);
                        diseaseRepository.mergeHigh(disName+"-"+type+"组块"+(i+1),disId);
                        this.splitConditionContent(nisplits,disName,disName+"-"+type+"组块"+(i+1),allData);
                    }
                }
            }
        }
    }

    /**
     * 处理任几
     * @param nisplits
     * @param disName
     * @param startNode
     * @param allData
     */
    public void splitConditionContent(String[] nisplits,String disName,String startNode,List<Map<String, String>> allData){
        Integer path = 1;
        String rel = "";
        for (String ni:nisplits) {

            if(ni.contains("/")){
                if(ni.contains("任一")){
                    path = 1;
                    rel = "任一";
                }else if(ni.contains("任二")){
                    path = 2;
                    rel = "任二";
                }else if(ni.contains("任三")){
                    path = 3;
                    rel = "任三";
                }else if(ni.contains("任四")){
                    path = 4;
                    rel = "任四";
                }else if(ni.contains("任五")){
                    path = 5;
                    rel = "任五";
                }else if(ni.contains("任六")){
                    path = 6;
                    rel = "任六";
                }else if(ni.contains("任七")){
                    path = 7;
                    rel = "任七";
                }else if(ni.contains("任八")){
                    path = 8;
                    rel = "任八";
                }else if(ni.contains("任九")){
                    path = 9;
                    rel = "任九";
                }else if(ni.contains("任十")){
                    path = 10;
                    rel = "任十";
                }else {
                    path = 1;
                    rel = "任一";
                }
                diseaseRepository.mergeRenCondition(disName+ni,path,rel);
                diseaseRepository.mergeRenCondition(disName+ni,startNode);
                //获取这个任几集合的数字集合
                List<String> numList = this.getNumList(ni);
                if(numList != null && numList.size()>0){
                    for (String num:numList
                            ) {
                        this.processDetailNum(disName,num,disName+ni,allData);
                    }
                }
            }else {
                this.processDetailNum(disName,ni,startNode,allData);
            }
        }
    }

    /**
     * 获取任几集合的code列表
     * @return
     */
    public List<String> getNumList(String renCondition){
        List<String> numList = new ArrayList<>();
        String[] numSplits = renCondition.split("/");
        if(numSplits.length>0){
            for (int i=0;i<numSplits.length;i++){
                if(i == 0){
                    numList.add(numSplits[i].replaceAll("\\(",""));
                }else if(i == numSplits.length-1){
                    String numSplit = numSplits[i];
                    int i1 = numSplit.indexOf(")");
                    System.out.println(numSplit+"\t"+i1);
                    if(i1 >= 0){
                        numList.add(numSplits[i].substring(0,numSplits[i].indexOf(")")));
                    }else {
                        numList.add(numSplit);
                    }

                }else {
                    numList.add(numSplits[i]);
                }
            }
        }
        return numList;
    }
    public void processDetailNum(String disName,String num,String renCondition,List<Map<String, String>> allData){
        String[] types = {"化验","辅检","排除条件"};
        for (Map<String, String> row:allData) {
            String code = row.get("code");//编码
            String type = row.get("type");//类型
            String typeName = row.get("typeName");//类型对应的中文名
            String relation = row.get("relation");//关联词
            String result = row.get("result");//结果
            if(num.equals(code)){
                if(Arrays.asList(types).indexOf(typeName) <0){
                    diseaseRepository.mergeNUMCondition(disName+code);
                    diseaseRepository.mergeNUMCondition(disName+code,renCondition);
                }else if("化验".equals(typeName) && !"".equals(result)){
                    diseaseRepository.mergeNUMCondition(disName+code);
                    diseaseRepository.mergeNUMCondition(disName+code,renCondition);
                }else if("辅检".equals(typeName) && !"".equals(relation)){
                    diseaseRepository.mergeNUMCondition(disName+code);
                    diseaseRepository.mergeNUMCondition(disName+code,renCondition);
                }
            }
        }
    }

    /**
     * 保存完整的诊断依据入知识图谱
     * @param allData
     * @param disId
     * @param disName
     */
    public void saveData2Neo4j(List<Map<String, String>> allData,Long disId,String disName,Map<String, Map<String, String>> ciKu){
        for (Map<String,String> row:allData) {
            String code = row.get("code");//编码
            String type = row.get("type");//类型
            String typeName = row.get("typeName");//类型对应的中文名
            String standard = row.get("standard");//标准词
            String relation = row.get("relation");//关联词
            String unique_name = row.get("unique_name");//公表项
            String result = row.get("result");//结果
            if(StringUtils.isNotEmpty(type)){
                String[] split =null;
                String[] lisResultSplit =null;
                String[] pacsResultSplit =null;
                String standWord = null;String lisResult = null,pacsResult=null;
                if(!"3".equals(type) && !"4".equals(type) && !"5".equals(type)){
                    //添加词语之前，要找标准词
                    //添加standard
                    switch (type){
                        case "1": //症状
                            standWord = searchStandWord(standard, type, ciKu);
                            if(StringUtils.isNotEmpty(standWord)){
                                diseaseRepository.mergeStandardSymptom(standWord);
                                diseaseRepository.mergeRelationStandard(disId,standWord);
                                diseaseRepository.mergeRelationStandardshuyu(disName+code,standWord);
                            }
                            if(StringUtils.isNotEmpty(relation)){
                                split = relation.split("、");
                                if(split!=null && split.length>0){
                                    for (String ci:split) {
                                        if(StringUtils.isNotEmpty(ci)){
                                            //找标准词
                                            standWord = searchStandWord(ci,type,ciKu);
                                            if(StringUtils.isNotEmpty(standWord)){
                                                diseaseRepository.mergeStandardSymptom(standWord);
                                                diseaseRepository.mergeRelationStandardshuyu(disName+code,standWord);
                                            }
                                        }
                                    }
                                }
                            }
                            break;
                        case "2"://体征结果
                            standWord = searchStandWord(standard,type,ciKu);
                            if(StringUtils.isNotEmpty(standWord)){
                                diseaseRepository.mergeStandardVital(standWord);
                                diseaseRepository.mergeRelationStandardVital(disId,standWord);
                                diseaseRepository.mergeRelationStandardVitalshuyu(disName+code,standWord);
                            }
                            if(StringUtils.isNotEmpty(relation)){
                                split = relation.split("、");
                                if(split!=null && split.length>0){
                                    for (String ci:split) {
                                        if(StringUtils.isNotEmpty(ci)){
                                            //找标准词
                                            standWord = searchStandWord(ci,type,ciKu);
                                            if(StringUtils.isNotEmpty(standWord)){
                                                diseaseRepository.mergeStandardVital(standWord);
                                                diseaseRepository.mergeRelationStandardVitalshuyu(disName+code,standWord);
                                            }
                                        }
                                    }
                                }
                            }
                            break;
                        case "6"://病史
                            standWord = searchStandWord(standard,type,ciKu);
                            if(StringUtils.isNotEmpty(standWord)){
                                diseaseRepository.mergeStandardHistory(standWord);
                                diseaseRepository.mergeRelationStandardHistory(disId,standWord);
                                diseaseRepository.mergeRelationStandardHistoryshuyu(disName+code,standWord);
                            }
                            if(StringUtils.isNotEmpty(relation)){
                                split = relation.split("、");
                                if(split!=null && split.length>0){
                                    for (String ci:split) {
                                        if(StringUtils.isNotEmpty(ci)){
                                            //找标准词
                                            standWord = searchStandWord(ci,type,ciKu);
                                            if(StringUtils.isNotEmpty(standWord)){
                                                diseaseRepository.mergeStandardHistory(standWord);
                                                diseaseRepository.mergeRelationStandardHistoryshuyu(disName+code,standWord);
                                            }
                                        }
                                    }
                                }
                            }
                            break;
                        case "7"://诱因
                            standWord = searchStandWord(standard,type,ciKu);
                            if(StringUtils.isNotEmpty(standWord)){
                                diseaseRepository.mergeStandardCause(standWord);
                                diseaseRepository.mergeRelationStandardCause(disId,standWord);
                                diseaseRepository.mergeRelationStandardCauseshuyu(disName+code,standWord);
                            }
                            if(StringUtils.isNotEmpty(relation)){
                                split = relation.split("、");
                                if(split!=null && split.length>0){
                                    for (String ci:split) {
                                        if(StringUtils.isNotEmpty(ci)){
                                            //找标准词
                                            standWord = searchStandWord(ci,type,ciKu);
                                            if(StringUtils.isNotEmpty(standWord)){
                                                diseaseRepository.mergeStandardCause(standWord);
                                                diseaseRepository.mergeRelationStandardCauseshuyu(disName+code,standWord);
                                            }
                                        }
                                    }
                                }
                            }
                            break;
                        case "8"://病程
                            standWord = searchStandWord(standard,type,ciKu);
                            if(StringUtils.isNotEmpty(standWord)){
                                diseaseRepository.mergeStandardPrognosis(standWord);
                                diseaseRepository.mergeRelationStandardPrognosis(disId,standWord);
                                diseaseRepository.mergeRelationStandardPrognosisshuyu(disName+code,standWord);
                            }
                            if(StringUtils.isNotEmpty(relation)){
                                split = relation.split("、");
                                if(split!=null && split.length>0){
                                    for (String ci:split) {
                                        if(StringUtils.isNotEmpty(ci)){
                                            //找标准词
                                            standWord = searchStandWord(ci,type,ciKu);
                                            if(StringUtils.isNotEmpty(standWord)){
                                                diseaseRepository.mergeStandardPrognosis(standWord);
                                                diseaseRepository.mergeRelationStandardPrognosisshuyu(disName+code,standWord);
                                            }
                                        }
                                    }
                                }
                            }
                            break;
                        case "9"://其他
                            standWord = searchStandWord(standard,type,ciKu);
                            if(StringUtils.isNotEmpty(standWord)){
                                diseaseRepository.mergeStandardOther(standard);
                                diseaseRepository.mergeRelationStandardOther(disId,standard);
                                diseaseRepository.mergeRelationStandardOthershuyu(disName+code,standard);
                            }
                            if(StringUtils.isNotEmpty(relation)){
                                split = relation.split("、");
                                if(split!=null && split.length>0){
                                    for (String ci:split) {
                                        if(StringUtils.isNotEmpty(ci)){
                                            //找标准词
                                            standWord = searchStandWord(ci,type,ciKu);
                                            if(StringUtils.isNotEmpty(standWord)){
                                                diseaseRepository.mergeStandardOther(standWord);
                                                diseaseRepository.mergeRelationStandardOthershuyu(disName+code,standWord);
                                            }

                                        }
                                    }
                                }
                            }
                            break;
                    }
                }else if("5".equals(type)){   //鉴别诊断
                    //找标准词
                    diseaseRepository.mergeDifferentDis(standard);
                    diseaseRepository.mergeRelationDifferentDis(disId,standard);
                    if(StringUtils.isNotEmpty(relation)){
                        split = relation.split("、");
                        if(split !=null && split.length>0){
                            for (String dis:split) {
                                if(StringUtils.isNotEmpty(dis)){
                                    //找标准词
                                    diseaseRepository.mergeDifferentDis(dis);
                                    diseaseRepository.mergeRelationDifferentDis(disId,dis);
                                }
                            }
                        }
                    }
                } else if("3".equals(type)){ //处理化验
                    String lis = "";
                    if(StringUtils.isNotEmpty(unique_name)){
                        //创建化验公表项
                        diseaseRepository.mergePublicLIS_1(unique_name);
                        //疾病和化验公表项创建推荐关系
                        diseaseRepository.mergeRelationLIS_1(disId,unique_name);
                        lis =standard;
                    //创建大项名
                    diseaseRepository.mergePublicLIS(lis);
                    //疾病推荐化验大项名
                    diseaseRepository.mergeRelationLIS(disId,lis);
                    //处理化验结果
                    if(StringUtils.isNotEmpty(result) && StringUtils.isNotEmpty(unique_name)){
                        lisResultSplit = result.split("、");
                        if(lisResultSplit != null && lisResultSplit.length>0){
                            for (String lisRs:lisResultSplit) {
                                if(StringUtils.isNotEmpty(lisRs)){
                                    //创建化验结果节点
                                    diseaseRepository.mergeLISRESULT(lisRs);
                                    //大项和化验结果创建关系
                                    diseaseRepository.mergeRelationPublicLIS(lis,lisRs);
                                    //化验结果和对应的codeCondition创建关系
                                    diseaseRepository.mergeRelationCondiLisRes(disName+code,lisRs);
                                    //化验大项和化验公表项创建关系
//                                    diseaseRepository.mergeRelationPublicAndLIS(lis,unique_name);
                                }
                            }
                        }
                    }
                    }
                }else if("4".equals(type)){ //辅检
                    //查找辅检的标准词
                    standWord = searchStandWord(standard,type,ciKu);
                    if(StringUtils.isNotEmpty(standWord)){
                        //创建辅检标准词的节点
                        diseaseRepository.mergePacs(standWord);
                        //疾病推荐辅检
                        diseaseRepository.mergeRelationDis2Pacs(disId,standWord);
                    }
                    if(StringUtils.isNotEmpty(relation)){
                        pacsResultSplit = relation.split("、");
                        if(pacsResultSplit != null && pacsResultSplit.length>0){
                            for (String pacs:pacsResultSplit) {
                                //查找辅检结果的标准词
                                if(StringUtils.isNotEmpty(pacs)){
                                   pacsResult = searchStandWord(pacs,"resultPacs",ciKu);
                                   if(StringUtils.isNotEmpty(pacsResult)){
                                       diseaseRepository.mergePacsResult(pacsResult);
                                       //创建辅检和辅检结果关系
                                       diseaseRepository.mergeRelationPacsResult(standWord,pacsResult);
                                       //创建辅检结果和对应的pacsCondition的关系
                                       diseaseRepository.mergeRelationCondiPacsRes(disName+code,pacsResult);
                                   }

                                }
                            }
                        }
                    }
                }
            }
        }

    }

    /**
     * 查找标准词
     * @param type
     * @return
     */
    public String searchStandWord(String word,String type,Map<String, Map<String, String>> ciKu){
        String stand = null;
        Map<String, String> detaiMap =null;
        String label = Ciku.getLabel(type);
        String[] labelSplits = label.split(",");
        if(labelSplits.length == 1){
            detaiMap = ciKu.get(word + "," + label);
            if(detaiMap != null){
                stand = detaiMap.get("stand");
            }
        }else if(labelSplits.length == 2){
            detaiMap = ciKu.get(word + "," + labelSplits[0]);
            if(detaiMap == null){
                detaiMap = ciKu.get(word + "," + labelSplits[1]);
            }
            if(detaiMap != null){
                stand = detaiMap.get("stand");
            }
        }
        return stand;
    }
    /**
     * 在图谱中删除诊断依据
     * @param singleDisease
     * @return
     */
    @Override
    public RespDTO deleteNeoDisease(NeoParamVO singleDisease) {
        Long disId = singleDisease.getId();
        RespDTO respDTO = null;
        try {
        Connection connect = getConnect();
        if(disId != null){
            this.neo4jDelete(disId,connect);
            connect.close();
            respDTO = RespDTO.onSuc(true);
        }else {
            respDTO = RespDTO.onError(" 删除失败！！！");
        }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return respDTO;
    }
    //删除
    public void neo4jDelete(Long disId,Connection connection) {
        if (disId != null) {
            diseaseRepository.deleteRelation1(disId);
            diseaseRepository.deleteRelation2(disId);
            diseaseRepository.deleteRelation3(disId);
            diseaseRepository.deleteRelation4(disId);
//            diseaseRepository.deleteRelation5(disId);
//            diseaseRepository.deleteRelation6(disId);
//            diseaseRepository.deleteRelation7(disId);
//            diseaseRepository.deleteRelation8(disId);
//            diseaseRepository.deleteRelation9(disId);
            //删除disId
            diseaseRepository.deleteRelation11(disId);
            List<String> allCode = this.getAllCode(disId,connection);
            if(allCode.size()>0){
                for (String conName:allCode) {
                    diseaseRepository.deleteRelation10(conName);
                }
            }

        }
    }

    /**
     * 批量插入
     *
     * @return
     */
    @Override
    public RespDTO<Boolean> batchInsertDis() {
        //获取mysql链接
        Connection connect = getConnect();
        //把数据库中的所有词读进map缓存
        Map<String, Map<String, String>> ciKu = this.allStandWord2Map(connect);
        RespDTO<Boolean> respDTO = new RespDTO<>();
        try {
            List<Long> disList = getDisList(connect);
            if(disList != null && disList.size()>0){
                for (Long disId:disList) {
                   respDTO = this.updateNeo(respDTO, disId, connect, ciKu);
                   this.updateDate(connect,disId);

                }
            }
            connect.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return respDTO;
    }

    @Override
    public List<BiDetail> neoBi() {
        List<BiDetail> biDetailList = new ArrayList<>();
        Long disCount = biRepository.diagnoseCount();
        Long childCount = biRepository.childCount();
        Long scaleCount = biRepository.scaleCount();
        BiDetail dis = new BiDetail();
        dis.setModuleName("疾病");
        dis.setItemName("图谱推送的疾病");
        dis.setCount(disCount);
        BiDetail child = new BiDetail();
        child.setModuleName("疾病");
        child.setItemName("图谱推送的儿科疾病");
        child.setCount(childCount);
        BiDetail scale = new BiDetail();
        scale.setModuleName("量表");
        scale.setItemName("量表总数");
        scale.setCount(scaleCount);
        biDetailList.add(dis);
        biDetailList.add(child);
        biDetailList.add(scale);
        return biDetailList;
    }

    public void updateDate(Connection connection,Long disId) throws SQLException {
        String sql = "UPDATE `kl_diagnose` set neo_update='1970-01-01 12:00:00' where id=?";
        PreparedStatement preparedStatement =null;
        try {
            connection.setAutoCommit(false);
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setLong(1,disId);
            int i = preparedStatement.executeUpdate();
            connection.commit();
        } catch (SQLException e) {
            connection.rollback();
            e.printStackTrace();
        }finally {
            preparedStatement.close();
        }
    }
    public List<Long> getDisList(Connection connection){
        List<Long> disIds = new ArrayList<>();
        Statement st = null;
        ResultSet rs = null;
        try {
            Long id ;
            String sql = "SELECT id FROM `kl_diagnose` where has_question=0 and is_deleted='N'";
            st = connection.createStatement();
            rs = st.executeQuery(sql);
            while (rs.next()){
                disIds.add(rs.getLong(1));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return disIds;
    }

    /**
     * 获取一个诊断依据的全部code
     * @param disId
     * @return
     */
    public List<String> getAllCode(Long disId,Connection connection){
        List<String> codeList = new ArrayList<>();
        Statement st = null;
        ResultSet rs = null;
        try {
            String code ,name;
            String sql = "SELECT dis_name,code FROM `kl_diagnose_detail` where diagnose_id="+disId+" and code != \"\"";
            st = connection.createStatement();
            rs = st.executeQuery(sql);
            while (rs.next()){
                name = rs.getString("dis_name");
                code = rs.getString("code");
                codeList.add(name+code);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return codeList;
    }

    @Override
    public List<Map<String, Object>> getRecommendItem(QueryVo queryVo) {
        List<Map<String, Object>> list = relationRepository.getRecommendItem(queryVo.getDiseaselist());
        return list;
    }

    @Override
    public Map<String, List<Map<String, Object>>> getScale(QueryVo queryVo) {
        Map<String, List<Map<String, Object>>> map = new HashMap<>();

        for (String name : queryVo.getScalelist()) {
            List<Map<String, Object>> list = scaleRepository.getScale(name);
            map.put(name, list);
        }

        return map;
    }



    public Pageable getPageable(PageVo pageVo) {
        if (pageVo.getSize() > 0) {
            if (pageVo.getSort_key() != null && pageVo.getSort_direct() != null) {
                if (pageVo.getSort_direct().toLowerCase().equals("asc")) {
                    pageable = PageRequest.of(pageVo.getCurrent(), pageVo.getSize(),
                            Sort.Direction.ASC, pageVo.getSort_key().trim());
                } else if (pageVo.getSort_direct().toLowerCase().equals("desc")) {
                    pageable = PageRequest.of(pageVo.getCurrent(), pageVo.getSize(),
                            Sort.Direction.DESC, pageVo.getSort_key().trim());
                } else {
                    pageable = PageRequest.of(pageVo.getCurrent(), pageVo.getSize());
                }
            } else {
                pageable = PageRequest.of(pageVo.getCurrent(), pageVo.getSize());
            }
        } else {
            pageable = PageRequest.of(0, 100);
        }
        return pageable;
    }

    public List<Map<String, Object>> extractPath(Iterable<Map<String, Object>> path) {
        Map<String, Object> item = new HashMap<>();
        List<Map<String, Object>> pathlist = new ArrayList<>();
        Map<String, Object> pathmap;

        Iterator<Map<String, Object>> iterator = path.iterator();
        while (iterator.hasNext()) {
            item = iterator.next();
            pathmap = new HashMap<>();
            if (item.get("P") != null) {
                Path p = (Path) item.get("P");
                pathmap = parsePath(p);
            }
            pathlist.add(pathmap);
        }

        return pathlist;
    }

    public Map<String, Object> parsePath(Path p) {
        Map<String, Object> path = new HashMap<>();
        path.put("start", new HashMap<>());
        path.put("end", new HashMap<>());
        Map<String, String> s = (Map) path.get("start");
        Map<String, String> e = (Map) path.get("end");
        Node start = p.start();
        Node end = p.end();
        s.put("label", start.labels().iterator().next());
        e.put("label", end.labels().iterator().next());
        String relation = p.relationships().iterator().next().type();
        path.put("relation", new HashMap<>());
        ((Map) path.get("relation")).put("type", relation);

        for (String prop : start.keys()) {
            s.put(prop, start.get(prop).toString().replaceAll("\"", ""));
        }

        for (String prop : end.keys()) {
            e.put(prop, end.get(prop).toString().replaceAll("\"", ""));
        }

        return path;
    }

    /**
     * 根据出现次数排序,去重
     *
     * @param list
     * @return
     */
    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;
    }

}
