package com.yihu.jw.es.util;

import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.expr.SQLQueryExpr;
import com.alibaba.druid.sql.parser.SQLExprParser;


import com.yihu.jw.es.es.ElasticFactory;
import com.yihu.jw.util.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.nlpcn.es4sql.domain.Select;
import org.nlpcn.es4sql.jdbc.ObjectResult;
import org.nlpcn.es4sql.jdbc.ObjectResultsExtractor;
import org.nlpcn.es4sql.parse.ElasticSqlExprParser;
import org.nlpcn.es4sql.parse.SqlParser;
import org.nlpcn.es4sql.query.AggregationQueryAction;
import org.nlpcn.es4sql.query.DefaultQueryAction;
import org.nlpcn.es4sql.query.SqlElasticSearchRequestBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by chenweida on 2017/7/17.
 * SELECT town,townName,sum(result1) result1 FROM wlyy_quota_test
 * where quotaCode='1'
 * group by town,townName ， date_histogram(field='quotaDate','interval'='week')
 */
@Component
public class ElasticsearchUtil {

    private Logger logger = LoggerFactory.getLogger(ElasticsearchUtil.class);

    private final String commonParams = "xmijk_quota";

    @Autowired
    private ElasticFactory elasticFactory;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Value("${es.type.Statistics}")
    private String esType;
    @Value("${es.index.Statistics}")
    private String esIndex;


    /**
     * 直接执行essql语句
     * @param sql
     * @return
     * @throws Exception
     */
    public ObjectResult excuteSql(String sql) throws Exception{
        SQLExprParser parser = new ElasticSqlExprParser(sql);
        SQLExpr expr = parser.expr();
        SQLQueryExpr queryExpr = (SQLQueryExpr) expr;

        Select select = null;
        select = new SqlParser().parseSelect(queryExpr);

        //通过抽象语法树，封装成自定义的Select，包含了select、from、where group、limit等
        AggregationQueryAction action = null;
        DefaultQueryAction queryAction = null;
        SqlElasticSearchRequestBuilder requestBuilder = null;
        if (select.isAgg) {
            //包含计算的的排序分组的
            action = new AggregationQueryAction(elasticFactory.getTransportClient(), select);
            requestBuilder = action.explain();
        } else {
            //封装成自己的Select对象
            queryAction = new DefaultQueryAction(elasticFactory.getTransportClient(), select);
            requestBuilder = queryAction.explain();
        }
        SearchResponse response = (SearchResponse) requestBuilder.get();
        Object queryResult = null;
        if (sql.toUpperCase().indexOf("GROUP") != -1 || sql.toUpperCase().indexOf("SUM") != -1 || select.isAgg) {
            queryResult = response.getAggregations();
        } else {
            queryResult = response.getHits();
        }
        ObjectResult temp = new ObjectResultsExtractor(true, true, true).extractResults(queryResult, true);
        return temp;
    }


    public List excute(String sql, Class clazz, String esType, String esIndex) {
        List saveModels = new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXX");
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            //解决 group by之后默认是200的问题
            if (sql.toLowerCase().contains("group by")) {
                sql = sql + " limit 0,2000";
            }

            SQLExprParser parser = new ElasticSqlExprParser(sql);
            SQLExpr expr = parser.expr();
            SQLQueryExpr queryExpr = (SQLQueryExpr) expr;

            Select select = null;
            select = new SqlParser().parseSelect(queryExpr);

            //通过抽象语法树，封装成自定义的Select，包含了select、from、where group、limit等
            AggregationQueryAction action = null;
            DefaultQueryAction queryAction = null;
            SqlElasticSearchRequestBuilder requestBuilder = null;
            if (select.isAgg) {
                //包含计算的的排序分组的
                action = new AggregationQueryAction(elasticFactory.getTransportClient(), select);
                requestBuilder = action.explain();
            } else {
                //封装成自己的Select对象
                queryAction = new DefaultQueryAction(elasticFactory.getTransportClient(), select);
                requestBuilder = queryAction.explain();
            }
            SearchResponse response = (SearchResponse) requestBuilder.get();
            Object queryResult = null;
            if (sql.toUpperCase().indexOf("GROUP") != -1 || sql.toUpperCase().indexOf("SUM") != -1 || select.isAgg) {
                queryResult = response.getAggregations();
            } else {
                queryResult = response.getHits();
            }
            ObjectResult temp = new ObjectResultsExtractor(true, true, true).extractResults(queryResult, true);
            List<String> heads = temp.getHeaders();
            temp.getLines().forEach(one -> {
                Object saveModel = null;
                try {

                    saveModel = clazz.newInstance();
                } catch (Exception e) {
                    logger.error(e.getMessage());
                }
                for (int i = 0; i < one.size(); i++) {
                    try {
                        String key = null;
                        Object value = one.get(i);
                        if (heads.get(i).startsWith("_")) {
                            if(heads.get(i).contains("_id")){
                                clazz.getMethod("setId", String.class).invoke(saveModel, value);
                            }
                            continue;
                        }
                        key = "set" + UpFirstStr(heads.get(i));
                        if (heads.get(i).contains("quotaDate") || heads.get(i).contains("createTime") || heads.get(i).contains("date_histogram") || heads.get(i).contains("czrq")) {
                            if (heads.get(i).contains("date_histogram")) {
                                key = "setQuotaDate";
                            }
                            if(heads.get(i).contains("czrq") && one.get(i) == null ){
                                continue;
                            }
                            try {
                                //yyyy-MM-dd'T'HH:mm:ssXX
                                value = dateFormat.parse(String.valueOf(one.get(i)));
                            } catch (Exception e) {
                                //yyyy-MM-dd HH:mm:ss
                                try {
                                    value = dateFormat1.parse(String.valueOf(one.get(i)));
                                }catch (Exception e1){
                                    Timestamp ts = new Timestamp(Long.parseLong(String.valueOf(one.get(i))));
                                    try {
                                        Date date = new Date();
                                        date = ts;
                                        value =date;
                                    
                                    } catch (Exception e2) {
                                        value = String.valueOf(one.get(i));
                                    }
                                }
                                
                            }
//                            value = DateUtil.strToDate(String.valueOf(value).replace("T00:00:00+0800", " 00:00:00"), "yyyy-MM-dd HH:mm:ss");
                        }

                        if (value instanceof String) {
                            clazz.getMethod(key, String.class).invoke(saveModel, value);
                        } else if (value instanceof Integer) {
                            Field field = clazz.getDeclaredField(heads.get(i));
                            if(field.getGenericType().getTypeName().equals("java.lang.Long")) {
                                clazz.getMethod(key, Long.class).invoke(saveModel, Long.valueOf(value + ""));
                            } else {
                                clazz.getMethod(key, Integer.class).invoke(saveModel, value);
                            }
                        } else if (value instanceof Double) {
                            clazz.getMethod(key, Double.class).invoke(saveModel, value);
                        } else if (value instanceof java.util.Date) {
                            clazz.getMethod(key, java.util.Date.class).invoke(saveModel, value);
                        } else if (value instanceof java.util.List) {
                            Field field = clazz.getDeclaredField(heads.get(i));
                            if(field.getGenericType().getTypeName().equals("java.util.Set<java.lang.String>")){
                                Set<String> set = new HashSet<>();
                                for(Object s : (ArrayList) value){
                                    set.add(s + "");
                                }
                                clazz.getMethod(key, java.util.Set.class).invoke(saveModel, set);
                            }else {
                                clazz.getMethod(key, java.util.List.class).invoke(saveModel, value);
                            }
                        }
                    } catch (Exception e) {
                        logger.warn(e.getMessage());
                    }
                }
                saveModels.add(saveModel);
            });
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return saveModels;
    }

    public Long excuteForLong(String sql, String esType, String esIndex) {
        try {
            SQLExprParser parser = new ElasticSqlExprParser(sql);
            SQLExpr expr = parser.expr();
            SQLQueryExpr queryExpr = (SQLQueryExpr) expr;

            Select select = null;
            select = new SqlParser().parseSelect(queryExpr);

            //通过抽象语法树，封装成自定义的Select，包含了select、from、where group、limit等
            AggregationQueryAction action = null;
            DefaultQueryAction queryAction = null;
            SqlElasticSearchRequestBuilder requestBuilder = null;
            if (select.isAgg) {
                //包含计算的的排序分组的
                action = new AggregationQueryAction(elasticFactory.getTransportClient(), select);
                requestBuilder = action.explain();
            } else {
                //封装成自己的Select对象
                queryAction = new DefaultQueryAction(elasticFactory.getTransportClient(), select);
                requestBuilder = queryAction.explain();
            }
            SearchResponse response = (SearchResponse) requestBuilder.get();
            ObjectResult temp = new ObjectResultsExtractor(true, true, true).extractResults(response.getAggregations(), true);
            Long Longvalue = ((Double) temp.getLines().get(0).get(0)).longValue();
            return Longvalue;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return 0L;
    }

    /**
     * 首字母大写
     *
     * @param str
     * @return
     */
    private String UpFirstStr(String str) {
        return str.replaceFirst(str.substring(0, 1), str.substring(0, 1).toUpperCase());
    }

    public Object excuteOneObject(String sql, Class clazz, String esType, String esIndex) {
        try {
            SQLExprParser parser = new ElasticSqlExprParser(sql);
            SQLExpr expr = parser.expr();
            SQLQueryExpr queryExpr = (SQLQueryExpr) expr;

            Select select = null;
            select = new SqlParser().parseSelect(queryExpr);

            //通过抽象语法树，封装成自定义的Select，包含了select、from、where group、limit等
            AggregationQueryAction action = null;
            DefaultQueryAction queryAction = null;
            SqlElasticSearchRequestBuilder requestBuilder = null;
            if (select.isAgg) {
                //包含计算的的排序分组的
                action = new AggregationQueryAction(elasticFactory.getTransportClient(), select);
                requestBuilder = action.explain();
            } else {
                //封装成自己的Select对象
                queryAction = new DefaultQueryAction(elasticFactory.getTransportClient(), select);
                requestBuilder = queryAction.explain();
            }
            SearchResponse response = (SearchResponse) requestBuilder.get();
            ObjectResult temp = new ObjectResultsExtractor(true, true, true).extractResults(response.getHits(), true);
            List<String> heads = temp.getHeaders();
            Object saveModel = clazz.newInstance();
            try {
                for (int i = 0; i < temp.getLines().get(0).size(); i++) {
                    String key = null;
                    Object value = temp.getLines().get(0).get(i);
                    if (heads.get(i).contains("createTime")) {
                        key = "setCreateTime";
                        value = DateUtil.strToDate(String.valueOf(value).replace("+0800", "").replace("T", " "), "yyyy-MM-dd HH:mm:ss");
                    } else {
                        key = "set" + UpFirstStr(heads.get(i));
                    }

                    if (value instanceof String) {
                        clazz.getMethod(key, String.class).invoke(saveModel, value);
                    } else if (value instanceof Integer) {
                        clazz.getMethod(key, Integer.class).invoke(saveModel, value);
                    } else if (value instanceof Double) {
                        clazz.getMethod(key, Double.class).invoke(saveModel, value);
                    } else if (value instanceof java.util.Date) {
                        clazz.getMethod(key, java.util.Date.class).invoke(saveModel, value);
                    }
                }
            } catch (Exception e) {
                logger.warn(e.getMessage());
            }
            return saveModel;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }

    /**
     * 0级指标查询列表
     * 获取所有指标的增量、到达量
     * 备注：原来接口的一级指标对应现在的
     *
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @param area      区域code
     * @param level     等级
     * @param index     指标
     * @param timeLevel 1增量 2到达量
     * @param interval  1日 2周 3月
     * @param lowLevel  下一级区域等级
     * @return
     * @throws Exception
     */
        public List findDateQuotaLevel0(String startDate, String endDate, String area, int level, String index, String timeLevel, String interval, String lowLevel) throws Exception {

        String areaLevel="6";
        if (!index.contains(",")){
            String sqlArea = " select area_level from wlyy_job_config_new where id='"+index+"' ";
            List<String> areaLevels = jdbcTemplate.queryForList(sqlArea,String.class);
            if (areaLevels.size()>0){
                areaLevel = areaLevels.get(0);
            }
        }


        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
            } else {
                startDate = changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = changeTime(endDate);
            } else {
                endDate = changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        if (SaveModel.doctorLevel.equals(low_level)) {
            sql.append("select doctor as doctor,doctorName as doctorName,sum(result1) as result1, sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by doctor,doctorName");
        }else if (SaveModel.deptLevel.equals(low_level)) {
            sql.append("select dept as dept,deptName as deptName,sum(result1) as result1, sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by dept,deptName");
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital as hospital ,hospitalName as hospitalName,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by hospital,hospitalName");
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town as town,townName astownName,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by town,townName");
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city,cityName,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by city,cityName");
        }

        if (StringUtils.isNotEmpty(area)) {

            if (SaveModel.doctorLevel.equals(level + "")) {
                sql.append(" doctor='" + area + "'");
            }else if (SaveModel.deptLevel.equals(level + "")) {
                sql.append(" dept='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }
            sql.append(" and ");
        }
//        sql.append(" quotaCode='" + index + "'  ");
        sql.append(" quotaCode in(" + index + ")  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='"+areaLevel+"'");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }


        //根据时间维度分组
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00','alias'='quotaDate') ");
            }
        }
        sql.append(groupBy);
        logger.info("sql:"+sql);
        return excute(sql.toString(), SaveModel.class, "", "");
    }

    /**
     * 0级指标查询列表
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param timeLevel
     * @param interval
     * @param lowLevel
     * @param areaLevel
     * @return
     * @throws Exception
     */
    public List findDateQuotaLevel0(String startDate, String endDate, String area, int level, String index, String timeLevel, String interval, String lowLevel,String areaLevel) throws Exception {

        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        areaLevel="6";
        if (!index.contains(",")){
            String sqlArea = " select area_level from wlyy_job_config_new where id="+index;
            List<String> areaLevels = jdbcTemplate.queryForList(sqlArea,String.class);
            if (areaLevels.size()>0){
                areaLevel = areaLevels.get(0);
            }
        }
        if (StringUtils.isBlank(areaLevel)){
            areaLevel="6";
        }
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
            } else {
                startDate = changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = changeTime(endDate);
            } else {
                endDate = changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        if (SaveModel.doctorLevel.equals(low_level)) {
            sql.append("select doctor as doctor,doctorName as doctorName,sum(result1) as result1, sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by doctor,doctorName");
        }else if (SaveModel.deptLevel.equals(low_level)) {
            sql.append("select dept as dept,deptName as deptName,sum(result1) as result1, sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by dept,deptName");
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital as hospital ,hospitalName as hospitalName,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by hospital,hospitalName");
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town as town,townName astownName,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by town,townName");
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city,cityName,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by city,cityName");
        }

        if (StringUtils.isNotEmpty(area)) {

            if (SaveModel.doctorLevel.equals(level + "")) {
                sql.append(" doctor='" + area + "'");
            }else if (SaveModel.deptLevel.equals(level + "")) {
                sql.append(" dept='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }
            sql.append(" and ");
        }
//        sql.append(" quotaCode='" + index + "'  ");
        sql.append(" quotaCode in(" + index + ")  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='"+areaLevel+"'");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }


        //根据时间维度分组
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00','alias'='quotaDate') ");
            }
        }
        sql.append(groupBy);
        logger.info("sql:"+sql);
        return excute(sql.toString(), SaveModel.class, "", "");
    }

    /**
     * 按照医生人数统计-不重复
     * 获取所有指标的增量、到达量
     * 备注：原来接口的一级指标对应现在的
     *
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @param area      区域code
     * @param level     等级
     * @param index     指标
     * @param timeLevel 1增量 2到达量
     * @param interval  1日 2周 3月
     * @param lowLevel  下一级区域等级
     * @return
     * @throws Exception
     */
    public List findDateQuotaLevel0AndPaibanLine(String startDate, String endDate, String area, int level, String index, String timeLevel, String interval, String lowLevel) throws Exception {

        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
            } else {
                startDate = changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = changeTime(endDate);
            } else {
                endDate = changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        if (SaveModel.doctorLevel.equals(low_level)) {
            sql.append("select doctor as doctor,doctorName as doctorName,count(doctor) as result1, count(doctor) as result2 from " + esIndex + " where ");
            groupBy.append("  group by doctor,doctorName");
        }else if (SaveModel.deptLevel.equals(low_level)) {
            sql.append("select dept as dept,deptName as deptName,count(DISTINCT doctor) as result1, count(DISTINCT doctor) as result2 from " + esIndex + " where ");
            groupBy.append("  group by ");
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital as hospital,hospitalName as hospitalName,count(DISTINCT doctor) as result1,count(DISTINCT doctor) as result2 from " + esIndex + " where ");
            groupBy.append("  group by ");
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town as town,townName as townName,count(DISTINCT doctor) as result1,count(DISTINCT doctor) as result2 from " + esIndex + " where ");
            groupBy.append("  group by ");
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city as city,cityName as cityName,count(DISTINCT doctor) as result1,count(DISTINCT doctor) as result2 from " + esIndex + " where ");
            groupBy.append("  group by ");
        }

        if (StringUtils.isNotEmpty(area)) {

            if (SaveModel.doctorLevel.equals(level + "")) {
                sql.append(" doctor='" + area + "'");
            }else if (SaveModel.deptLevel.equals(level + "")) {
                sql.append(" dept='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }
            sql.append(" and ");
        }
//        sql.append(" quotaCode='" + index + "'  ");
        sql.append(" quotaCode in(" + index + ")  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='6'");
        sql.append(" and result1<>0 ");

        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }


        //根据时间维度分组
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00','alias'='quotaDate') ");
            }
        }
        sql.append(groupBy);

        return excute(sql.toString(), SaveModel.class, "", "");
    }



    /**
     * 按照医生人数统计-不重复
     * 获取所有指标的增量、到达量
     * 备注：原来接口的一级指标对应现在的
     *
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @param area      区域code
     * @param level     等级
     * @param index     指标
     * @param timeLevel 1增量 2到达量
     * @param interval  1日 2周 3月
     * @param lowLevel  下一级区域等级
     * @return
     * @throws Exception
     */
    public List findDateQuotaLevel0AndPaibanList(String startDate, String endDate, String area, int level, String index, String timeLevel, String interval, String lowLevel) throws Exception {

        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
            } else {
                startDate = changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = changeTime(endDate);
            } else {
                endDate = changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        if (SaveModel.doctorLevel.equals(low_level)) {
            sql.append("select doctor as doctor,doctorName as doctor,count(doctor) as result1, count(doctor) as result2 from " + esIndex + " where ");
            groupBy.append("  group by doctor,doctorName");
        }else if (SaveModel.deptLevel.equals(low_level)) {
            sql.append("select dept as dept,deptName as deptName,count(DISTINCT doctor) as result1, count(DISTINCT doctor) as result2 from " + esIndex + " where ");
            groupBy.append("  group by dept");
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital as hospital,hospitalName as hospitalName,count(DISTINCT doctor) as result1,count(DISTINCT doctor) as result2 from " + esIndex + " where ");
            groupBy.append("  group by hospital");
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town as town,townName as townName,count(DISTINCT doctor) as result1,count(DISTINCT doctor) as result2 from " + esIndex + " where ");
            groupBy.append("  group by town");
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city as city,cityName as cityName,count(DISTINCT doctor) as result1,count(DISTINCT doctor) as result2 from " + esIndex + " where ");
            groupBy.append("  group by city");
        }

        if (StringUtils.isNotEmpty(area)) {

            if (SaveModel.doctorLevel.equals(level + "")) {
                sql.append(" doctor='" + area + "'");
            }else if (SaveModel.deptLevel.equals(level + "")) {
                sql.append(" dept='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }
            sql.append(" and ");
        }
//        sql.append(" quotaCode='" + index + "'  ");
        sql.append(" quotaCode in(" + index + ")  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='6'");
        sql.append(" and result1<>0 ");

        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }


        //根据时间维度分组
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00','alias'='quotaDate') ");
            }
        }
        sql.append(groupBy);

        return excute(sql.toString(), SaveModel.class, "", "");
    }

    /**
     * 一级指标查询列表
     * 获取一级指标的增量、到达量
     * 备注：原接口的二级指标对应现在的一级指标
     *
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @param area      区域code
     * @param level     等级
     * @param index     指标
     * @param timeLevel 1增量 2到达量
     * @param slaveKey1 一级维度
     * @param interval  1日 2周 3月
     * @param lowLevel  下个等级
     * @return
     * @throws Exception
     */
    public List findDateQuotaLevel1(String startDate, String endDate, String area, int level, String index, String timeLevel, String slaveKey1, String interval, String lowLevel) throws Exception {

        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
            } else {
                startDate = changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = changeTime(endDate);
            } else {
                endDate = changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        if (SaveModel.doctorLevel.equals(low_level)) {
            sql.append("select doctor as doctor,doctorName as doctorName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,sum(result1) as result1, sum(result2) as result2,quotaDate as quotaDate from " + esIndex + " where ");
            groupBy.append("  group by doctor,doctorName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1)&&!slaveKey1.contains(",")&&(!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1))) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        }
        if (SaveModel.deptLevel.equals(low_level)) {
            sql.append("select dept as dept,deptName as deptName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,sum(result1) as result1, sum(result2) as result2,quotaDate as quotaDate from " + esIndex + " where ");
            groupBy.append("  group by dept,deptName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1)&&!slaveKey1.contains(",")&&(!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1))) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital as hospital,hospitalName as hospitalName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,sum(result1)  as result1,sum(result2) as result2,quotaDate as quotaDate from " + esIndex + " where ");
            groupBy.append("  group by hospital,hospitalName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1)&&!slaveKey1.contains(",")&&(!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1))) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town as town,townName as townName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,sum(result1) as result1,sum(result2) as result2,quotaDate as quotaDate from " + esIndex + " where ");
            groupBy.append("  group by town,townName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1)&&!slaveKey1.contains(",")&&(!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1))) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city as city,cityName as cityName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,sum(result1) as result1,sum(result2) as result2,quotaDate as quotaDate from " + esIndex + " where ");
            groupBy.append("  group by city,cityName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1)&&!slaveKey1.contains(",")&&(!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1))) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        }

        if (StringUtils.isNotEmpty(area)) {
            if (SaveModel.doctorLevel.equals(level + "")) {
                sql.append(" doctor='" + area + "'");
            }else if (SaveModel.deptLevel.equals(level + "")) {
                sql.append(" dept='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }
            sql.append(" and ");
        }
//        sql.append(" quotaCode='" + index + "'  ");
        sql.append(" quotaCode in(" + index + ")  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='6'");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }
        if (StringUtils.isNotEmpty(slaveKey1) && !commonParams.equals(slaveKey1)) {
            String[] temp = slaveKey1.split(",");
            String slaveKey1Temp = "";
            for(String one : temp){
                slaveKey1Temp += ",'"+one+"'";
            }
            sql.append(" and slaveKey1 in ("+slaveKey1Temp.substring(1)+")");
        }

        //根据时间维度分组
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00','alias'='quotaDate') ");
            }
        }
        sql.append(groupBy);
        logger.info("sql:"+sql);
        return excute(sql.toString(), SaveModel.class, "", "");
    }

    /**
     * 一级指标查询列表
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param timeLevel
     * @param slaveKey1
     * @param interval
     * @param lowLevel
     * @param areaLevel
     * @return
     * @throws Exception
     */
    public List findDateQuotaLevel1(String startDate, String endDate, String area, int level, String index, String timeLevel, String slaveKey1, String interval, String lowLevel,String areaLevel) throws Exception {

        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
            } else {
                startDate = changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = changeTime(endDate);
            } else {
                endDate = changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        if (SaveModel.doctorLevel.equals(low_level)) {
            sql.append("select doctor as doctor,doctorName as doctorName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,sum(result1) as result1, sum(result2) as result2,quotaDate as quotaDate from " + esIndex + " where ");
            groupBy.append("  group by doctor,doctorName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1)&&!slaveKey1.contains(",")&&(!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1))) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        }
        if (SaveModel.deptLevel.equals(low_level)) {
            sql.append("select dept as dept,deptName as deptName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,sum(result1) as result1, sum(result2) as result2,quotaDate as quotaDate from " + esIndex + " where ");
            groupBy.append("  group by dept,deptName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1)&&!slaveKey1.contains(",")&&(!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1))) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital as hospital,hospitalName as hospitalName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,sum(result1)  as result1,sum(result2) as result2,quotaDate as quotaDate from " + esIndex + " where ");
            groupBy.append("  group by hospital,hospitalName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1)&&!slaveKey1.contains(",")&&(!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1))) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town as town,townName as townName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,sum(result1) as result1,sum(result2) as result2,quotaDate as quotaDate from " + esIndex + " where ");
            groupBy.append("  group by town,townName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1)&&!slaveKey1.contains(",")&&(!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1))) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city as city,cityName as cityName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,sum(result1) as result1,sum(result2) as result2,quotaDate as quotaDate from " + esIndex + " where ");
            groupBy.append("  group by city,cityName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1)&&!slaveKey1.contains(",")&&(!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1))) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        }

        if (StringUtils.isNotEmpty(area)) {
            if (SaveModel.doctorLevel.equals(level + "")) {
                sql.append(" doctor='" + area + "'");
            }else if (SaveModel.deptLevel.equals(level + "")) {
                sql.append(" dept='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }
            sql.append(" and ");
        }
//        sql.append(" quotaCode='" + index + "'  ");
        sql.append(" quotaCode in(" + index + ")  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='"+areaLevel+"'");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }
        if (StringUtils.isNotEmpty(slaveKey1) && !commonParams.equals(slaveKey1)) {
            String[] temp = slaveKey1.split(",");
            String slaveKey1Temp = "";
            for(String one : temp){
                slaveKey1Temp += ",'"+one+"'";
            }
            sql.append(" and slaveKey1 in ("+slaveKey1Temp.substring(1)+")");
        }

        //根据时间维度分组
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00','alias'='quotaDate') ");
            }
        }
        sql.append(groupBy);
        logger.info("sql:"+sql);
        return excute(sql.toString(), SaveModel.class, "", "");
    }

    /**
     * 二级指标查询列表
     * 获取二级指标的增量、到达量
     * 备注：原接口的三级指标对应现在的二级指标
     *
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @param area      区域code
     * @param level     等级
     * @param index     指标
     * @param timeLevel 1增量 2到达量
     * @param slaveKey1 一级维度code
     * @param slaveKey2 二级维度code
     * @param interval  1日 2周 3月
     * @param lowLevel  下一等级
     * @return
     */
    public List findDateQuotaLevel2(String startDate, String endDate, String area, int level, String index, String timeLevel, String slaveKey1, String slaveKey2, String interval, String lowLevel) {

        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
            } else {
                startDate = changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = changeTime(endDate);
            } else {
                endDate = changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        if (SaveModel.doctorLevel.equals(low_level)) {
            sql.append("select doctor as doctor,doctorName as doctorName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,slaveKey2 as slaveKey2,slaveKey2Name as slaveKey2Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by doctor,doctorName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey2) || commonParams.equals(slaveKey2)) {
                groupBy.append(",slaveKey2,slaveKey2Name");
            }
        }else if (SaveModel.deptLevel.equals(low_level)) {
            sql.append("select dept as dept,deptName as deptName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,slaveKey2 as slaveKey2,slaveKey2Name as slaveKey2Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by dept,deptName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey2) || commonParams.equals(slaveKey2)) {
                groupBy.append(",slaveKey2,slaveKey2Name");
            }
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital as hospital,hospitalName as hospitalName,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by hospital,hospitalName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey2) || commonParams.equals(slaveKey2)) {
                groupBy.append(",slaveKey2,slaveKey2Name");
            }
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town as town,townName as townName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,slaveKey2 as slaveKey2,slaveKey2Name as slaveKey2Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by town,townName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey2) || commonParams.equals(slaveKey2)) {
                groupBy.append(",slaveKey2,slaveKey2Name");
            }
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city as city,cityName as cityName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,slaveKey2 as slaveKey2,slaveKey2Name as slaveKey2Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by city,cityName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey2) || commonParams.equals(slaveKey2)) {
                groupBy.append(",slaveKey2,slaveKey2Name");
            }
        }
        if (StringUtils.isNotEmpty(area)) {

                if (SaveModel.doctorLevel.equals(level + "")) {
                sql.append(" doctor='" + area + "'");
            }else if (SaveModel.deptLevel.equals(level + "")) {
                sql.append(" dept='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }
            sql.append(" and ");
        }
        sql.append(" quotaCode in(" + index + ")  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='6'");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }
        if (StringUtils.isNotBlank(slaveKey1) && (!commonParams.equals(slaveKey1))) {
            String[] str = slaveKey1.split(",");
            StringBuffer buffer = new StringBuffer();
            for (int i=0;i<str.length;i++){
                buffer.append("'"+str[i]+"',");
            }
            buffer.deleteCharAt(buffer.length()-1);
            sql.append(" and slaveKey1 in (" + buffer + ")");
        }
        if (StringUtils.isNotBlank(slaveKey2) && (!commonParams.equals(slaveKey2))) {
            String[] str = slaveKey2.split(",");
            StringBuffer buffer = new StringBuffer();
            for (int i=0;i<str.length;i++){
                buffer.append("'"+str[i]+"',");
            }
            buffer.deleteCharAt(buffer.length()-1);
            sql.append(" and slaveKey2 in (" + buffer + ")");

        }


        //根据时间维度分组
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00','alias'='quotaDate') ");
            }
        }
        sql.append(groupBy);
        logger.info("sql :" + sql.toString());
        return excute(sql.toString(), SaveModel.class, "", "");
    }

    /**
     * 多维度指标查寻(可控纬度与分组)
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param timeLevel
     * @param interval
     * @param lowLevel
     * @param groupKey
     * @param slaveKeys
     * @return
     */
    public List findDateQuotaLevels(String startDate, String endDate, String area, int level, String index, String timeLevel,String interval, String lowLevel,String groupKey,String ...slaveKeys) {
        String areaLevel="6";
        if (!index.contains(",")){
            String sqlArea = " select area_level from wlyy_job_config_new where id='"+index+"' ";
            List<String> areaLevels = jdbcTemplate.queryForList(sqlArea,String.class);
            if (areaLevels.size()>0){
                areaLevel = areaLevels.get(0);
            }
        }

        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
            } else {
                startDate = changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = changeTime(endDate);
            } else {
                endDate = changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        String[] groupKeys = groupKey.split(",");
        StringBuffer selectKeys = new StringBuffer();
        StringBuffer groupStr = new StringBuffer();

        int i=1;
        for (String slaveKeyTmp:slaveKeys){
            selectKeys.append(" slaveKey").append(i).append(" as slaveKey").append(i).append(",slaveKey").append(i).append("Name as slaveKey").append(i).append("Name, ");
            i++;
        }
        for (String groupKeyTmp:groupKeys){
            groupStr.append(",slaveKey"+groupKeyTmp+",slaveKey"+groupKeyTmp+"Name");
        }
        if (SaveModel.doctorLevel.equals(low_level)) {
            sql.append("select doctor as doctor,doctorName as doctorName,"+selectKeys.toString()+"sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by doctor,doctorName").append(groupStr.toString());

        }else if (SaveModel.deptLevel.equals(low_level)) {
            sql.append("select dept as dept,deptName as deptName,"+selectKeys.toString()+"sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by dept,deptName").append(groupStr.toString());

        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital as hospital,hospitalName as hospitalName,"+selectKeys.toString()+"sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by hospital,hospitalName").append(groupStr.toString());

        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town as town,townName as townName,"+selectKeys.toString()+"sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by town,townName").append(groupStr.toString());

        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city as city,cityName as cityName,"+selectKeys.toString()+"sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by city,cityName").append(groupStr.toString());

        }
        if (StringUtils.isNotEmpty(area)) {

            if (SaveModel.doctorLevel.equals(level + "")) {
                sql.append(" doctor='" + area + "'");
            }else if (SaveModel.deptLevel.equals(level + "")) {
                sql.append(" dept='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }
            sql.append(" and ");
        }
        sql.append(" quotaCode in(" + index + ")  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='"+areaLevel+"'");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }

        i=1;
        for (String slaveKeyTmp:slaveKeys){
            if (StringUtils.isNotBlank(slaveKeyTmp)){
                String[] str = slaveKeyTmp.split(",");
                StringBuffer buffer = new StringBuffer();
                for (int j=0;j<str.length;j++){
                    buffer.append("'"+str[j]+"',");
                }
                buffer.deleteCharAt(buffer.length()-1);
                sql.append(" and slaveKey").append(i).append(" in (" + buffer + ")");
            }
            i++;
        }

        //根据时间维度分组
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00','alias'='quotaDate') ");
            }
        }
        sql.append(groupBy);
        logger.info("sql :" + sql.toString());
        return excute(sql.toString(), SaveModel.class, "", "");
    }

    /**
     * 二级指标查询
     */
    public List findDateQuotaLevel2(String startDate, String endDate, String area, int level, String index, String timeLevel, String slaveKey1, String slaveKey2, String interval, String lowLevel,String areaLevel) {

        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
            } else {
                startDate = changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = changeTime(endDate);
            } else {
                endDate = changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        if (SaveModel.doctorLevel.equals(low_level)) {
            sql.append("select doctor as doctor,doctorName as doctorName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,slaveKey2 as slaveKey2,slaveKey2Name as slaveKey2Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by doctor,doctorName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey2) || commonParams.equals(slaveKey2)) {
                groupBy.append(",slaveKey2,slaveKey2Name");
            }
        }else if (SaveModel.deptLevel.equals(low_level)) {
            sql.append("select dept as dept,deptName as deptName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,slaveKey2 as slaveKey2,slaveKey2Name as slaveKey2Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by dept,deptName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey2) || commonParams.equals(slaveKey2)) {
                groupBy.append(",slaveKey2,slaveKey2Name");
            }
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital as hospital,hospitalName as hospitalName,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by hospital,hospitalName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey2) || commonParams.equals(slaveKey2)) {
                groupBy.append(",slaveKey2,slaveKey2Name");
            }
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town as town,townName as townName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,slaveKey2 as slaveKey2,slaveKey2Name as slaveKey2Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by town,townName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey2) || commonParams.equals(slaveKey2)) {
                groupBy.append(",slaveKey2,slaveKey2Name");
            }
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city as city,cityName as cityName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,slaveKey2 as slaveKey2,slaveKey2Name as slaveKey2Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by city,cityName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey2) || commonParams.equals(slaveKey2)) {
                groupBy.append(",slaveKey2,slaveKey2Name");
            }
        }
        if (StringUtils.isNotEmpty(area)) {

            if (SaveModel.doctorLevel.equals(level + "")) {
                sql.append(" doctor='" + area + "'");
            }else if (SaveModel.deptLevel.equals(level + "")) {
                sql.append(" dept='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }
            sql.append(" and ");
        }
        sql.append(" quotaCode in(" + index + ")  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='"+areaLevel+"'");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }
        if (StringUtils.isNotBlank(slaveKey1) && (!commonParams.equals(slaveKey1))) {
            String[] str = slaveKey1.split(",");
            StringBuffer buffer = new StringBuffer();
            for (int i=0;i<str.length;i++){
                buffer.append("'"+str[i]+"',");
            }
            buffer.deleteCharAt(buffer.length()-1);
            sql.append(" and slaveKey1 in (" + buffer + ")");
        }
        if (StringUtils.isNotBlank(slaveKey2) && (!commonParams.equals(slaveKey2))) {
            String[] str = slaveKey2.split(",");
            StringBuffer buffer = new StringBuffer();
            for (int i=0;i<str.length;i++){
                buffer.append("'"+str[i]+"',");
            }
            buffer.deleteCharAt(buffer.length()-1);
            sql.append(" and slaveKey2 in (" + buffer + ")");

        }


        //根据时间维度分组
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00','alias'='quotaDate') ");
            }
        }
        sql.append(groupBy);
        logger.info("sql :" + sql.toString());
        return excute(sql.toString(), SaveModel.class, "", "");
    }

    /**
     * 二级指标查询,并根据key分组查询
     *
     */
    public List findDateQuotaLevel2ByKeyGroup(String startDate, String endDate, String area, int level, String index, String timeLevel, String slaveKey1, String slaveKey2, String interval, String lowLevel,String areaLevel,String keyGroup) {

        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
            } else {
                startDate = changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = changeTime(endDate);
            } else {
                endDate = changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        if (SaveModel.doctorLevel.equals(low_level)) {
            sql.append("select doctor as doctor,doctorName as doctorName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,slaveKey2 as slaveKey2,slaveKey2Name as slaveKey2Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by doctor,doctorName");
            if ("2".equals(keyGroup)){
                groupBy.append(",slaveKey2,slaveKey2Name");
            }else {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        }else if (SaveModel.deptLevel.equals(low_level)) {
            sql.append("select dept as dept,deptName as deptName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,slaveKey2 as slaveKey2,slaveKey2Name as slaveKey2Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by dept,deptName");
            if ("2".equals(keyGroup)){
                groupBy.append(",slaveKey2,slaveKey2Name");
            }else {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital as hospital,hospitalName as hospitalName,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by hospital,hospitalName");
            if ("2".equals(keyGroup)){
                groupBy.append(",slaveKey2,slaveKey2Name");
            }else {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town as town,townName as townName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,slaveKey2 as slaveKey2,slaveKey2Name as slaveKey2Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by town,townName");
            if ("2".equals(keyGroup)){
                groupBy.append(",slaveKey2,slaveKey2Name");
            }else {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city as city,cityName as cityName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,slaveKey2 as slaveKey2,slaveKey2Name as slaveKey2Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by city,cityName");
            if ("2".equals(keyGroup)){
                groupBy.append(",slaveKey2,slaveKey2Name");
            }else {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        }
        if (StringUtils.isNotEmpty(area)) {

            if (SaveModel.doctorLevel.equals(level + "")) {
                sql.append(" doctor='" + area + "'");
            }else if (SaveModel.deptLevel.equals(level + "")) {
                sql.append(" dept='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }
            sql.append(" and ");
        }
        sql.append(" quotaCode in(" + index + ")  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='"+areaLevel+"'");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }
        if (StringUtils.isNotBlank(slaveKey1) && (!commonParams.equals(slaveKey1))) {
            String[] str = slaveKey1.split(",");
            StringBuffer buffer = new StringBuffer();
            for (int i=0;i<str.length;i++){
                buffer.append("'"+str[i]+"',");
            }
            buffer.deleteCharAt(buffer.length()-1);
            sql.append(" and slaveKey1 in (" + buffer + ")");
        }
        if (StringUtils.isNotBlank(slaveKey2) && (!commonParams.equals(slaveKey2))) {
            String[] str = slaveKey2.split(",");
            StringBuffer buffer = new StringBuffer();
            for (int i=0;i<str.length;i++){
                buffer.append("'"+str[i]+"',");
            }
            buffer.deleteCharAt(buffer.length()-1);
            sql.append(" and slaveKey2 in (" + buffer + ")");

        }


        //根据时间维度分组
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00','alias'='quotaDate') ");
            }
        }
        sql.append(groupBy);
        logger.info("sql :" + sql.toString());
        return excute(sql.toString(), SaveModel.class, "", "");
    }

    /**
     * 时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
     *
     * @param quotaDate
     */
    public String changeDate(String quotaDate) {
        try {
            quotaDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXX").format(new SimpleDateFormat("yyyy-MM-dd").parse(quotaDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return quotaDate;
    }

    public String changeTime(String time) {
        try {
            if (time.length() == 10) {
                time = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXX").format(new SimpleDateFormat("yyyy-MM-dd").parse(time));
            } else if (time.length() == 19) {
                time = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXX").format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    //获取最新更新的时间
    public String getQuotaTime() {
        String date = redisTemplate.opsForValue().get("quota:date");
//        date = date.replace(" ","T")+"+0800";
        try {
            date = new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 获取一个指标下所有一级维度按维度分组的数据
     *
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param timeLevel
     * @param interval
     * @param lowLevel
     * @return
     * @throws Exception
     */
    public List findDateAllQuotaLevel1(String startDate, String endDate, String area, int level, String index, String timeLevel, String interval, String lowLevel,String areaLevel) throws Exception {

        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
            } else {
                startDate = changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = changeTime(endDate);
            } else {
                endDate = changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        if (SaveModel.doctorLevel.equals(low_level)) {
            sql.append("select doctor as doctor,doctorName as doctorName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,sum(result1) as result1, sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by doctor,doctorName,slaveKey1,slaveKey1Name");
        }else if (SaveModel.deptLevel.equals(low_level)) {
            sql.append("select dept as dept,deptName as deptName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,sum(result1) as result1, sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by dept,deptName,slaveKey1,slaveKey1Name");
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital as hospital,hospitalName as hospitalName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by hospital,hospitalName,slaveKey1,slaveKey1Name");
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town as town,townName as townName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by town,townName,slaveKey1,slaveKey1Name");
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city as city,cityName as cityName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by city,cityName,slaveKey1,slaveKey1Name");
        }

        if (StringUtils.isNotEmpty(area)) {
            if (SaveModel.doctorLevel.equals(level + "")) {
                sql.append(" doctor='" + area + "'");
            }else if (SaveModel.deptLevel.equals(level + "")) {
                sql.append(" dept='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }
            sql.append(" and ");
        }
        sql.append(" quotaCode='" + index + "'  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='"+areaLevel+"'");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }

        //根据时间维度分组
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00','alias'='quotaDate') ");
            }
        }
        sql.append(groupBy);

        return excute(sql.toString(), SaveModel.class, "", "");
    }

    /**
     *获取一个指标下所有二级维度按维度分组的数据
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param timeLevel
     * @param interval
     * @param lowLevel
     * @param areaLevel
     * @return
     * @throws Exception
     */
    public List findDateAllQuotaLevel2(String startDate, String endDate, String area, int level, String index, String timeLevel, String interval, String lowLevel,String areaLevel) throws Exception {

        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
            } else {
                startDate = changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = changeTime(endDate);
            } else {
                endDate = changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        if (SaveModel.doctorLevel.equals(low_level)) {
            sql.append("select doctor as doctor,doctorName as doctorName,slaveKey2 as slaveKey2,slaveKey2Name as slaveKey2Name,sum(result1) as result1, sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by doctor,doctorName,slaveKey2,slaveKey2Name");
        }else if (SaveModel.deptLevel.equals(low_level)) {
            sql.append("select dept as dept,deptName as deptName,slaveKey2 as slaveKey2,slaveKey2Name as slaveKey2Name,sum(result1) as result1, sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by dept,deptName,slaveKey2,slaveKey2Name");
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital as hospital,hospitalName as hospitalName,slaveKey2 as slaveKey2,slaveKey2Name as slaveKey2Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by hospital,hospitalName,slaveKey2,slaveKey2Name");
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town as town,townName as townName,slaveKey2 as slaveKey2,slaveKey2Name as slaveKey2Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by town,townName,slaveKey2,slaveKey2Name");
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city as city,cityName as cityName,slaveKey2 as slaveKey2,slaveKey2Name as slaveKey2Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by city,cityName,slaveKey2,slaveKey2Name");
        }

        if (StringUtils.isNotEmpty(area)) {
            if (SaveModel.doctorLevel.equals(level + "")) {
                sql.append(" doctor='" + area + "'");
            }else if (SaveModel.deptLevel.equals(level + "")) {
                sql.append(" dept='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }
            sql.append(" and ");
        }
        sql.append(" quotaCode='" + index + "'  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='"+areaLevel+"'");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }

        //根据时间维度分组
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00','alias'='quotaDate') ");
            }
        }
        sql.append(groupBy);

        return excute(sql.toString(), SaveModel.class, "", "");
    }

    public List findDateAllQuotaLevel3(String startDate, String endDate, String area, int level, String index, String timeLevel, String interval, String lowLevel) throws Exception {

        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
            } else {
                startDate = changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = changeTime(endDate);
            } else {
                endDate = changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        if (SaveModel.doctorLevel.equals(low_level)) {
            sql.append("select doctor as doctor,doctorName as doctorName,slaveKey3 as slaveKey3,slaveKey3Name as slaveKey3Name,sum(result1) as result1, sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by doctor,doctorName,slaveKey3,slaveKey3Name");
        }else if (SaveModel.deptLevel.equals(low_level)) {
            sql.append("select dept as dept,deptName as deptName,slaveKey3 as slaveKey3,slaveKey3Name as slaveKey3Name,sum(result1) as result1, sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by dept,deptName,slaveKey3,slaveKey3Name");
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital as hospital,hospitalName as hospitalName,slaveKey3 as slaveKey3,slaveKey3Name as slaveKey3Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by hospital,hospitalName,slaveKey3,slaveKey3Name");
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town as town,townName as townName,slaveKey3 as slaveKey3,slaveKey3Name as slaveKey3Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by town,townName,slaveKey3,slaveKey3Name");
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city as city,cityName as cityName,slaveKey3 as slaveKey3,slaveKey3Name as slaveKey3Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by city,cityName,slaveKey3,slaveKey3Name");
        }

        if (StringUtils.isNotEmpty(area)) {
            if (SaveModel.doctorLevel.equals(level + "")) {
                sql.append(" doctor='" + area + "'");
            }else if (SaveModel.deptLevel.equals(level + "")) {
                sql.append(" dept='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }
            sql.append(" and ");
        }
        sql.append(" quotaCode='" + index + "'  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='6'");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }

        //根据时间维度分组
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00','alias'='quotaDate') ");
            }
        }
        sql.append(groupBy);

        return excute(sql.toString(), SaveModel.class, "", "");
    }

    /**
     * 0级维度
     * 查询某一天某一个0级维度的指标
     *
     * @param quotaDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @return
     */
    public SaveModel findOneDateQuotaLevel0(String quotaDate, String area, int level, String index, String timelevel) throws Exception {
        List list = findDateQuotaLevel0(quotaDate, quotaDate, area, level, index, timelevel, null, null);
        return (SaveModel) list.get(0);
    }

    /**
     * 0级维度
     * 查询某个时间区间某一个0级维度的指标
     *
     * @param startDate 开始时间 yyyy-mm-dd
     * @param endDate   结束时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5科室 6医生
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @return
     */
    public SaveModel findOneDateQuotaLevel0(String startDate, String endDate, String area, int level, String index, String timelevel) throws Exception {
        List list = findDateQuotaLevel0(startDate, endDate, area, level, index, timelevel, null, null);
        return (SaveModel) list.get(0);
    }

    public SaveModel findOneDateQuotaLevel0(String startDate, String endDate, String area, int level, String index, String timelevel,String areaLevel) throws Exception {
        List list = findDateQuotaLevel0(startDate, endDate, area, level, index, timelevel, null, null,areaLevel);
        return (SaveModel) list.get(0);
    }

//    public SaveModel findOneDateQuotaLevel1(String startDate, String endDate, String area, int level, String index, String timelevel,String slaveKey1,String areaLevel) throws Exception {
//        List list = findDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, slaveKey1, null, null);
//        return (SaveModel) list.get(0);
//    }

    /**
     * 1级维度
     * 查询某一天某一个1级维度的某个1级维度下的指标 例如查询65岁以上患者
     *
     * @param quotaDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5科室 6医生
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @param slaveKey1 一级维度的key 不传返回全部
     * @return
     */
    public SaveModel findOneDateQuotaLevel1(String quotaDate, String area, int level, String index, String timelevel, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel1(quotaDate, quotaDate, area, level, index, timelevel, slaveKey1, null, null);
        if (list.size() > 0) {
            return (SaveModel) list.get(0);
        } else {
            return null;
        }
    }




    /**
     * 1级维度
     * 查询某一天某一个1级维度的某个1级维度下的指标 例如查询65岁以上患者
     *
     * @param quotaDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5科室 6医生
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @return
     */
    public SaveModel findOneDateQuotaLevel1NoSlaveKey1(String quotaDate, String area, int level, String index, String timelevel) throws Exception {
        List list = findDateQuotaLevel1(quotaDate, quotaDate, area, level, index, timelevel, null, null, null);
        return (SaveModel) list.get(0);
    }

    /**
     * 1级维度
     * 查询某一个时间区间某一个1级维度的某个1级维度下的指标 例如查询65岁以上患者
     *
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param timelevel
     * @return
     * @throws Exception
     */
    public SaveModel findOneDateQuotaLevel1NoSlaveKey1(String startDate, String endDate, String area, int level, String index, String timelevel) throws Exception {
        List list = findDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, null, null, null);
        return (SaveModel) list.get(0);
    }

    /**
     * 1级维度
     * 查询某个时间区间某一个1级维度的某个1级维度下的指标 例如查询65岁以上患者
     *
     * @param startDate 开始时间 yyyy-mm-dd
     * @param endDate   结束时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5科室 6团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @param slaveKey1 一级维度的key 不传返回全部
     * @return
     */
    public SaveModel findOneDateQuotaLevel1(String startDate, String endDate, String area, int level, String index, String timelevel, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, slaveKey1, null, null);
        return (SaveModel) list.get(0);
    }
    public SaveModel findOneDateQuotaLevel1(String startDate, String endDate, String area, int level, String index, String timelevel, String slaveKey1,String areaLevel) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, slaveKey1, null, null,areaLevel);
        return (SaveModel) list.get(0);
    }

    public SaveModel bfindOneDateQuotaLevel12(String startDate, String endDate, String area, int level, String index, String timelevel, String slaveKey1, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, slaveKey1, slaveKey2, null, null);
        return (SaveModel) list.get(0);
    }

    /**
     * 多维度指标查询 可控制key与group
     */
    public  SaveModel findOneDateQuotaLevels(String startDate, String endDate, String area, int level, String index, String timelevel,String groupKey,String ...slaveKeys) throws Exception {
        List list = findDateQuotaLevels(startDate, endDate, area, level, index, timelevel,null, null,groupKey,slaveKeys);
        return (SaveModel) list.get(0);
    }

    /**
     * 1级维度
     * 查询某一天某一个所有1级维度下的指标 例如某个机构下的所有维度的患者列表
     *
     * @param quotaDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @return
     */
    public List<SaveModel> findOneDateQuotaLevel1(String quotaDate, String area, int level, String index, String timelevel) throws Exception {
        List list = findDateQuotaLevel1(quotaDate, quotaDate, area, level, index, timelevel, commonParams, null, null);
        return list;
    }

    /**
     * 多维度指标查询 可控制key与group
     */
    public  List<SaveModel> findDateQuotaLevelList(String startDate, String endDate, String area, int level, String index, String timelevel,String groupKey,String ...slaveKeys) throws Exception {
        List list = findDateQuotaLevels(startDate, endDate, area, level, index, timelevel,null, null,groupKey,slaveKeys);
        return list;
    }

    /**
     * 1级维度
     * 查询某一天某一个所有1级维度下的指标 例如某个机构下的所有维度的患者列表
     *
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @return
     */
    public List<SaveModel> findOneDateQuotaLevel1(String startDate, String endDate, String area, int level, String index, String timelevel) throws Exception {
        List list = findDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, commonParams, null, null);
        return list;
    }

    /**
     * 2级维度
     * 查询某一天某一个2级维度的某个1级维度和2级维度下的指标  例如查询65岁以上的高血压患者
     *
     * @param quotaDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @param slaveKey1 一级维度的key
     * @param slaveKey2 二级维度的key
     * @return
     */
    public List<SaveModel> findOneDateQuotaLevel2(String quotaDate, String area, int level, String index, String timelevel, String slaveKey1, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, slaveKey1, slaveKey2, null, null);
        return list;
    }

    /**
     * 根据2级维度的2级指标去聚合 没有一级维度
     * 查询某一天某一个2级维度的某个1级维度和2级维度下的指标  例如查询65岁以上的高血压患者
     *
     * @param quotaDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @param slaveKey2 二级维度的key
     * @return
     */
    public SaveModel findOneDateQuotaLevel2NoSlaveKey1(String quotaDate, String area, int level, String index, String timelevel, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, null, slaveKey2, null, null);
        return (SaveModel) list.get(0);
    }

    /**
     * 二级维度指标查询，无一级维度
     */
    public SaveModel findOneDateQuotaLevel2NoSlaveKey1(String quotaDate, String area, int level, String index, String timelevel, String slaveKey2,String areaLevel) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, null, slaveKey2, null, null,areaLevel);
        return (SaveModel) list.get(0);
    }

    /**
     * 根据2级维度的2级指标去聚合 没有一级维度
     * 查询某一天某一个2级维度的某个1级维度和2级维度下的指标  例如查询65岁以上的高血压患者
     *
     * @param startDate 时间 yyyy-mm-dd
     * @param endDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @param slaveKey2 二级维度的key
     * @return
     */
    public SaveModel findOneDateQuotaLevel2NoSlaveKey1(String startDate,String endDate, String area, int level, String index, String timelevel, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, null, slaveKey2, null, null);
        return (SaveModel) list.get(0);
    }

    /**
     * 根据2级维度的1级指标去聚合 没有2级维度
     * 查询某一天某一个2级维度的某个1级维度和2级维度下的指标  例如查询65岁以上的高血压患者
     *
     * @param quotaDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @param slaveKey1 二级维度的key
     * @return
     */
    public SaveModel findOneDateQuotaLevel2NoSlaveKey2(String quotaDate, String area, int level, String index, String timelevel, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, slaveKey1, null, null, null);
        return (SaveModel) list.get(0);
    }

    /**
     * 根据2级维度的1级指标去聚合 没有2级维度
     * 查询某一天某一个2级维度的某个1级维度和2级维度下的指标  例如查询65岁以上的高血压患者
     *
     * @param endDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @param slaveKey1 二级维度的key
     * @return
     */
    public SaveModel findOneDateQuotaLevel3NoSlaveKey2(String startDate,String endDate, String area, int level, String index, String timelevel, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, slaveKey1, null, null, null);
        return (SaveModel) list.get(0);
    }
    /**
     * 2级维度
     * 查询某个时间区间某一个2级维度的某个1级维度和2级维度下的指标  例如查询65岁以上的高血压患者
     *
     * @param startDate 开始时间 yyyy-mm-dd
     * @param endDate   结束时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @param slaveKey1 一级维度的key
     * @param slaveKey2 二级维度的key
     * @return
     */
    public SaveModel findOneDateQuotaLevel2(String startDate, String endDate, String area, int level, String index, String timelevel, String slaveKey1, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, slaveKey1, slaveKey2, null, null);
        return calculateResult(list);
    }

    /**
     * 对ES查询出来的结果的result1进行求和计算(可能有多条记录)
     * @param list
     * @return
     */
    private SaveModel calculateResult(List<SaveModel> list) {
        SaveModel saveModel = list.get(0);
        double sum = list.stream().mapToDouble(SaveModel::getResult1).sum();
        double sum2 = list.stream().mapToDouble(SaveModel::getResult2).sum();
        saveModel.setResult1(sum);
        saveModel.setResult2(sum2);
        return saveModel;
    }


    /**
     * 2级维度
     * 查询某个时间区间某一个2级维度的某个1级维度和2级维度下的指标  例如查询65岁以上的高血压患者
     *
     * @param startDate 开始时间 yyyy-mm-dd
     * @param endDate   结束时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @param slaveKey1 一级维度的key
     * @param slaveKey2 二级维度的key
     * @return
     */
    public SaveModel findOneDateQuotaLevel3(String startDate, String endDate, String area, int level, String index, String timelevel, String slaveKey1, String slaveKey2) throws Exception {
        List<SaveModel> list = findDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, slaveKey1, slaveKey2, null, null);
        SaveModel saveModel =(SaveModel) list.get(0);
        double result1 = 0L;
        double result2 = 0L;
        for (SaveModel saveModel1:list){
            result1+=saveModel1.getResult1();
            result2+=saveModel1.getResult2();
        }
        saveModel.setResult1(result1);
        saveModel.setResult1(result2);
        return saveModel;
    }

    /**
     * 2级维度
     * 查询某一天某个1级维度下所有2级维度的指标  例如查询65岁以上的高血压患者
     *
     * @param quotaDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @param slaveKey1 一级维度的key
     * @return
     */
    public List<SaveModel> findOneDateQuotaLevel2(String quotaDate, String area, int level, String index, String timelevel, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, slaveKey1, commonParams, null, null);
        return list;
    }

    /**
     * 折线图
     * 0级维度
     * 查询某个0级维度的指标折线图
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量（按照年度）
     * @param interval  1日 2周 3月 （按照日周月聚合）
     * @return
     * @throws Exception
     */
    public List<SaveModel> findLineChartDateQuotaLevel0(String startDate, String endDate, String area, int level, String index, String timelevel, String interval) throws Exception {
        List list = findDateQuotaLevel0(startDate, endDate, area, level, index, timelevel, interval, null);
        return list;
    }

    /**
     * 折线图
     * 1级维度
     * 查询某个1级维度的某个1级维度下的折线图 例如查询65岁以上患者
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量（按照年度）
     * @param interval  1日 2周 3月 （按照日周月聚合）
     * @param slaveKey1 一级维度的key
     * @return
     */
    public List<SaveModel> findLineChartDateQuotaLevel1(String startDate, String endDate, String area, int level, String index, String timelevel, String interval, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, slaveKey1, interval, null);
        return list;
    }

    /**
     * 折线图
     * 1级维度
     * 查询某个1级维度的某个1级维度下的折线图 例如查询65岁以上患者
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量（按照年度）
     * @param interval  1日 2周 3月 （按照日周月聚合）
     * @return
     */
    public List<SaveModel> findLineChartDateQuotaLevel1NoSlaveKey1(String startDate, String endDate, String area, int level, String index, String timelevel, String interval) throws Exception {
        List list = findDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, null, interval, null);
        return list;
    }

    /**
     * 折线图
     * 2级维度
     * 查询某个2级维度的某个1级维度和2级维度下的折线图  例如查询65岁以上的高血压患者
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量（按照年度）
     * @param interval  1日 2周 3月 （按照日周月聚合）
     * @param slaveKey1 一级维度的key
     * @param slaveKey2 二级维度的key
     * @return
     */
    public List<SaveModel> findLineChartDateQuotaLevel2(String startDate, String endDate, String area, int level, String index, String timelevel, String interval, String slaveKey1, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, slaveKey1, slaveKey2, interval, null);
        return list;
    }
    public List<SaveModel> findLineChartDateQuotaLevel4(String startDate, String endDate, String area, int level, String index, String timelevel, String interval, String slaveKey1, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, slaveKey1, slaveKey2, interval,null);
        return list;
    }

    public List<SaveModel> findLineChartDateQuotaLevel3(String startDate, String endDate, String area, int level, String index, String timelevel, String interval, String slaveKey1, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, slaveKey1, slaveKey2, interval, null);
        return list;
    }


    /**
     * 折线图
     * 2级维度只根绝第二个指标聚合
     * 查询某个2级维度的某个1级维度和2级维度下的折线图  例如查询65岁以上的高血压患者
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量（按照年度）
     * @param interval  1日 2周 3月 （按照日周月聚合）
     * @param slaveKey2 二级维度的key
     * @return
     */
    public List<SaveModel> findLineChartDateQuotaLevel2NoSlaveKey1(String startDate, String endDate, String area, int level, String index, String timelevel, String interval, String slaveKey2) throws Exception {
        List list = findLineChartDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, interval, null, slaveKey2);
        return list;
    }
    public List<SaveModel> findLineChartDateQuotaLevel2OnlySlaveKey2(String startDate, String endDate, String area, int level, String index, String timelevel, String interval, String slaveKey2) throws Exception {
        List list = findLineChartDateQuotaLevel4(startDate, endDate, area, level, index, timelevel, interval, null, slaveKey2);
        return list;
    }

    /**
     * 折线图
     * 2级维度只根绝第一个指标聚合
     * 查询某个2级维度的某个1级维度和2级维度下的折线图  例如查询65岁以上的高血压患者
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量（按照年度）
     * @param interval  1日 2周 3月 （按照日周月聚合）
     * @param slaveKey1 一级维度的key
     * @return
     */
    public List<SaveModel> findLineChartDateQuotaLevel2NoSlaveKey2(String startDate, String endDate, String area, int level, String index, String timelevel, String interval, String slaveKey1) throws Exception {
        List list = findLineChartDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, interval, slaveKey1, null);
        return list;
    }

    /**
     * 折线图
     * 2级维度只根绝第一个指标聚合
     * 查询某个2级维度的某个1级维度和2级维度下的折线图  例如查询65岁以上的高血压患者
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量（按照年度）
     * @param interval  1日 2周 3月 （按照日周月聚合）
     * @return
     */
    public List<SaveModel> findLineChartDateQuotaLevel2NoSlaveKey1NoSlaveKey2(String startDate, String endDate, String area, int level, String index, String timelevel, String interval) throws Exception {
        List list = findLineChartDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, interval, null, null);
        return list;
    }

    /**
     * 列表
     * 0级维度
     * 查询某一天某个0级维度的指标列表
     *
     * @param quotaDate 时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量（按照年度）
     * @param lowLevel  下一级区域等级   1 省 2 市 3 区县 4 机构 5团队
     * @return
     * @throws Exception
     */
    public List<SaveModel> findListDateQuotaLevel0(String quotaDate, String area, int level, String index, String timelevel, String lowLevel) throws Exception {
        List list = findDateQuotaLevel0(quotaDate, quotaDate, area, level, index, timelevel, null, lowLevel);
        return list;
    }

    /**
     * 列表
     * 0级维度
     * 查询某个区间某个0级维度的指标列表
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量（按照年度）
     * @param lowLevel  下一级区域等级   1 省 2 市 3 区县 4 机构 5团队.
     * @return
     * @throws Exception
     */
    public List<SaveModel> findListDateQuotaLevel0(String startDate, String endDate, String area, int level, String index, String timelevel, String lowLevel) throws Exception {
        List list = findDateQuotaLevel0(startDate, endDate, area, level, index, timelevel, null, lowLevel);
        return list;
    }

    /**
     * 列表
     * 1级维度
     * 查询某个1级维度的某个1级维度下的列表 例如查询65岁以上患者
     *
     * @param quotaDate 时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量（按照年度）
     * @param lowLevel  下一级区域等级   1 省 2 市 3 区县 4 机构 5团队
     * @param slaveKey1 一级维度的key
     * @return
     */
    public List<SaveModel> findListDateQuotaLevel1(String quotaDate, String area, int level, String index, String timelevel, String lowLevel, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel1(quotaDate, quotaDate, area, level, index, timelevel, slaveKey1, null, lowLevel);
        return list;
    }

    /**
     * 列表
     * 1级维度
     * 查询某个1级维度的某个1级维度下的列表 例如查询65岁以上患者
     *
     * @param quotaDate 时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量（按照年度）
     * @param lowLevel  下一级区域等级   1 省 2 市 3 区县 4 机构 5团队
     * @return
     */
    public List<SaveModel> findListDateQuotaLevel1NoSlaveKey1(String quotaDate, String area, int level, String index, String timelevel, String lowLevel) throws Exception {
        List list = findDateQuotaLevel1(quotaDate, quotaDate, area, level, index, timelevel, null, null, lowLevel);
        return list;
    }

    /**
     * 列表
     * 1级维度
     * 查询某个区间某个1级维度的某个1级维度下的列表 例如查询65岁以上患者
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量（按照年度）
     * @param lowLevel  下一级区域等级   1 省 2 市 3 区县 4 机构 5团队
     * @param slaveKey1 一级维度的key
     * @return
     */
    public List<SaveModel> findListDateQuotaLevel1(String startDate, String endDate, String area, int level, String index, String timelevel, String lowLevel, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, slaveKey1, null, lowLevel);
        return list;
    }

    /**
     * 列表
     * 2级维度
     * 查询某个2级维度的某个1级维度和2级维度下的列表  例如查询65岁以上的高血压患者
     *
     * @param quotaDate 时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量（按照年度）
     * @param lowLevel  下一级区域等级   1 省 2 市 3 区县 4 机构 5团队
     * @param slaveKey1 一级维度的key
     * @param slaveKey2 二级维度的key
     * @return
     */
    public List<SaveModel> findListDateQuotaLevel2(String quotaDate, String area, int level, String index, String timelevel, String lowLevel, String slaveKey1, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, slaveKey1, slaveKey2, null, lowLevel);
        return list;
    }

    public List<SaveModel> findListDateQuotaLevel2NoSlaveKey1(String quotaDate, String area, int level, String index, String timelevel, String lowLevel, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, null, slaveKey2, null, lowLevel);
        return list;
    }

    public List<SaveModel> findListDateQuotaLevel2NoSlaveKey2(String quotaDate, String area, int level, String index, String timelevel, String lowLevel, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, slaveKey1, null, null, lowLevel);
        return list;
    }

    public List<SaveModel> findListDateQuotaLevel2NoSlaveKey1NoSlaveKey2(String quotaDate, String area, int level, String index, String timelevel, String lowLevel) throws Exception {
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, null, null, null, lowLevel);
        return list;
    }

    /**
     * 列表
     * 2级维度
     * 查询某个区间某个2级维度的某个1级维度和2级维度下的列表  例如查询65岁以上的高血压患者
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量（按照年度）
     * @param lowLevel  下一级区域等级   1 省 2 市 3 区县 4 机构 5团队
     * @param slaveKey1 一级维度的key
     * @param slaveKey2 二级维度的key
     * @return
     */
    public List<SaveModel> findListDateQuotaLevel2(String startDate, String endDate, String area, int level, String index, String timelevel, String lowLevel, String slaveKey1, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, slaveKey1, slaveKey2, null, lowLevel);
        return list;
    }

    /**
     * 将参数转换成需要的SaveModel里的标识
     *
     * @param level 等级  5 市  4区  3社区 2科室 1医生
     *              转换后的level  等级  2 市  3区  4医院 5、科室 6医生
     * @return
     * @author zhangdan
     * @time 2017-10-18
     */
    public int changeLevel(int level) {
        int resultLevel = 0;
        if (level == 1) {
            //团队转成SaveModel里的标识
            resultLevel = Integer.valueOf(SaveModel.doctorLevel);
        }else if (level == 2) {
            //团队转成SaveModel里的标识
            resultLevel = Integer.valueOf(SaveModel.deptLevel);
        } else if (level == 3) {
            //社区转成SaveModel里的标识
            resultLevel = Integer.valueOf(SaveModel.OrgLevel);
        } else if (level == 4) {
            //区转成SaveModel里的标识
            resultLevel = Integer.valueOf(SaveModel.townLevel);
        } else if (level == 5) {
            //市转成SaveModel里的标识
            resultLevel = Integer.valueOf(SaveModel.cityLevel);
        }
        if (resultLevel == 0) {
            resultLevel = level;
        }
        return resultLevel;
    }

    public List<Map<String, Object>> excuteDataModel(String sql) {
        List<Map<String, Object>> returnModels = new ArrayList<>();
        try {
            SQLExprParser parser = new ElasticSqlExprParser(sql);
            SQLExpr expr = parser.expr();
            SQLQueryExpr queryExpr = (SQLQueryExpr) expr;
//            if (parser.getLexer().token() != Token.EOF) {
//                throw new ParserException("illegal sql expr : " + sql);
//            }
            Select select = null;
            select = new SqlParser().parseSelect(queryExpr);

            //通过抽象语法树，封装成自定义的Select，包含了select、from、where group、limit等
            AggregationQueryAction action = null;
            DefaultQueryAction queryAction = null;
            SqlElasticSearchRequestBuilder requestBuilder = null;
            if (select.isAgg) {
                //包含计算的的排序分组的
                action = new AggregationQueryAction(elasticFactory.getTransportClient(), select);
                requestBuilder = action.explain();
            } else {
                //封装成自己的Select对象
                Client client = elasticFactory.getTransportClient();
                queryAction = new DefaultQueryAction(client, select);
                requestBuilder = queryAction.explain();
            }
            SearchResponse response = (SearchResponse) requestBuilder.get();
            Object queryResult = null;
            if (sql.toUpperCase().indexOf("GROUP") != -1 || sql.toUpperCase().indexOf("SUM") != -1) {
                queryResult = response.getAggregations();
            } else {
                queryResult = response.getHits();
            }
            ObjectResult temp = new ObjectResultsExtractor(true, true, true).extractResults(queryResult, true);
            List<String> heads = temp.getHeaders();
            temp.getLines().stream().forEach(one -> {
                try {
                    Map<String, Object> oneMap = new HashMap<String, Object>();
                    for (int i = 0; i < one.size(); i++) {
                        String key = null;
                        Object value = one.get(i);
                        key = heads.get(i);
                        oneMap.put(key, value);
                    }
                    returnModels.add(oneMap);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnModels;
    }

    /**
     * 将slaveKey1作为筛选条件而不进行group by
     *
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @param area      区域code
     * @param level     等级
     * @param index     指标
     * @param timeLevel 1增量 2到达量
     * @param interval  1日 2周 3月
     * @param lowLevel  下一级区域等级
     * @return
     * @throws Exception
     */
    public List findDateQuotaLevel0BySlaveKey1(String startDate, String endDate, String area, int level, String index, String timeLevel, String interval, String lowLevel, String slaveKey1) throws Exception {

        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
            } else {
                startDate = changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = changeTime(endDate);
            } else {
                endDate = changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }

        if (SaveModel.deptLevel.equals(low_level)) {
            sql.append("select dept,deptName,sum(result1) result1, sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by dept,deptName");
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital,hospitalName,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by hospital,hospitalName");
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town,townName,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by town,townName");
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city,cityName,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by city,cityName");
        }else if (SaveModel.doctorLevel.equals(low_level)) {
            sql.append("select doctor,doctorName,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by doctor,doctorName ");
        }

        if (StringUtils.isNotEmpty(area)) {

            if (SaveModel.deptLevel.equals(level + "")) {
                sql.append(" dept='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }else if (SaveModel.doctorLevel.equals(level + "")) {
                sql.append(" doctor='" + area + "'");
            }
            sql.append(" and ");
        }
//        sql.append(" quotaCode='" + index + "'  ");
        sql.append(" quotaCode in(" + index + ")  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='6'");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }
        if (StringUtils.isNotEmpty(slaveKey1) && !commonParams.equals(slaveKey1)) {
            String[] temp = slaveKey1.split(",");
            String slaveKey1Temp = "";
            for(String one : temp){
                slaveKey1Temp += ",'"+one+"'";
            }
            sql.append(" and slaveKey1 in ("+slaveKey1Temp.substring(1)+")");
        }

        //根据时间维度分组
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00','alias'='quotaDate') ");
            }
        }
        sql.append(groupBy);

        return excute(sql.toString(), SaveModel.class, "", "");
    }

    public List searchBySql(String sql){
        return excute(sql, SaveModel.class, "", "");
    }
}
