package org.diagbot.graphWeb.work;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.diagbot.common.work.FeatureRate;
import org.diagbot.common.javabean.Filnlly;
import org.diagbot.common.work.ResponseData;
import org.diagbot.common.work.SearchData;
import org.diagbot.graph.jdbc.DriverManager;
import org.diagbot.graph.jdbc.Neo4jAPI;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import org.diagbot.graphWeb.util.MapValueComparator;

public class GraphCalculate {
    /**
     * 返回诊断和治疗
     * @param request
     * @param searchData
     * @return
     * @throws Exception
     */
    public ResponseData calculate(HttpServletRequest request, SearchData searchData) throws Exception {
        ResponseData responseData = new ResponseData();
        ParamsDataProxy paramsDataProxy = new ParamsDataProxy();
        paramsDataProxy.createSearchData(request,searchData);
        List<String> inputList = new ArrayList<>();
        Map<String, Map<String, String>> inputs = searchData.getInputs();
        Set<String> ss = inputs.keySet();
        inputList.addAll(ss);
        Neo4jAPI neo4jAPI = new Neo4jAPI(DriverManager.newDrive());
        //处理化验数据
      /*  if(searchData.getLisArr().size()!=0){
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(searchData.getLisArr()));
            List<String> lisResult = neo4jAPI.AnalysisLISResult(jsonArray);
            inputList.addAll(lisResult);
        }*/
        //计算提出的词,是否在图谱中找到
       List<String> grapWords = neo4jAPI.getGrapWords((String[]) inputList.toArray(new String[inputList.size()]));
        List<FeatureRate> graphWordfeatureRates = new ArrayList<>();
        if(grapWords.size()>0){
            for (String word: grapWords ) {
                FeatureRate featureRate = new FeatureRate();
                featureRate.setFeatureName(word.replaceAll("\"",""));
                featureRate.setExtraProperty("");
                featureRate.setDesc("");
                featureRate.setRate("");
                graphWordfeatureRates.add(featureRate);
            }
        }
        //计算诊断
        Map<String, String> condition = neo4jAPI.getCondition((String[]) inputList.toArray(new String[inputList.size()]));
        List<FeatureRate> featureRates = new ArrayList<>();
        for (Map.Entry<String,String> d:condition.entrySet()
                ) {
            FeatureRate featureRate = new FeatureRate();
            featureRate.setFeatureName(d.getKey());
            featureRate.setExtraProperty("");
            featureRate.setDesc(d.getValue());
            featureRate.setRate("neo4j");
            featureRates.add(featureRate);
        }

        String webDiag = searchData.getDiag();
        //走治疗
        if(webDiag.trim()!=null && Arrays.asList(searchData.getFeatureTypes()).contains("8")){
            //走平常诊断治疗
            Map<String, Filnlly> mulDiseaseTreat = neo4jAPI.getMulDiseaseTreat_2(webDiag, String.join(",", inputList));
            responseData.setTreat(mulDiseaseTreat);
        }
        if("0".equals(searchData.getDiseaseType())){    //走复诊
            if(Arrays.asList(searchData.getFeatureTypes()).contains("22")){ //取指标

            }
        }
        responseData.setGraphWords(graphWordfeatureRates);
        responseData.setDis(featureRates);
        responseData.setInputs(searchData.getInputs());
        return responseData;
    }

    /**
     * 返回LIS,PACS
     * @param searchData
     */
    public ResponseData getLisPacs(HttpServletRequest request,SearchData searchData) throws Exception {
        ResponseData responseData = new ResponseData();
        Neo4jAPI neo4jAPI = new Neo4jAPI(DriverManager.newDrive());
        String webDiag = searchData.getDiag();
        List<String> webDiagList = Arrays.asList(webDiag.split(",|，|、"));
        List<FeatureRate> bigdataDiagFeature = searchData.getPushDiags();
        List<String> bigdataDiagList =new LinkedList<>();
        if(bigdataDiagFeature.size()>0){
            for (FeatureRate fe:bigdataDiagFeature) {
                if("neo4j".equals(fe.getRate())){
                    bigdataDiagList.add(fe.getFeatureName());
                }else {
                    bigdataDiagList.add(fe.getFeatureName());
                }
            }
        }
        for (String web: webDiagList ) {
                for (int i=0;i<bigdataDiagList.size();i++ ) {
                    if(bigdataDiagList.get(i).equals(web)){
                        bigdataDiagList.remove(bigdataDiagList.get(i));
                    }
                }
        }

        Map<String, Set<String>> weblisPacs1 =null;
        Map<String, Set<String>> biglisPacs1 =null;
        if(webDiagList !=null && webDiagList.size()>0){
            weblisPacs1=neo4jAPI.getLisPacs(webDiagList);//界面诊断推出的LIS,PACS
        }
        if(bigdataDiagList !=null && bigdataDiagList.size()>0){
            biglisPacs1=neo4jAPI.getLisPacs(bigdataDiagList);//大数据推得诊断
        }
        Set<String> lis =null;
        Set<String> pacs =null;
        //如果界面有诊断
        if(weblisPacs1 !=null && weblisPacs1.values().size()>0){
            lis = weblisPacs1.get("LIS");
            pacs = weblisPacs1.get("PACS");
            if(biglisPacs1 !=null && biglisPacs1.values().size()>0){
                Set<String> bl = biglisPacs1.get("LIS");
                Set<String>  bp= biglisPacs1.get("PACS");
                lis.addAll(bl);
                pacs.addAll(bp);
            }
        }else {
            lis = biglisPacs1.get("LIS");
            pacs = biglisPacs1.get("PACS");
        }
        ArrayList<FeatureRate> lisFeature = new ArrayList<>();
        ArrayList<FeatureRate> pacsFeature = new ArrayList<>();
        for (String l:lis) {
            FeatureRate featureRate = new FeatureRate();
            featureRate.setFeatureName(l);
            lisFeature.add(featureRate);
        }
        for (String p:pacs) {
            FeatureRate featureRate = new FeatureRate();
            featureRate.setFeatureName(p);
            pacsFeature.add(featureRate);
        }
        responseData.setLabs(lisFeature);
        responseData.setPacs(pacsFeature);
        return responseData;
    }


    /**
     * 对化验和检查的结果进行排序
     * @param set
     * @return List<FeatureRate>
     */
    public Set<String> processResult(Set<String> set) {
        Set<String> frlist = new LinkedHashSet<>();
        Map<String, String> sortval = new HashMap<>();
        Map<String, String> items = new HashMap<>();
        String name;

        try {
            if (set != null && set.size() > 0) {
                for (String item : set) {
                    if (sortval.get(item) == null) {
                        sortval.put(item, "1");
                    } else {
                        sortval.put(item, String.valueOf(Integer.parseInt(sortval.get(item)) + 1));
                    }
                }

                sortval = sortMapByValue(sortval);

                for (String key : sortval.keySet()) {
                    frlist.add(items.get(key));
                }
            }
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
        finally {
            return frlist;
        }
    }


    /**
     * 使用 Map按value进行排序
     * @param oriMap
     * @return
     */
    public static Map<String, String> sortMapByValue(Map<String, String> oriMap) {
        if (oriMap == null || oriMap.isEmpty()) {
            return null;
        }
        Map<String, String> sortedMap = new LinkedHashMap<String, String>();
        List<Map.Entry<String, String>> entryList = new ArrayList<Map.Entry<String, String>>(
                oriMap.entrySet());
        Collections.sort(entryList, new MapValueComparator());

        Iterator<Map.Entry<String, String>> iter = entryList.iterator();
        Map.Entry<String, String> tmpEntry = null;
        while (iter.hasNext()) {
            tmpEntry = iter.next();
            sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
        }
        return sortedMap;
    }
}
