package com.yihu.jw.es.service;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.area.dao.BaseCityDao;
import com.yihu.jw.dict.dao.DictHospitalDeptDao;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.entity.base.dict.DictHospitalDeptDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
import com.yihu.jw.entity.base.org.BaseOrgDO;
import com.yihu.jw.es.util.ElasticsearchUtil;
import com.yihu.jw.es.util.SaveModel;
import com.yihu.jw.evaluate.score.service.BaseEvaluateScoreService;
import com.yihu.jw.org.dao.BaseOrgDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import org.apache.commons.lang3.StringUtils;
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.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by wangzhinan on 2019/12/3.
 */
@Service
@Transactional
public class StatisticsEsService {

    Logger logger = LoggerFactory.getLogger(StatisticsEsService.class);

    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BaseDoctorHospitalDao doctorHospitalDao;
    @Autowired
    private DictHospitalDeptDao hospitalDeptDao;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private BaseOrgDao orgDao;
    @Autowired
    private BaseCityDao cityDao;
    @Autowired
    private BaseEvaluateScoreService baseEvaluateScoreService;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Value("${wechat.id}")
    private String wxId;
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");


    /**
     * 问诊量
     * @param startDate
     * @param endDate
     * @param area
     * @param level 2 市  3区  4医院 5、科室 6医生
     * @param index
     * @param level2_type
     * @return
     * @throws Exception
     */
    public JSONObject getTotalAmount(String startDate, String endDate, String area, int level, String index, String level2_type) throws Exception {
        //问诊量
        SaveModel saveModel = null;
        //开方量
        SaveModel saveModel1 = null;
        //收入
        SaveModel saveModel2 = null;
        //昨天收入;
        SaveModel saveModel3 = null;
        //上周今天收入;
        SaveModel saveModel4 = null;
        SaveModel saveModel7 = null;
        String[] indexes = index.split(",");
        if (StringUtils.isNotEmpty(level2_type)) {
            saveModel = elasticsearchUtil.findOneDateQuotaLevel1(endDate, endDate, area, level, indexes[0], SaveModel.timeLevel_DDL, level2_type);
            saveModel1 = elasticsearchUtil.findOneDateQuotaLevel1(endDate, endDate, area, level, indexes[1], SaveModel.timeLevel_DDL, level2_type);
            saveModel2 = elasticsearchUtil.findOneDateQuotaLevel1(endDate, endDate, area, level, indexes[2]+",21", SaveModel.timeLevel_DDL,level2_type);
        } else {
            saveModel = elasticsearchUtil.findOneDateQuotaLevel0(endDate, endDate, area, level, indexes[0], SaveModel.timeLevel_DDL);
            saveModel1 = elasticsearchUtil.findOneDateQuotaLevel0(endDate, endDate, area, level, indexes[1], SaveModel.timeLevel_DDL);
            saveModel2 = elasticsearchUtil.findOneDateQuotaLevel0(endDate, endDate, area, level, indexes[2]+",21", SaveModel.timeLevel_DDL);
        }
        JSONObject object = new JSONObject();
        String yesterday = DateUtil.getNextDay(endDate, -1);//昨天
        String lastDay = DateUtil.getNextDay(endDate, -7);//上周的今天
        String weekFirstDay = DateUtil.getMondayOfThisWeek();//周一
        String weekLastDay = DateUtil.getSundayOfThisWeek();//周日
        JSONArray array = dateTotalStatistics2(weekFirstDay,weekLastDay,area,level,indexes[2]+",21",null,SaveModel.timeLevel_ZL,null);//本周量
        Double prices = 0.0;
        for (int i=0;i<array.size();i++){
            JSONObject jsonObject = array.getJSONObject(i);
            prices +=jsonObject.getDouble("num");
        }
        Double num = prices/array.size();
        DecimalFormat df = new DecimalFormat("0.00");
        String str = df.format(num);
        object.put("dayPrice",str);//日均收入
        saveModel3 = elasticsearchUtil.findOneDateQuotaLevel0(yesterday, yesterday, area, level, indexes[2]+",21", SaveModel.timeLevel_DDL);
        saveModel4 = elasticsearchUtil.findOneDateQuotaLevel0(lastDay, lastDay, area, level, indexes[2]+",21", SaveModel.timeLevel_DDL);
        object.put("outPatientCount",saveModel.getResult2().longValue());//问诊量
        object.put("prescriptionCount",saveModel1.getResult2().longValue());//开方量
        object.put("priceTotal",saveModel2.getResult1().longValue());//总收入
        object.put("priceDayRate",baseEvaluateScoreService.judgeScore(saveModel2.getResult1().doubleValue(),saveModel3.getResult1().doubleValue()));
        object.put("priceWeekRate",baseEvaluateScoreService.judgeScore(saveModel2.getResult1().doubleValue(),saveModel4.getResult1().doubleValue()));
        String prescriptionRate = getRange(saveModel1.getResult2().intValue(), saveModel.getResult2().intValue(),0);
        object.put("prescriptionRate",prescriptionRate);//开方率
        String startTime = DateUtil.getStringDateShort()+" 00:00:00";
        String endTime = DateUtil.getStringDateShort() +" 23:59:59";
        String sql = "";
        if("xm_ykyy_wx".equalsIgnoreCase(wxId)){
            sql = "select count(*) as \"total\" from wlyy_consult_outpatient_info o where  o.create_time >= to_date('"+startTime+"','yyyy-mm-dd hh24:mi:ss') and o.create_time <= to_date('"+endTime+"','yyyy-mm-dd hh24:mi:ss')";
        }else {
            sql = "select count(*) as \"total\" from wlyy_consult_outpatient_info o where  o.create_time >='"+startTime+"' and o.create_time <='"+endTime+"'";
        }
        if (level==4){
            sql += " and o.doctor IN (SELECT doctor_code as \"doctor_code\" FROM `base_doctor_hospital` dh where dh.org_code ='"+area+"' and dh.del=1)";
        }if (level==2){
            sql += " AND 1=1 ";
        }else if (level==5){
            sql += " and o.doctor IN (SELECT doctor_code as \"doctor_code\" FROM `base_doctor_hospital` dh where dh.dept_code ='"+area+"' and dh.del=1)";
        }else if (level==6){
            sql +=" and o.doctor='"+area+"'";
        }
        List<Map<String,Object>> rstotal = jdbcTemplate.queryForList(sql);
        Long count = 0L;
        if(rstotal!=null&&rstotal.size()>0){
            count =Long.parseLong(rstotal.get(0).get("total").toString()) ;
        }
        object.put("todayOutPatientCount",count);//今日问诊量
        Map<String, Object> scoreAndPercentage = baseEvaluateScoreService.getScoreAndPercentage(area, level);
        object.put("totalAvgScore",scoreAndPercentage.get("totalAvgScore"));//服务总评分
        object.put("weekJudge",scoreAndPercentage.get("weekJudge"));//周同比
        object.put("dayJudge",scoreAndPercentage.get("dayJudge"));//日环比

        return object;
    }


    /**
     * 按日期柱状图
     *
     *
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param level2_type
     * @return
     * @throws Exception
     */
    public JSONObject getOutPatientLine(String startDate, String endDate, String area, int level, String index,int interval, String level2_type) throws Exception {
        logger.info("service index:"+index+" and level2_type:"+level2_type+" and level:"+level);
        //问诊量
        JSONObject object = new JSONObject();
        if (interval==1){
            JSONArray array = dateTotalStatistics2(startDate,endDate,area,level,index,null,SaveModel.timeLevel_ZL,null);
            object.put("data",array);
            JSONArray array1 = dateTotalStatistics2(startDate,endDate,area,level,"5","1",SaveModel.timeLevel_ZL,null);
            object.put("specialistData",array1);
            JSONArray array2 = dateTotalStatistics2(startDate,endDate,area,level,"12","9",SaveModel.timeLevel_ZL,null);
            object.put("topicData",array2);
            JSONArray array3 = dateTotalStatistics2(startDate,endDate,area,level,"14","12",SaveModel.timeLevel_ZL,null);
            object.put("synergyData",array3);
            JSONArray array4 = dateTotalStatistics2(startDate,endDate,area,level,"16","16",SaveModel.timeLevel_ZL,null);
            object.put("vedioData",array4);
            JSONArray array5 = dateTotalStatistics2(startDate,endDate,area,level,"12","1",SaveModel.timeLevel_ZL,null);
            object.put("twzxData",array5);
            JSONArray array6 = dateTotalStatistics2(startDate,endDate,area,level,"16","17",SaveModel.timeLevel_ZL,null);
            object.put("spzxData",array6);
        }else if (interval==2){

            JSONArray array = weekTotalStatistics7(startDate,endDate,area,level,index,null,SaveModel.timeLevel_ZL);
            object.put("data",array);
            JSONArray array1 = weekTotalStatistics7(startDate,endDate,area,level,"5","1",SaveModel.timeLevel_ZL);
            object.put("specialistData",array1);
            JSONArray array2 = weekTotalStatistics7(startDate,endDate,area,level,"12","9",SaveModel.timeLevel_ZL);
            object.put("topicData",array2);
            JSONArray array3 = weekTotalStatistics7(startDate,endDate,area,level,"14","12",SaveModel.timeLevel_ZL);
            object.put("synergyData",array3);
            JSONArray array4 = weekTotalStatistics7(startDate,endDate,area,level,"16","16",SaveModel.timeLevel_ZL);
            object.put("vedioData",array4);
            JSONArray array5 = weekTotalStatistics7(startDate,endDate,area,level,"12","1",SaveModel.timeLevel_ZL);
            object.put("twzxData",array5);
            JSONArray array6 = weekTotalStatistics7(startDate,endDate,area,level,"16","17",SaveModel.timeLevel_ZL);
            object.put("spzxData",array6);
        }else if (interval==3){
            JSONArray array = monthTotalStatistics2(startDate,endDate,area,level,index,null,SaveModel.timeLevel_ZL,null);
            object.put("data",array);
            JSONArray array1 = monthTotalStatistics2(startDate,endDate,area,level,"5","1",SaveModel.timeLevel_ZL,null);
            object.put("specialistData",array1);
            JSONArray array2 = monthTotalStatistics2(startDate,endDate,area,level,"12","9",SaveModel.timeLevel_ZL,null);
            object.put("topicData",array2);
            JSONArray array3 = monthTotalStatistics2(startDate,endDate,area,level,"14","12",SaveModel.timeLevel_ZL,null);
            object.put("synergyData",array3);
            JSONArray array4 = monthTotalStatistics2(startDate,endDate,area,level,"16","16",SaveModel.timeLevel_ZL,null);
            object.put("vedioData",array4);
            JSONArray array5 = monthTotalStatistics2(startDate,endDate,area,level,"12","1",SaveModel.timeLevel_ZL,null);
            object.put("twzxData",array5);
            JSONArray array6 = monthTotalStatistics2(startDate,endDate,area,level,"16","17",SaveModel.timeLevel_ZL,null);
            object.put("spzxData",array6);
        }
        if (StringUtils.isNoneBlank(level2_type)){

            //问诊量表格
            //专家咨询数量
/*
            List<SaveModel> specialistSaveModels = elasticsearchUtil.findDateQuotaLevel0(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL,null,level2_type);
*/
            //协同门诊
            List<SaveModel> syngySaveModels = elasticsearchUtil.findDateQuotaLevel1(startDate, endDate, area, level, "14", SaveModel.timeLevel_ZL,"12",null,level2_type);
            //图文复诊
            List<SaveModel> topicSaveModels = elasticsearchUtil.findDateQuotaLevel1(startDate, endDate, area, level, "12", SaveModel.timeLevel_ZL,"9",null,level2_type);
            ///视频复诊
            List<SaveModel> vedioSaveModels = elasticsearchUtil.findDateQuotaLevel1(startDate, endDate, area, level, "16", SaveModel.timeLevel_ZL,"16",null,level2_type);
            ///图文咨询
            List<SaveModel> twzxSaveModels = elasticsearchUtil.findDateQuotaLevel1(startDate, endDate, area, level, "12", SaveModel.timeLevel_ZL,"1",null,level2_type);
            ///视频咨询
            List<SaveModel> spzxSaveModels = elasticsearchUtil.findDateQuotaLevel1(startDate, endDate, area, level, "16", SaveModel.timeLevel_ZL,"17",null,level2_type);

            JSONArray array = new JSONArray();
            List<String> list = new ArrayList<>();

            for (SaveModel saveModel:syngySaveModels){
                if (level2_type.equals(SaveModel.OrgLevel)){
                    if (StringUtils.isNoneBlank(saveModel.getHospital())){
                        list.add(saveModel.getHospital());
                    }

                }else if (level2_type.equals(SaveModel.deptLevel)){
                    if (StringUtils.isNoneBlank(saveModel.getDept())){
                        list.add(saveModel.getDept());
                    }

                }else if (level2_type.equals(SaveModel.doctorLevel)){
                    if (StringUtils.isNoneBlank(saveModel.getDoctor())){
                        list.add(saveModel.getDoctor());
                    }

                }
            }
            for (int i=0;i<list.size();i++){
                String code = list.get(i);
                JSONObject jsonObject = new JSONObject();
                Double specialist = 0.0;
                Double topic = 0.0;
                Double vedio =0.0;
                Double synegy =0.0;
                Double topicZJ =0.0;
                Double vedioZJ = 0.0;
                if (index.equalsIgnoreCase("3")){
                    specialist = 0.0;
                }/*else if (index.equalsIgnoreCase("5")){
                    for (SaveModel saveModel:specialistSaveModels){
                        if (level2_type.equals(SaveModel.OrgLevel)){
                            if (StringUtils.isNoneBlank(saveModel.getHospital())&&code.equalsIgnoreCase(saveModel.getHospital())){
                                jsonObject.put("code",code);
                                jsonObject.put("name",saveModel.getHospitalName());
                                jsonObject.put("specialist",saveModel.getResult1());
                                specialist = saveModel.getResult1();
                                break;
                            }
                        }else if (level2_type.equals(SaveModel.deptLevel)){
                            if (StringUtils.isNoneBlank(saveModel.getDept())&&code.equalsIgnoreCase(saveModel.getDept())){
                                jsonObject.put("code",code);
                                jsonObject.put("name",saveModel.getDeptName());
                                jsonObject.put("specialist",saveModel.getResult1());
                                specialist = saveModel.getResult1();
                                break;
                            }
                        }else if (level2_type.equals(SaveModel.doctorLevel)){
                            if (StringUtils.isNoneBlank(saveModel.getDoctor())&&code.equalsIgnoreCase(saveModel.getDoctor())){

                                if (level==6){
                                    List<BaseDoctorHospitalDO> doctorHospitalDOS = doctorHospitalDao.findByDoctorCode(area);
                                    if (doctorHospitalDOS!=null&&doctorHospitalDOS.size()!=0){
                                        BaseDoctorHospitalDO doctorHospitalDO = doctorHospitalDOS.get(0);
                                        jsonObject.put("code",doctorHospitalDO.getDeptCode());
                                        jsonObject.put("name",doctorHospitalDO.getDeptName());
                                    }
                                }else {
                                    DictHospitalDeptDO dictHospitalDeptDO =  hospitalDeptDao.findByCode(area);
                                    jsonObject.put("code",area);
                                    jsonObject.put("name",dictHospitalDeptDO.getName());
                                }

                                jsonObject.put("doctorCode",code);
                                BaseDoctorDO doctorDO = doctorDao.findById(code);
                                if (doctorDO!=null){
                                    jsonObject.put("doctorJob",doctorDO.getJobTitleName());
                                }else {
                                    jsonObject.put("doctorJob",null);
                                }
                                jsonObject.put("doctorName",saveModel.getDoctorName());
                                jsonObject.put("specialist",saveModel.getResult1());
                                specialist = saveModel.getResult1();
                                break;
                            }
                        }
                    }
                }*/

                for (SaveModel saveModel:syngySaveModels){
                    if (level2_type.equals(SaveModel.OrgLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getHospital())&&code.equalsIgnoreCase(saveModel.getHospital())){
                            jsonObject.put("code",code);
                            jsonObject.put("name",saveModel.getHospitalName());
                            jsonObject.put("synegy",saveModel.getResult1());
                            synegy = saveModel.getResult1();
                            break;
                        }
                    }else if (level2_type.equals(SaveModel.deptLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getDept())&&code.equalsIgnoreCase(saveModel.getDept())){
                            jsonObject.put("code",code);
                            jsonObject.put("name",saveModel.getDeptName());
                            jsonObject.put("synegy",saveModel.getResult1());
                            synegy = saveModel.getResult1();
                            break;
                        }
                    }else if (level2_type.equals(SaveModel.doctorLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getDoctor())&&code.equalsIgnoreCase(saveModel.getDoctor())){
                            if (level==6){
                                List<BaseDoctorHospitalDO> doctorHospitalDOS = doctorHospitalDao.findByDoctorCode(area);
                                if (doctorHospitalDOS!=null&&doctorHospitalDOS.size()!=0){
                                    BaseDoctorHospitalDO doctorHospitalDO = doctorHospitalDOS.get(0);
                                    jsonObject.put("code",doctorHospitalDO.getDeptCode());
                                    jsonObject.put("name",doctorHospitalDO.getDeptName());
                                }
                            }else {
                                DictHospitalDeptDO dictHospitalDeptDO =  hospitalDeptDao.findByCode(area);
                                jsonObject.put("code",area);
                                jsonObject.put("name",dictHospitalDeptDO.getName());
                            }
                            BaseDoctorDO doctorDO = doctorDao.findById(code);
                            if (doctorDO!=null){
                                jsonObject.put("doctorJob",doctorDO.getJobTitleName());
                            }else {
                                jsonObject.put("doctorJob",null);
                            }

                            jsonObject.put("doctorCode",code);
                            jsonObject.put("doctorName",saveModel.getDoctorName());
                            jsonObject.put("synegy",saveModel.getResult1());
                            synegy = saveModel.getResult1();
                            break;
                        }
                    }
                }
                for (SaveModel saveModel:topicSaveModels){
                    if (level2_type.equals(SaveModel.OrgLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getHospital())&&code.equalsIgnoreCase(saveModel.getHospital())){
                            jsonObject.put("code",code);
                            jsonObject.put("name",saveModel.getHospitalName());
                            jsonObject.put("topic",saveModel.getResult1());
                            topic = saveModel.getResult1();
                            break;
                        }
                    }else if (level2_type.equals(SaveModel.deptLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getDept())&&code.equalsIgnoreCase(saveModel.getDept())){
                            jsonObject.put("code",code);
                            jsonObject.put("name",saveModel.getDeptName());
                            jsonObject.put("topic",saveModel.getResult1());
                            topic = saveModel.getResult1();
                            break;
                        }
                    }else if (level2_type.equals(SaveModel.doctorLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getDoctor())&&code.equalsIgnoreCase(saveModel.getDoctor())){
                            if (level==6){
                                List<BaseDoctorHospitalDO> doctorHospitalDOS = doctorHospitalDao.findByDoctorCode(area);
                                if (doctorHospitalDOS!=null&&doctorHospitalDOS.size()!=0){
                                    BaseDoctorHospitalDO doctorHospitalDO = doctorHospitalDOS.get(0);
                                    jsonObject.put("code",doctorHospitalDO.getDeptCode());
                                    jsonObject.put("name",doctorHospitalDO.getDeptName());
                                }
                            }else {
                                DictHospitalDeptDO dictHospitalDeptDO =  hospitalDeptDao.findByCode(area);
                                jsonObject.put("code",area);
                                jsonObject.put("name",dictHospitalDeptDO.getName());
                            }
                            BaseDoctorDO doctorDO = doctorDao.findById(code);
                            if (doctorDO!=null){
                                jsonObject.put("doctorJob",doctorDO.getJobTitleName());
                            }else {
                                jsonObject.put("doctorJob",null);
                            }
                            jsonObject.put("doctorCode",code);
                            jsonObject.put("doctorName",saveModel.getDoctorName());
                            jsonObject.put("topic",saveModel.getResult1());
                            topic = saveModel.getResult1();
                            break;
                        }
                    }
                }
                for (SaveModel saveModel:vedioSaveModels){
                    if (level2_type.equals(SaveModel.OrgLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getHospital())&&code.equalsIgnoreCase(saveModel.getHospital())){
                            jsonObject.put("code",code);
                            jsonObject.put("name",saveModel.getHospitalName());
                            jsonObject.put("vedio",saveModel.getResult1());
                            vedio = saveModel.getResult1();
                            break;
                        }
                    }else if (level2_type.equals(SaveModel.deptLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getDept())&&code.equalsIgnoreCase(saveModel.getDept())){
                            jsonObject.put("code",code);
                            jsonObject.put("name",saveModel.getDeptName());
                            jsonObject.put("vedio",saveModel.getResult1());
                            vedio = saveModel.getResult1();
                            break;
                        }
                    }else if (level2_type.equals(SaveModel.doctorLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getDoctor())&&code.equalsIgnoreCase(saveModel.getDoctor())){
                            if (level==6){
                                List<BaseDoctorHospitalDO> doctorHospitalDOS = doctorHospitalDao.findByDoctorCode(area);
                                if (doctorHospitalDOS!=null&&doctorHospitalDOS.size()!=0){
                                    BaseDoctorHospitalDO doctorHospitalDO = doctorHospitalDOS.get(0);
                                    jsonObject.put("code",doctorHospitalDO.getDeptCode());
                                    jsonObject.put("name",doctorHospitalDO.getDeptName());
                                }
                            }else {
                                DictHospitalDeptDO dictHospitalDeptDO =  hospitalDeptDao.findByCode(area);
                                jsonObject.put("code",area);
                                jsonObject.put("name",dictHospitalDeptDO.getName());
                            }
                            jsonObject.put("doctorCode",code);
                            BaseDoctorDO doctorDO = doctorDao.findById(code);
                            if (doctorDO!=null){
                                jsonObject.put("doctorJob",doctorDO.getJobTitleName());
                            }else {
                                jsonObject.put("doctorJob",null);
                            }
                            jsonObject.put("doctorName",saveModel.getDoctorName());
                            jsonObject.put("vedio",saveModel.getResult1());
                            vedio = saveModel.getResult1();
                            break;
                        }
                    }
                }
                for (SaveModel saveModel:twzxSaveModels){
                    if (level2_type.equals(SaveModel.OrgLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getHospital())&&code.equalsIgnoreCase(saveModel.getHospital())){
                            jsonObject.put("code",code);
                            jsonObject.put("name",saveModel.getHospitalName());
                            jsonObject.put("topicZJ",saveModel.getResult1());
                            topicZJ = saveModel.getResult1();
                            break;
                        }
                    }else if (level2_type.equals(SaveModel.deptLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getDept())&&code.equalsIgnoreCase(saveModel.getDept())){
                            jsonObject.put("code",code);
                            jsonObject.put("name",saveModel.getDeptName());
                            jsonObject.put("topicZJ",saveModel.getResult1());
                            topicZJ = saveModel.getResult1();
                            break;
                        }
                    }else if (level2_type.equals(SaveModel.doctorLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getDoctor())&&code.equalsIgnoreCase(saveModel.getDoctor())){
                            if (level==6){
                                List<BaseDoctorHospitalDO> doctorHospitalDOS = doctorHospitalDao.findByDoctorCode(area);
                                if (doctorHospitalDOS!=null&&doctorHospitalDOS.size()!=0){
                                    BaseDoctorHospitalDO doctorHospitalDO = doctorHospitalDOS.get(0);
                                    jsonObject.put("code",doctorHospitalDO.getDeptCode());
                                    jsonObject.put("name",doctorHospitalDO.getDeptName());
                                }
                            }else {
                                DictHospitalDeptDO dictHospitalDeptDO =  hospitalDeptDao.findByCode(area);
                                jsonObject.put("code",area);
                                jsonObject.put("name",dictHospitalDeptDO.getName());
                            }
                            jsonObject.put("doctorCode",code);
                            BaseDoctorDO doctorDO = doctorDao.findById(code);
                            if (doctorDO!=null){
                                jsonObject.put("doctorJob",doctorDO.getJobTitleName());
                            }else {
                                jsonObject.put("doctorJob",null);
                            }
                            jsonObject.put("doctorName",saveModel.getDoctorName());
                            jsonObject.put("topicZJ",saveModel.getResult1());
                            topicZJ = saveModel.getResult1();
                            break;
                        }
                    }
                }
                for (SaveModel saveModel:spzxSaveModels){
                    if (level2_type.equals(SaveModel.OrgLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getHospital())&&code.equalsIgnoreCase(saveModel.getHospital())){
                            jsonObject.put("code",code);
                            jsonObject.put("name",saveModel.getHospitalName());
                            jsonObject.put("vedioZJ",saveModel.getResult1());
                            vedioZJ = saveModel.getResult1();
                            break;
                        }
                    }else if (level2_type.equals(SaveModel.deptLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getDept())&&code.equalsIgnoreCase(saveModel.getDept())){
                            jsonObject.put("code",code);
                            jsonObject.put("name",saveModel.getDeptName());
                            jsonObject.put("vedioZJ",saveModel.getResult1());
                            vedioZJ = saveModel.getResult1();
                            break;
                        }
                    }else if (level2_type.equals(SaveModel.doctorLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getDoctor())&&code.equalsIgnoreCase(saveModel.getDoctor())){
                            if (level==6){
                                List<BaseDoctorHospitalDO> doctorHospitalDOS = doctorHospitalDao.findByDoctorCode(area);
                                if (doctorHospitalDOS!=null&&doctorHospitalDOS.size()!=0){
                                    BaseDoctorHospitalDO doctorHospitalDO = doctorHospitalDOS.get(0);
                                    jsonObject.put("code",doctorHospitalDO.getDeptCode());
                                    jsonObject.put("name",doctorHospitalDO.getDeptName());
                                }
                            }else {
                                DictHospitalDeptDO dictHospitalDeptDO =  hospitalDeptDao.findByCode(area);
                                jsonObject.put("code",area);
                                jsonObject.put("name",dictHospitalDeptDO.getName());
                            }
                            jsonObject.put("doctorCode",code);
                            BaseDoctorDO doctorDO = doctorDao.findById(code);
                            if (doctorDO!=null){
                                jsonObject.put("doctorJob",doctorDO.getJobTitleName());
                            }else {
                                jsonObject.put("doctorJob",null);
                            }
                            jsonObject.put("doctorName",saveModel.getDoctorName());
                            jsonObject.put("vedioZJ",saveModel.getResult1());
                            vedioZJ = saveModel.getResult1();
                            break;
                        }
                    }
                }
                Double total1 = topic+vedio ;//图文和视频总和
                Double total = topic+vedio+synegy+specialist+topicZJ+vedioZJ;//总和
                Double total2 = topicZJ+vedioZJ ;//图文咨询和视频咨询总和
                jsonObject.put("total1",total1);//图文和视频总和
                jsonObject.put("total",total);//总和
                jsonObject.put("total2",total2);//图文咨询和视频咨询总和
                array.add(jsonObject);
            }
            object.put("excelData",array);
        }
        return object;
    }


    public JSONObject getOutPatientPriceLine(String startDate, String endDate, String area, int level, String index,int interval, String level2_type) throws Exception {
        logger.info("service index:"+index+" and level2_type:"+level2_type+" and level:"+level);
        //问诊量
        JSONObject object = new JSONObject();
        if (interval==1){
            JSONArray array = dateTotalStatistics3(startDate,endDate,area,level,index,null,SaveModel.timeLevel_ZL,null);
            object.put("data",array);
            JSONArray array1 = dateTotalStatistics3(startDate,endDate,area,level,index,"3",SaveModel.timeLevel_ZL,null);
            object.put("specialistData",array1);
            JSONArray array2 = dateTotalStatistics3(startDate,endDate,area,level,index,"1",SaveModel.timeLevel_ZL,"1");
            object.put("topicData",array2);
            JSONArray array3 = dateTotalStatistics3(startDate,endDate,area,level,index,"2",SaveModel.timeLevel_ZL,null);
            object.put("synergyData",array3);
            JSONArray array4 = dateTotalStatistics3(startDate,endDate,area,level,index,"1",SaveModel.timeLevel_ZL,"2");
            object.put("vedioData",array4);
            JSONArray array5 = dateTotalStatistics3(startDate,endDate,area,level,index,"3",SaveModel.timeLevel_ZL,"1");
            object.put("twzxData",array5);
            JSONArray array6 = dateTotalStatistics3(startDate,endDate,area,level,index,"3",SaveModel.timeLevel_ZL,"2");
            object.put("spzxData",array6);
        }else if (interval==2){
            JSONArray array = weekTotalStatistics7(startDate,endDate,area,level,index,null,SaveModel.timeLevel_ZL);
            object.put("data",array);
            JSONArray array1 = weekTotalStatistics8(startDate,endDate,area,level,index,"3",SaveModel.timeLevel_ZL,"1");
            object.put("specialistData",array1);
            JSONArray array2 = weekTotalStatistics8(startDate,endDate,area,level,index,"1",SaveModel.timeLevel_ZL,"1");
            object.put("topicData",array2);
            JSONArray array3 = weekTotalStatistics8(startDate,endDate,area,level,index,"2",SaveModel.timeLevel_ZL,null);
            object.put("synergyData",array3);
            JSONArray array4 = weekTotalStatistics8(startDate,endDate,area,level,index,"1",SaveModel.timeLevel_ZL,"2");
            object.put("vedioData",array4);
            JSONArray array5 = weekTotalStatistics8(startDate,endDate,area,level,index,"3",SaveModel.timeLevel_ZL,"1");
            object.put("twzxData",array5);
            JSONArray array6 = weekTotalStatistics8(startDate,endDate,area,level,index,"3",SaveModel.timeLevel_ZL,"2");
            object.put("spzxData",array6);
        }else if (interval==3){
            JSONArray array = monthTotalStatistics3(startDate,endDate,area,level,index,null,SaveModel.timeLevel_ZL,null);
            object.put("data",array);
            JSONArray array1 = monthTotalStatistics3(startDate,endDate,area,level,index,"3",SaveModel.timeLevel_ZL,"1");
            object.put("specialistData",array1);
            JSONArray array2 = monthTotalStatistics3(startDate,endDate,area,level,index,"1",SaveModel.timeLevel_ZL,"1");
            object.put("topicData",array2);
            JSONArray array3 = monthTotalStatistics3(startDate,endDate,area,level,index,"2",SaveModel.timeLevel_ZL,null);
            object.put("synergyData",array3);
            JSONArray array4 = monthTotalStatistics3(startDate,endDate,area,level,index,"1",SaveModel.timeLevel_ZL,"2");
            object.put("vedioData",array4);
            JSONArray array5 = monthTotalStatistics3(startDate,endDate,area,level,index,"3",SaveModel.timeLevel_ZL,"1");
            object.put("twzxData",array5);
            JSONArray array6 = monthTotalStatistics3(startDate,endDate,area,level,index,"3",SaveModel.timeLevel_ZL,"2");
            object.put("spzxData",array6);
        }
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        if (StringUtils.isNoneBlank(level2_type)){

            //问诊量表格
            //专家咨询数量
            List<SaveModel> specialistSaveModels = elasticsearchUtil.findDateQuotaLevel1(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL,"3",null,level2_type);
            //协同门诊
            List<SaveModel> syngySaveModels = elasticsearchUtil.findDateQuotaLevel1(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL,"2",null,level2_type);
            //图文复诊
            List<SaveModel> topicSaveModels = elasticsearchUtil.findDateQuotaLevel2(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL,"1","1",null,level2_type);
            ///视频复诊
            List<SaveModel> vedioSaveModels = elasticsearchUtil.findDateQuotaLevel2(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL,"1","2",null,level2_type);
            ///图文咨询
            List<SaveModel> twzxSaveModels = elasticsearchUtil.findDateQuotaLevel2(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL,"3","1",null,level2_type);
            ///视频咨询
            List<SaveModel> spzxSaveModels = elasticsearchUtil.findDateQuotaLevel2(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL,"3","2",null,level2_type);
            JSONArray array = new JSONArray();
            List<String> list = new ArrayList<>();

            for (SaveModel saveModel:syngySaveModels){
                if (level2_type.equals(SaveModel.deptLevel)){
                    if (StringUtils.isNoneBlank(saveModel.getDept())){
                        list.add(saveModel.getDept());
                    }

                }else if (level2_type.equals(SaveModel.doctorLevel)){
                    if (StringUtils.isNoneBlank(saveModel.getDoctor())){
                        list.add(saveModel.getDoctor());
                    }

                }else if (level2_type.equals(SaveModel.OrgLevel)){
                    if (StringUtils.isNoneBlank(saveModel.getHospital())){
                        list.add(saveModel.getHospital());
                    }

                }
            }
            for (int i=0;i<list.size();i++){
                String code = list.get(i);
                JSONObject jsonObject = new JSONObject();
                Double specialist = 0.0;
                Double topic = 0.0;
                Double vedio =0.0;
                Double synegy =0.0;
                Double topicZJ  =0.0;
                Double vedioZJ = 0.0;
                if (index.equalsIgnoreCase("3")){
                    specialist = 0.0;
                    jsonObject.put("specialist",specialist);
                }else if (index.equalsIgnoreCase("5")){
                   /* for (SaveModel saveModel:specialistSaveModels){
                        if (level2_type.equals(SaveModel.OrgLevel)){
                            if (StringUtils.isNoneBlank(saveModel.getHospital())&&code.equalsIgnoreCase(saveModel.getHospital())){
                                jsonObject.put("code",code);
                                jsonObject.put("name",saveModel.getHospitalName());
                                jsonObject.put("specialist",decimalFormat.format(saveModel.getResult1()));
                                specialist = saveModel.getResult1();
                                break;
                            }
                        }else if (level2_type.equals(SaveModel.deptLevel)){
                            if (StringUtils.isNoneBlank(saveModel.getDept())&&code.equalsIgnoreCase(saveModel.getDept())){
                                jsonObject.put("code",code);
                                jsonObject.put("name",saveModel.getDeptName());
                                jsonObject.put("specialist",decimalFormat.format(saveModel.getResult1()));
                                specialist = saveModel.getResult1();
                                break;
                            }
                        }else if (level2_type.equals(SaveModel.doctorLevel)){
                            if (StringUtils.isNoneBlank(saveModel.getDoctor())&&code.equalsIgnoreCase(saveModel.getDoctor())){

                                if (level==6){
                                    List<BaseDoctorHospitalDO> doctorHospitalDOS = doctorHospitalDao.findByDoctorCode(area);
                                    if (doctorHospitalDOS!=null&&doctorHospitalDOS.size()!=0){
                                        BaseDoctorHospitalDO doctorHospitalDO = doctorHospitalDOS.get(0);
                                        jsonObject.put("code",doctorHospitalDO.getDeptCode());
                                        jsonObject.put("name",doctorHospitalDO.getDeptName());
                                    }
                                }else if (level==4){
                                    BaseOrgDO orgDO = orgDao.findByCode(area);
                                    jsonObject.put("code",area);
                                    jsonObject.put("name",orgDO.getName());
                                }else if (level==2){
                                    jsonObject.put("code",area);
                                    jsonObject.put("name","厦门市");
                                }else {
                                    DictHospitalDeptDO dictHospitalDeptDO =  hospitalDeptDao.findByCode(area);
                                    jsonObject.put("code",area);
                                    jsonObject.put("name",dictHospitalDeptDO.getName());
                                }

                                jsonObject.put("doctorCode",code);
                                BaseDoctorDO doctorDO = doctorDao.findById(code);
                                if (doctorDO!=null){
                                    jsonObject.put("doctorJob",doctorDO.getJobTitleName());
                                }else {
                                    jsonObject.put("doctorJob",null);
                                }
                                jsonObject.put("doctorName",saveModel.getDoctorName());
                                jsonObject.put("specialist",decimalFormat.format(saveModel.getResult1()));
                                specialist = saveModel.getResult1();
                                break;
                            }
                        }
                    }*/
                }

                for (SaveModel saveModel:syngySaveModels){
                    if (level2_type.equals(SaveModel.OrgLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getHospital())&&code.equalsIgnoreCase(saveModel.getHospital())){
                            jsonObject.put("code",code);
                            jsonObject.put("name",saveModel.getHospitalName());
                            jsonObject.put("synegy",decimalFormat.format(saveModel.getResult1()));
                            synegy = saveModel.getResult1();
                            break;
                        }
                    }else if (level2_type.equals(SaveModel.deptLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getDept())&&code.equalsIgnoreCase(saveModel.getDept())){
                            jsonObject.put("code",code);
                            jsonObject.put("name",saveModel.getDeptName());
                            jsonObject.put("synegy",decimalFormat.format(saveModel.getResult1()));
                            synegy = saveModel.getResult1();
                            break;
                        }
                    }else if (level2_type.equals(SaveModel.doctorLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getDoctor())&&code.equalsIgnoreCase(saveModel.getDoctor())){
                            if (level==6){
                                List<BaseDoctorHospitalDO> doctorHospitalDOS = doctorHospitalDao.findByDoctorCode(area);
                                if (doctorHospitalDOS!=null&&doctorHospitalDOS.size()!=0){
                                    BaseDoctorHospitalDO doctorHospitalDO = doctorHospitalDOS.get(0);
                                    jsonObject.put("code",doctorHospitalDO.getDeptCode());
                                    jsonObject.put("name",doctorHospitalDO.getDeptName());
                                }
                            }else if (level==4){
                                BaseOrgDO orgDO = orgDao.findByCode(area);
                                jsonObject.put("code",area);
                                jsonObject.put("name",orgDO.getName());
                            }else if (level==2){
                                jsonObject.put("code",area);
                                jsonObject.put("name","厦门市");
                            }else {
                                DictHospitalDeptDO dictHospitalDeptDO =  hospitalDeptDao.findByCode(area);
                                jsonObject.put("code",area);
                                jsonObject.put("name",dictHospitalDeptDO.getName());
                            }
                            BaseDoctorDO doctorDO = doctorDao.findById(code);
                            if (doctorDO!=null){
                                jsonObject.put("doctorJob",doctorDO.getJobTitleName());
                            }else {
                                jsonObject.put("doctorJob",null);
                            }

                            jsonObject.put("doctorCode",code);
                            jsonObject.put("doctorName",saveModel.getDoctorName());
                            jsonObject.put("synegy",decimalFormat.format(saveModel.getResult1()));
                            synegy = saveModel.getResult1();
                            break;
                        }
                    }
                }
                for (SaveModel saveModel:topicSaveModels){
                    if (level2_type.equals(SaveModel.OrgLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getHospital())&&code.equalsIgnoreCase(saveModel.getHospital())){
                            jsonObject.put("code",code);
                            jsonObject.put("name",saveModel.getHospitalName());
                            jsonObject.put("topic",decimalFormat.format(saveModel.getResult1()));
                            topic = saveModel.getResult1();
                            break;
                        }
                    }else if (level2_type.equals(SaveModel.deptLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getDept())&&code.equalsIgnoreCase(saveModel.getDept())){
                            jsonObject.put("code",code);
                            jsonObject.put("name",saveModel.getDeptName());
                            jsonObject.put("topic",decimalFormat.format(saveModel.getResult1()));
                            topic = saveModel.getResult1();
                            break;
                        }
                    }else if (level2_type.equals(SaveModel.doctorLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getDoctor())&&code.equalsIgnoreCase(saveModel.getDoctor())){
                            if (level==6){
                                List<BaseDoctorHospitalDO> doctorHospitalDOS = doctorHospitalDao.findByDoctorCode(area);
                                if (doctorHospitalDOS!=null&&doctorHospitalDOS.size()!=0){
                                    BaseDoctorHospitalDO doctorHospitalDO = doctorHospitalDOS.get(0);
                                    jsonObject.put("code",doctorHospitalDO.getDeptCode());
                                    jsonObject.put("name",doctorHospitalDO.getDeptName());
                                }
                            }else if (level==4){
                                BaseOrgDO orgDO = orgDao.findByCode(area);
                                jsonObject.put("code",area);
                                jsonObject.put("name",orgDO.getName());
                            }else if (level==2){
                                jsonObject.put("code",area);
                                jsonObject.put("name","厦门市");
                            }else {
                                DictHospitalDeptDO dictHospitalDeptDO =  hospitalDeptDao.findByCode(area);
                                jsonObject.put("code",area);
                                jsonObject.put("name",dictHospitalDeptDO.getName());
                            }
                            BaseDoctorDO doctorDO = doctorDao.findById(code);
                            if (doctorDO!=null){
                                jsonObject.put("doctorJob",doctorDO.getJobTitleName());
                            }else {
                                jsonObject.put("doctorJob",null);
                            }
                            jsonObject.put("doctorCode",code);
                            jsonObject.put("doctorName",saveModel.getDoctorName());
                            jsonObject.put("topic",decimalFormat.format(saveModel.getResult1()));
                            topic = saveModel.getResult1();
                            break;
                        }
                    }
                }
                for (SaveModel saveModel:vedioSaveModels){
                    if (level2_type.equals(SaveModel.OrgLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getHospital())&&code.equalsIgnoreCase(saveModel.getHospital())){
                            jsonObject.put("code",code);
                            jsonObject.put("name",saveModel.getHospitalName());
                            jsonObject.put("vedio",decimalFormat.format(saveModel.getResult1()));
                            vedio = saveModel.getResult1();
                            break;
                        }
                    }else  if (level2_type.equals(SaveModel.deptLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getDept())&&code.equalsIgnoreCase(saveModel.getDept())){
                            jsonObject.put("code",code);
                            jsonObject.put("name",saveModel.getDeptName());
                            jsonObject.put("vedio",decimalFormat.format(saveModel.getResult1()));
                            vedio = saveModel.getResult1();
                            break;
                        }
                    }else if (level2_type.equals(SaveModel.doctorLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getDoctor())&&code.equalsIgnoreCase(saveModel.getDoctor())){
                            if (level==6){
                                List<BaseDoctorHospitalDO> doctorHospitalDOS = doctorHospitalDao.findByDoctorCode(area);
                                if (doctorHospitalDOS!=null&&doctorHospitalDOS.size()!=0){
                                    BaseDoctorHospitalDO doctorHospitalDO = doctorHospitalDOS.get(0);
                                    jsonObject.put("code",doctorHospitalDO.getDeptCode());
                                    jsonObject.put("name",doctorHospitalDO.getDeptName());
                                }
                            }else if (level==4){
                                BaseOrgDO orgDO = orgDao.findByCode(area);
                                jsonObject.put("code",area);
                                jsonObject.put("name",orgDO.getName());
                            }else if (level==2){
                                jsonObject.put("code",area);
                                jsonObject.put("name","厦门市");
                            }else {
                                DictHospitalDeptDO dictHospitalDeptDO =  hospitalDeptDao.findByCode(area);
                                jsonObject.put("code",area);
                                jsonObject.put("name",dictHospitalDeptDO.getName());
                            }
                            jsonObject.put("doctorCode",code);
                            BaseDoctorDO doctorDO = doctorDao.findById(code);
                            if (doctorDO!=null){
                                jsonObject.put("doctorJob",doctorDO.getJobTitleName());
                            }else {
                                jsonObject.put("doctorJob",null);
                            }
                            jsonObject.put("doctorName",saveModel.getDoctorName());
                            jsonObject.put("vedio",decimalFormat.format(saveModel.getResult1()));
                            vedio = saveModel.getResult1();
                            break;
                        }
                    }
                }
                for (SaveModel saveModel:twzxSaveModels){
                    if (level2_type.equals(SaveModel.OrgLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getHospital())&&code.equalsIgnoreCase(saveModel.getHospital())){
                            jsonObject.put("code",code);
                            jsonObject.put("name",saveModel.getHospitalName());
                            jsonObject.put("topicZJ",decimalFormat.format(saveModel.getResult1()));
                            topicZJ = saveModel.getResult1();
                            break;
                        }
                    }else if (level2_type.equals(SaveModel.deptLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getDept())&&code.equalsIgnoreCase(saveModel.getDept())){
                            jsonObject.put("code",code);
                            jsonObject.put("name",saveModel.getDeptName());
                            jsonObject.put("topicZJ",decimalFormat.format(saveModel.getResult1()));
                            topicZJ = saveModel.getResult1();
                            break;
                        }
                    }else if (level2_type.equals(SaveModel.doctorLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getDoctor())&&code.equalsIgnoreCase(saveModel.getDoctor())){
                            if (level==6){
                                List<BaseDoctorHospitalDO> doctorHospitalDOS = doctorHospitalDao.findByDoctorCode(area);
                                if (doctorHospitalDOS!=null&&doctorHospitalDOS.size()!=0){
                                    BaseDoctorHospitalDO doctorHospitalDO = doctorHospitalDOS.get(0);
                                    jsonObject.put("code",doctorHospitalDO.getDeptCode());
                                    jsonObject.put("name",doctorHospitalDO.getDeptName());
                                }
                            }else if (level==4){
                                BaseOrgDO orgDO = orgDao.findByCode(area);
                                jsonObject.put("code",area);
                                jsonObject.put("name",orgDO.getName());
                            }else if (level==2){
                                jsonObject.put("code",area);
                                jsonObject.put("name","厦门市");
                            }else {
                                DictHospitalDeptDO dictHospitalDeptDO =  hospitalDeptDao.findByCode(area);
                                jsonObject.put("code",area);
                                jsonObject.put("name",dictHospitalDeptDO.getName());
                            }
                            BaseDoctorDO doctorDO = doctorDao.findById(code);
                            if (doctorDO!=null){
                                jsonObject.put("doctorJob",doctorDO.getJobTitleName());
                            }else {
                                jsonObject.put("doctorJob",null);
                            }
                            jsonObject.put("doctorCode",code);
                            jsonObject.put("doctorName",saveModel.getDoctorName());
                            jsonObject.put("topicZJ",decimalFormat.format(saveModel.getResult1()));
                            topicZJ = saveModel.getResult1();
                            break;
                        }
                    }
                }
                for (SaveModel saveModel:spzxSaveModels){
                    if (level2_type.equals(SaveModel.OrgLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getHospital())&&code.equalsIgnoreCase(saveModel.getHospital())){
                            jsonObject.put("code",code);
                            jsonObject.put("name",saveModel.getHospitalName());
                            jsonObject.put("vedioZJ",decimalFormat.format(saveModel.getResult1()));
                            vedioZJ = saveModel.getResult1();
                            break;
                        }
                    }else if (level2_type.equals(SaveModel.deptLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getDept())&&code.equalsIgnoreCase(saveModel.getDept())){
                            jsonObject.put("code",code);
                            jsonObject.put("name",saveModel.getDeptName());
                            jsonObject.put("vedioZJ",decimalFormat.format(saveModel.getResult1()));
                            vedioZJ = saveModel.getResult1();
                            break;
                        }
                    }else if (level2_type.equals(SaveModel.doctorLevel)){
                        if (StringUtils.isNoneBlank(saveModel.getDoctor())&&code.equalsIgnoreCase(saveModel.getDoctor())){
                            if (level==6){
                                List<BaseDoctorHospitalDO> doctorHospitalDOS = doctorHospitalDao.findByDoctorCode(area);
                                if (doctorHospitalDOS!=null&&doctorHospitalDOS.size()!=0){
                                    BaseDoctorHospitalDO doctorHospitalDO = doctorHospitalDOS.get(0);
                                    jsonObject.put("code",doctorHospitalDO.getDeptCode());
                                    jsonObject.put("name",doctorHospitalDO.getDeptName());
                                }
                            }else if (level==4){
                                BaseOrgDO orgDO = orgDao.findByCode(area);
                                jsonObject.put("code",area);
                                jsonObject.put("name",orgDO.getName());
                            }else if (level==2){
                                jsonObject.put("code",area);
                                jsonObject.put("name","厦门市");
                            }else {
                                DictHospitalDeptDO dictHospitalDeptDO =  hospitalDeptDao.findByCode(area);
                                jsonObject.put("code",area);
                                jsonObject.put("name",dictHospitalDeptDO.getName());
                            }
                            BaseDoctorDO doctorDO = doctorDao.findById(code);
                            if (doctorDO!=null){
                                jsonObject.put("doctorJob",doctorDO.getJobTitleName());
                            }else {
                                jsonObject.put("doctorJob",null);
                            }
                            jsonObject.put("doctorCode",code);
                            jsonObject.put("doctorName",saveModel.getDoctorName());
                            jsonObject.put("vedioZJ",decimalFormat.format(saveModel.getResult1()));
                            vedioZJ = saveModel.getResult1();
                            break;
                        }
                    }
                }
                Double total1 = topic+vedio ;//图文和视频总和
                Double total = topic+vedio+synegy+specialist+topicZJ+vedioZJ;//总和
                Double total2 = topicZJ+vedioZJ ;//图文咨询和视频咨询总和
                jsonObject.put("total1",decimalFormat.format(total1));//图文和视频总和
                jsonObject.put("total",decimalFormat.format(total));//总和
                jsonObject.put("total2",decimalFormat.format(total2));//咨询总和
                jsonObject.put("topicZJ",decimalFormat.format(topicZJ));//咨询总和
                jsonObject.put("vedioZJ",decimalFormat.format(vedioZJ));//咨询总和
                array.add(jsonObject);
            }
            List<JSONObject> bindArrayResult = JSONArray.parseArray(array.toJSONString(), JSONObject.class);
            System.out.println("排序前："+bindArrayResult);
            Collections.sort(bindArrayResult, new Comparator<JSONObject>() {
                @Override
                public int compare(JSONObject o1, JSONObject o2) {
                    double a = o1.getDouble("total");
                    double b = o2.getDouble("total");
                    if (a > b) {
                        return -1;
                    } else if(a == b) {
                        return 0;
                    } else
                        return 1;
                }
            });
            JSONArray jsonArray = JSONArray.parseArray(bindArrayResult.toString());
            object.put("excelData",jsonArray);
        }
        return object;
    }


    /**
     * 开方量按日期柱状图
     *
     *
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param level2_type
     * @return
     * @throws Exception
     */
    public JSONObject getPrescriptionLine(String startDate, String endDate, String area, int level, String index,int interval, String level2_type) throws Exception {
        JSONObject object = new JSONObject();
        //开方量增量曲线
        JSONArray array = dateTotalStatistics3(startDate,endDate,area,level,index,null,SaveModel.timeLevel_ZL,null);
        object.put("prescriptionLine",array);
        return object;
    }


    /**
     *
     * 门诊圆形图
     *
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param level2_type
     * @return
     * @throws Exception
     */
    public JSONObject getOutPatientCircular(String startDate, String endDate, String area, int level, String index, String level2_type) throws Exception {

        JSONObject object = new JSONObject();
        if (index.equalsIgnoreCase("3")){
            //协同门诊
            SaveModel saveModel1 = null;
            saveModel1 = elasticsearchUtil.findOneDateQuotaLevel1(endDate, endDate, area, level, index+",21", SaveModel.timeLevel_DDL, "2");
            //图文复诊
            SaveModel saveModel2 = null;
            //saveModel2 = elasticsearchUtil.findOneDateQuotaLevel2(endDate, endDate, area, level, index, SaveModel.timeLevel_DDL, "1","1");
            saveModel2 = elasticsearchUtil.findOneDateQuotaLevel2(endDate, endDate, area, level, index+",21", SaveModel.timeLevel_DDL, "1","1");
            //视频复诊
            SaveModel saveModel3 = null;
/*
    saveModel3 = elasticsearchUtil.findOneDateQuotaLevel2(endDate, endDate, area, level, index, SaveModel.timeLevel_DDL, "1","2");
*/
            saveModel3 = elasticsearchUtil.findOneDateQuotaLevel2(endDate, endDate, area, level, index+",21", SaveModel.timeLevel_DDL, "1","2");
            Double specialistCount =0.0;
            //专科咨询
            SaveModel saveModel4 = null;
            saveModel4 = elasticsearchUtil.findOneDateQuotaLevel2(endDate, endDate, area, level, index+",21", SaveModel.timeLevel_DDL, "3","1");
            specialistCount = saveModel4.getResult1();//专家咨询数量
            //专科视频咨询
            Double specialistSPCount =0.0;
            SaveModel saveModel5 = null;
            saveModel5 = elasticsearchUtil.findOneDateQuotaLevel2(endDate, endDate, area, level, index+",21", SaveModel.timeLevel_DDL, "3","2");
            specialistSPCount = saveModel5.getResult1();//专家咨询视频数量
            Double synergyCount = saveModel1.getResult1();//协同门诊数量
            Double topicCount = saveModel2.getResult1();//图文复诊数量
            Double videoCount = saveModel3.getResult1();//视频复诊数量
            Double total = specialistCount+synergyCount+topicCount+videoCount+specialistSPCount;//总量
            DecimalFormat decimalFormat = new DecimalFormat("0.00");
            object.put("specialistCount",decimalFormat.format(specialistCount));//专家咨询数
            object.put("specialistRate",getRange(specialistCount.intValue(),total.intValue(),0));
            object.put("specialistSPCount",decimalFormat.format(specialistSPCount));//专家咨询数
            object.put("specialistSPRate",getRange(specialistSPCount.intValue(),total.intValue(),0));
            object.put("synergyCount",decimalFormat.format(synergyCount));//专家咨询数
            object.put("synergyRate",getRange(synergyCount.intValue(),total.intValue(),0));
            object.put("topicCount",decimalFormat.format(topicCount));//图文复诊数量
            object.put("topicRate",getRange(topicCount.intValue(),total.intValue(),0));
            object.put("videoCount",decimalFormat.format(videoCount));//视频复诊数量
            object.put("videoRate",getRange(videoCount.intValue(),total.intValue(),0));
            object.put("total",decimalFormat.format(total));

        }else {
            //协同门诊
            SaveModel saveModel1 = null;
            saveModel1 = elasticsearchUtil.findOneDateQuotaLevel1(endDate, endDate, area, level, index, SaveModel.timeLevel_DDL, "12");
            //图文复诊
            SaveModel saveModel2 = null;
            //saveModel2 = elasticsearchUtil.findOneDateQuotaLevel2(endDate, endDate, area, level, index, SaveModel.timeLevel_DDL, "1","1");
            saveModel2 = elasticsearchUtil.findOneDateQuotaLevel1(endDate, endDate, area, level, index, SaveModel.timeLevel_DDL, "9");
            //视频复诊
            SaveModel saveModel3 = null;
/*
    saveModel3 = elasticsearchUtil.findOneDateQuotaLevel2(endDate, endDate, area, level, index, SaveModel.timeLevel_DDL, "1","2");
*/
            saveModel3 = elasticsearchUtil.findOneDateQuotaLevel1(endDate, endDate, area, level, index, SaveModel.timeLevel_DDL, "16");
            Double specialistCount =0.0;
            //专科咨询图文
            SaveModel saveModel4 = null;
            saveModel4 = elasticsearchUtil.findOneDateQuotaLevel1(endDate, endDate, area, level, index, SaveModel.timeLevel_DDL, "1");
            specialistCount = saveModel4.getResult1();
            //专科咨询视频
            Double specialistCountSP =0.0;
            SaveModel saveModel5 = null;
            saveModel5 = elasticsearchUtil.findOneDateQuotaLevel1(endDate, endDate, area, level, index, SaveModel.timeLevel_DDL, "17");
            specialistCountSP = saveModel5.getResult1();//专家咨询数量

            Double synergyCount = saveModel1.getResult1();//协同门诊数量
            Double topicCount = saveModel2.getResult1();//图文复诊数量
            Double videoCount = saveModel3.getResult1();//视频复诊数量
            Double total = specialistCount+synergyCount+topicCount+videoCount+specialistCountSP;//总量
            object.put("specialistCount",specialistCount);//专家咨询数
            object.put("specialistRate",getRange(specialistCount.intValue(),total.intValue(),0));
            object.put("specialistSPCount",specialistCountSP);//专家咨询视频数
            object.put("specialistSPRate",getRange(specialistCountSP.intValue(),total.intValue(),0));
            object.put("synergyCount",synergyCount);//专家咨询数
            object.put("synergyRate",getRange(synergyCount.intValue(),total.intValue(),0));
            object.put("topicCount",topicCount);//图文复诊数量
            object.put("topicRate",getRange(topicCount.intValue(),total.intValue(),0));
            object.put("videoCount",videoCount);//视频复诊数量
            object.put("videoRate",getRange(videoCount.intValue(),total.intValue(),0));
            object.put("total",total);

        }





        return object;
    }


    /**
     * 问诊量统计-等级
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param level2_type
     * @return
     * @throws Exception
     */
    public JSONObject getOutPatientGrade(String startDate, String endDate, String area, int level, String index, String level2_type) throws Exception {

        JSONObject object = new JSONObject();

        //问诊总量
        SaveModel saveModel1 = null;
        saveModel1 = elasticsearchUtil.findOneDateQuotaLevel0(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL);
        int total = saveModel1.getResult1().intValue();

        List<SaveModel> saveModels = elasticsearchUtil.findDateQuotaLevel0(startDate,endDate,area,level,index,SaveModel.timeLevel_ZL,null,level2_type);

        List<JSONObject> result = new ArrayList<>();
        for (SaveModel saveModel:saveModels){
            JSONObject object1 = new JSONObject();
            if (level2_type.equals(SaveModel.deptLevel)){
                object1.put("dept",saveModel.getDept());
                object1.put("deptName",saveModel.getDeptName());
            }else if (level2_type.equals(SaveModel.doctorLevel)){
                object1.put("doctor",saveModel.getDoctor());
                object1.put("doctorName",saveModel.getDoctorName());
            }else if (level2_type.equals(SaveModel.OrgLevel)){
                object1.put("hospital",saveModel.getHospital());
                object1.put("hospitalName",saveModel.getHospitalName());
            }
            object1.put("result1",saveModel.getResult1());
            object1.put("rate",getRange(saveModel.getResult1().intValue(),total,0));
            object1.put("result2",saveModel.getResult2());
            result.add(object1);
        }
        // 排序
        result.sort(new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                if (o1.getString("result1").compareTo(o2.getString("result1")) > 0) {
                    return -1;
                } else if (o1.getString("result1").compareTo(o2.getString("result1")) < 0) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });
        JSONArray jsonArray = new JSONArray();
        for (JSONObject object2:result){
            jsonArray.add(object2);
        }
        object.put("data",result);
        return object;
    }

    /**
     * 问诊量统计-类别曲线
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param level2_type
     * @return
     * @throws Exception
     */
    public JSONObject getOutPatientTypeline(String startDate, String endDate, String area, int level, String index, String level2_type) throws Exception {
        JSONObject object = new JSONObject();
        //专家咨询
        JSONArray specialistArray = dateTotalStatistics2(startDate,endDate,area,level,index,"1",SaveModel.timeLevel_ZL,null);
        object.put("specialistArray",specialistArray);
        //专家咨询
        JSONArray specialistSPArray = dateTotalStatistics2(startDate,endDate,area,level,index,"17",SaveModel.timeLevel_ZL,null);
        object.put("specialistSPArray",specialistSPArray);
        //协同复诊
        JSONArray syngeryArray = dateTotalStatistics2(startDate,endDate,area,level,index,"12",SaveModel.timeLevel_ZL,null);
        object.put("syngeryArray",syngeryArray);
        //图文复诊
        JSONArray topicArray = dateTotalStatistics2(startDate,endDate,area,level,index,"9",SaveModel.timeLevel_ZL,null);
        object.put("topicArray",topicArray);
        //视频复诊
        JSONArray vedioArray = dateTotalStatistics2(startDate,endDate,area,level,index,"16",SaveModel.timeLevel_ZL,null);
        object.put("vedioArray",vedioArray);
        return object;
    }


    public JSONObject getDoctorStatistics(String startDate, String endDate, String area, int level, String index, String level2_type,Integer flag) throws Exception {
        String sql = null;
        JSONObject object1= new JSONObject();
        if (flag==1){
            sql="SELECT dhd.CODE AS \"dept_code\", dhd. NAME AS \"dept_name\", CASE WHEN c. COUNT IS NOT NULL THEN " +
                    "c. COUNT ELSE 0 END AS \"COUNT\" FROM DICT_HOSPITAL_DEPT dhd " +
                    "LEFT JOIN ( SELECT dh.DEPT_CODE as\"DEPT_CODE\", hd. NAME AS \"dept_name\", " +
                    "COUNT(dh.DOCTOR_CODE) AS \"COUNT\" FROM BASE_DOCTOR bd " +
                    "LEFT JOIN BASE_DOCTOR_HOSPITAL dh ON bd. ID = dh.DOCTOR_CODE " +
                    "RIGHT JOIN DICT_HOSPITAL_DEPT hd ON hd.CODE = dh.DEPT_CODE " +
                    "WHERE bd.DEL = 1 AND bd.job_title_code IN('1201','1301','1401','1101','066','067','061','1310','061','065')  AND  bd.OUTPATIENT_TYPE IS NOT NULL GROUP BY dh.DEPT_CODE, hd. NAME " +
                    "ORDER BY COUNT DESC ) c ON dhd.CODE = c.DEPT_CODE " +
                    "WHERE dhd.CONSULT_DEPT_FLAG='1'   " +
                    "ORDER BY count desc";
            List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
            JSONArray array = new JSONArray();
            for (Map<String,Object> map:mapList){
                JSONObject object = new JSONObject();
                if (array!=null&&array.size()!=0){
                    JSONObject jsonObject = array.getJSONObject(array.size()-1);
                    object.put("deptCode",map.get("dept_code"));
                    object.put("deptName",map.get("dept_name"));
                    object.put("count",map.get("count"));
                    if (jsonObject.getInteger("count")==Integer.parseInt(map.get("count").toString())){
                        object.put("rank",jsonObject.getInteger("rank"));
                    }else if (jsonObject.getInteger("count")>Integer.parseInt(map.get("count").toString())){
                        object.put("rank",jsonObject.getInteger("rank")+1);
                    }
                }else {
                    object.put("deptCode",map.get("dept_code"));
                    object.put("deptName",map.get("dept_name"));
                    object.put("count",map.get("count"));
                    object.put("rank",1);
                }
                array.add(object);
            }
            object1.put("data",array);//排名

        }else if (flag ==2) {
            List<SaveModel> saveModels = elasticsearchUtil.findDateQuotaLevel0(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL, null, "6");
            String deptSql = "select hd.CODE as \"code\",hd.NAME as \"name\" from DICT_HOSPITAL_DEPT hd where hd.ORG_CODE ='" + area + "' and hd.CONSULT_DEPT_FLAG=1";
            List<Map<String, Object>> mapList = hibenateUtils.createSQLQuery(deptSql);
            List<JSONObject> result = new ArrayList<>();
            for (SaveModel saveModel : saveModels) {
                List<BaseDoctorHospitalDO> baseDoctorHospitalDOS = doctorHospitalDao.findByDoctorCode(saveModel.getDoctor());
                if (baseDoctorHospitalDOS != null && baseDoctorHospitalDOS.size() != 0) {
                    saveModel.setDept(baseDoctorHospitalDOS.get(0).getDeptCode());
                    saveModel.setDeptName(baseDoctorHospitalDOS.get(0).getDeptName());
                }
            }
            for (Map<String, Object> map : mapList) {
                JSONObject object = new JSONObject();
                String code = map.get("code").toString();
                object.put("deptCode", map.get("code"));
                object.put("deptName", map.get("name"));
                Integer count = 0;
                for (SaveModel saveModel : saveModels) {
                    if (StringUtils.isNoneBlank(saveModel.getDept())&&saveModel.getDept().equalsIgnoreCase(code)) {
                        if (saveModel.getResult1() > 0) {
                            count += 1;
                        }
                    }
                }
                object.put("count", count);
                result.add(object);
            }
            // 排序
            result.sort(new Comparator<JSONObject>() {
                @Override
                public int compare(JSONObject o1, JSONObject o2) {
                    if (o1.getString("count").compareTo(o2.getString("count")) > 0) {
                        return -1;
                    } else if (o1.getString("count").compareTo(o2.getString("count")) < 0) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
            });
            JSONArray array = new JSONArray();
            for (JSONObject map:result){
                JSONObject object = new JSONObject();
                if (array!=null&&array.size()!=0){
                    JSONObject jsonObject = array.getJSONObject(array.size()-1);
                    object.put("deptCode",map.getString("deptCode"));
                    object.put("deptName",map.getString("deptName"));
                    object.put("count",map.getInteger("count"));
                    if (jsonObject.getInteger("count")==map.getInteger("count")){
                        object.put("rank",jsonObject.getInteger("rank"));
                    }else if (jsonObject.getInteger("count")>map.getInteger("count")){
                        object.put("rank",jsonObject.getInteger("rank")+1);
                    }
                }else {
                    object.put("deptCode",map.get("deptCode"));
                    object.put("deptName",map.get("deptName"));
                    object.put("count",map.get("count"));
                    object.put("rank",1);
                }
                array.add(object);
            }
            object1.put("data", array);

        }
        return object1;
    }

    public JSONObject getDoctorTotal(String startDate, String endDate, String area, int level, String index, String level2_type,Integer flag) throws Exception {
        JSONObject object = new JSONObject();
        if (flag==1){
            String sql = "SELECT bd.JOB_TITLE_CODE as \"JOB_TITLE_CODE\", bd.JOB_TITLE_NAME as \"JOB_TITLE_NAME\", COUNT(bd.ID) as \"count\" FROM " +
                    "BASE_DOCTOR bd, BASE_DOCTOR_HOSPITAL bdh,DICT_HOSPITAL_DEPT dhd  WHERE bd.ID = bdh.DOCTOR_CODE AND dhd.code = bdh.DEPT_CODE AND bd.DEL = 1 " +
                    " AND bdh.DEL = 1 AND bd.OUTPATIENT_TYPE IS NOT NULL AND bd.job_title_code IN('1201','1301','1401','1101','066','067','061','1310','061','065') " ;

            String sqlCount = "SELECT COUNT(bd.ID) as \"total\" FROM " +
                    "BASE_DOCTOR bd, BASE_DOCTOR_HOSPITAL bdh,DICT_HOSPITAL_DEPT dhd WHERE bd.ID = bdh.DOCTOR_CODE AND dhd.code = bdh.DEPT_CODE AND bd.DEL = 1 " +
                    " AND bdh.DEL = 1 AND bd.OUTPATIENT_TYPE IS NOT NULL AND dhd.CONSULT_DEPT_FLAG='1' AND bd.job_title_code IN('1201','1301','1401','1101','066','067','061','1310','061','065') ";

            if (level==4){
                sql+=" AND dhd.ORG_CODE = '"+area+"'";
                sqlCount+=" AND dhd.ORG_CODE = '"+area+"'";
            }else if (level==5){
                sql+=" AND bdh.DEPT_CODE = '"+area+"'";
                sqlCount+=" AND bdh.DEPT_CODE = '"+area+"'";
            }
            sql += " AND dhd.CONSULT_DEPT_FLAG='1' GROUP BY bd.JOB_TITLE_CODE,bd.JOB_TITLE_NAME";
            List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);//各职称人数
            List<Map<String,Object>> rstotal = jdbcTemplate.queryForList(sqlCount);//总人数
            Long total = 0L;
            if(rstotal!=null&&rstotal.size()>0){
                total = Long.parseLong(rstotal.get(0).get("total").toString()) ;
            }
            for (Map<String,Object> map:mapList){
                Integer count = Integer.parseInt(map.get("count").toString());
                map.put("rate",getRange(count,total.intValue(),0));//百分比
            }
            object.put("total",total);//总量
            object.put("data",mapList);//各职称人数
        }else if (flag==2){
            List<SaveModel> saveModels = elasticsearchUtil.findDateQuotaLevel0(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL, null, "6");
            StringBuffer buffer = new StringBuffer();
            int total = 0;
            for(SaveModel saveModel:saveModels){
                if (saveModel.getResult1()>0){
                    total+=1;
                    buffer.append("'"+saveModel.getDoctor()+"',");
                }
            }
            if (buffer.length()>0){
                buffer.deleteCharAt(buffer.length()-1);
            }
            if (buffer.length()>0){
                String sql ="SELECT bd.JOB_TITLE_CODE as \"JOB_TITLE_CODE\", bd.JOB_TITLE_NAME as \"JOB_TITLE_NAME\" ,COUNT(bd.ID) AS \"total\" FROM BASE_DOCTOR bd WHERE  bd.DEL = 1";
                sql +="  AND bd.ID IN("+buffer+")";
                sql +="  GROUP BY bd.JOB_TITLE_CODE,bd.JOB_TITLE_NAME";
                List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);//各职称人数
                for (Map<String,Object> map:mapList){
                    Integer count = Integer.parseInt(map.get("total").toString());
                    map.put("rate",getRange(count,total,0));//百分比
                }
                object.put("total",total);//总量
                object.put("data",mapList);//各职称人数
            }
        }
        return object;
    }

    public JSONObject getDoctorStatisticsExcel(String startDate, String endDate, String area, int level, String index, String level2_type,Integer flag) throws Exception {
        JSONObject object = new JSONObject();
        if (flag==1){//开通医生
            String sql ="SELECT bd.ID as\"ID\", bd.NAME as\"NAME\", bd.OUTPATIENT_TYPE as\"OUTPATIENT_TYPE\", " +
                    "dhd.code AS \"dept_code\", dhd.name AS \"dept_name\",bd.JOB_TITLE_NAME as\"JOB_TITLE_NAME\" FROM " +
                    "BASE_DOCTOR bd, BASE_DOCTOR_HOSPITAL bdh, " +
                    "DICT_HOSPITAL_DEPT dhd WHERE bd.ID = bdh.DOCTOR_CODE " +
                    "AND dhd.code = bdh.DEPT_CODE " +
                    "AND bd.DEL = 1 " +
                    "AND bdh.DEL = 1 " +
                    "AND bd.OUTPATIENT_TYPE IS NOT NULL " +
                    " AND dhd.CONSULT_DEPT_FLAG='1' AND bd.job_title_code IN('1201','1301','1401','1101','066','067','061','1310','061','065','1','2','3','4')";
            String deptSql = "select hd.CODE as \"CODE\",hd.NAME as \"NAME\" from DICT_HOSPITAL_DEPT hd where CONSULT_DEPT_FLAG=1";
            if (level==4){//科室
                sql+=" AND dhd.ORG_CODE = '"+area+"'";
                deptSql+=" AND hd.ORG_CODE ='" + area + "'";
            }else if (level==5){//医生
                sql+=" AND bdh.DEPT_CODE = '"+area+"'";
                deptSql+=" AND hd.CODE ='" + area + "'";
            }
            List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
            List<Map<String, Object>> mapList1 = jdbcTemplate.queryForList(deptSql);
            JSONArray array =new JSONArray();
            if (level==4){
                for (Map<String,Object> map1:mapList1){
                    JSONObject object1 = new JSONObject();
                    object1.put("deptCode",map1.get("code"));
                    object1.put("deptName",map1.get("name"));
                    Long topic = 0L;
                    Long vedio =0L;
                    Long synegy = 0L;
                    Long specialist =0L;
                    Long other =0L;
                    Long topicZJ = 0L;
                    Long vedioZJ =0L;
                    for (Map<String,Object> map:mapList){
                        if (map.get("dept_code").toString().equalsIgnoreCase(map1.get("code").toString())){
                            String outpatientType = map.get("outpatient_type").toString();
                            String str[]=outpatientType.split(",");
                            for (int i=0;i<str.length;i++){
                                if (str[i].contains("1")){
                                    topic+=1;
                                }else if (str[i].contains("2")){
                                    vedio+=1;
                                }else if (str[i].contains("xt")){
                                    synegy+=1;
                                }else if (str[i].contains("zj")){
                                    topicZJ+=1;
                                } else if (str[i].contains("zxsp")){
                                    vedioZJ+=1;
                                }else {
                                    other+=1;
                                }
                            }
                        }
                    }
                    object1.put("topic",topic);//图文
                    object1.put("vedio",vedio);//视频
                    object1.put("topicZJ",topicZJ);//图文
                    object1.put("vedioZJ",vedioZJ);//视频
                    object1.put("synegy",synegy);//协同
                    object1.put("specialist",specialist);//专家
                    object1.put("other",other);//其他
                    object1.put("doctorName","-");//医生名字
                    object1.put("doctorJob","-");//医生职称
                    array.add(object1);
                }
            }else if (level==5){
                for (Map<String,Object> map:mapList){
                    JSONObject object1 = new JSONObject();
                    object1.put("deptCode",map.get("dept_code"));
                    object1.put("deptName",map.get("dept_name"));
                    Long topic = 0L;
                    Long vedio =0L;
                    Long synegy = 0L;
                    Long specialist =0L;
                    Long other =0L;
                    Long topicZJ = 0L;
                    Long vedioZJ =0L;
                    String outpatientType = map.get("outpatient_type").toString();
                    String str[]=outpatientType.split(",");
                    for (int i=0;i<str.length;i++){
                        if (str[i].contains("1")){
                            topic+=1;
                        }else if (str[i].contains("2")){
                            vedio+=1;
                        }else if (str[i].contains("xt")){
                            synegy+=1;
                        }else if (str[i].contains("zj")){
                            topicZJ+=1;
                        } else if (str[i].contains("zxsp")){
                            vedioZJ+=1;
                        }else {
                            other+=1;
                        }
                    }
                    object1.put("topic",topic);//图文
                    object1.put("vedio",vedio);//视频
                    object1.put("topicZJ",topicZJ);//图文
                    object1.put("vedioZJ",vedioZJ);//视频
                    object1.put("synegy",synegy);//协同
                    object1.put("specialist",specialist);//专家
                    object1.put("other",other);//其他
                    object1.put("doctor",map.get("id"));
                    object1.put("doctorName",map.get("name"));//医生名字
                    object1.put("doctorJob",map.get("job_title_name"));//医生职称
                    array.add(object1);
                }
            }
            object.put("data",array);
        }else if (flag==2){//活跃医生
            //图文
            List<SaveModel> topicModels = elasticsearchUtil.findDateQuotaLevel1(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL, "9",null, "6");
            //视频
            List<SaveModel> vedioModels = elasticsearchUtil.findDateQuotaLevel1(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL, "16",null, "6");
            //协同
            List<SaveModel> synegyModels = elasticsearchUtil.findDateQuotaLevel1(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL, "12",null, "6");
            //专科图文
            List<SaveModel> specialistModels = elasticsearchUtil.findDateQuotaLevel1(startDate, endDate, area, level,index, SaveModel.timeLevel_ZL,"1",null, "6");
            //专科视频
            List<SaveModel> specialistSPModels = elasticsearchUtil.findDateQuotaLevel1(startDate, endDate, area, level,index, SaveModel.timeLevel_ZL,"17",null, "6");

            String deptSql = "select hd.CODE as \"CODE\",hd.NAME as \"NAME\" from DICT_HOSPITAL_DEPT hd where CONSULT_DEPT_FLAG=1";
            if (level==4){//科室
                deptSql+=" AND hd.ORG_CODE ='" + area + "'";
            }else if (level==5){//医生
                deptSql+=" AND hd.CODE ='" + area + "'";
            }
            List<Map<String, Object>> mapList1 = jdbcTemplate.queryForList(deptSql);
            JSONArray array =new JSONArray();
            if (level==4){
                for (Map<String,Object> map:mapList1){
                    Long topic = 0L;
                    Long vedio =0L;
                    Long synegy = 0L;
                    Long topicZJ =0L;
                    Long vedioZJ =0L;
                    Long other =0L;
                    JSONObject jsonObject = new JSONObject();
                    for(SaveModel saveModel:topicModels){
                        if (saveModel.getResult1()>0){
                            List<BaseDoctorHospitalDO> doctorHospitalDOs = doctorHospitalDao.findByDoctorCode(saveModel.getDoctor());
                            if (doctorHospitalDOs!=null&&doctorHospitalDOs.size()!=0){
                                saveModel.setDept(doctorHospitalDOs.get(0).getDeptCode());
                                saveModel.setDeptName(doctorHospitalDOs.get(0).getDeptName());
                            }
                            if(map.get("code").toString().equalsIgnoreCase(saveModel.getDept())) {
                                topic += 1;
                            }
                        }
                    }

                    for(SaveModel saveModel:vedioModels){
                        if (saveModel.getResult1()>0){
                            List<BaseDoctorHospitalDO> doctorHospitalDOs = doctorHospitalDao.findByDoctorCode(saveModel.getDoctor());
                            if (doctorHospitalDOs!=null&&doctorHospitalDOs.size()!=0){
                                saveModel.setDept(doctorHospitalDOs.get(0).getDeptCode());
                                saveModel.setDeptName(doctorHospitalDOs.get(0).getDeptName());
                            }
                            if(map.get("code").toString().equalsIgnoreCase(saveModel.getDept())){
                                vedio+=1;
                            }
                        }
                    }
                    for(SaveModel saveModel:synegyModels){
                        if (saveModel.getResult1()>0){
                            List<BaseDoctorHospitalDO> doctorHospitalDOs = doctorHospitalDao.findByDoctorCode(saveModel.getDoctor());
                            if (doctorHospitalDOs!=null&&doctorHospitalDOs.size()!=0){
                                saveModel.setDept(doctorHospitalDOs.get(0).getDeptCode());
                                saveModel.setDeptName(doctorHospitalDOs.get(0).getDeptName());
                            }
                            if(map.get("code").toString().equalsIgnoreCase(saveModel.getDept())){
                                    synegy+=1;
                            }
                        }
                    }
                    for(SaveModel saveModel:specialistModels){
                        if (saveModel.getResult1()>0){
                            List<BaseDoctorHospitalDO> doctorHospitalDOs = doctorHospitalDao.findByDoctorCode(saveModel.getDoctor());
                            if (doctorHospitalDOs!=null&&doctorHospitalDOs.size()!=0){
                                saveModel.setDept(doctorHospitalDOs.get(0).getDeptCode());
                                saveModel.setDeptName(doctorHospitalDOs.get(0).getDeptName());
                            }
                            if(map.get("code").toString().equalsIgnoreCase(saveModel.getDept())){
                                topicZJ+=1;
                            }
                        }
                    }
                    for(SaveModel saveModel:specialistSPModels){
                        if (saveModel.getResult1()>0){
                            List<BaseDoctorHospitalDO> doctorHospitalDOs = doctorHospitalDao.findByDoctorCode(saveModel.getDoctor());
                            if (doctorHospitalDOs!=null&&doctorHospitalDOs.size()!=0){
                                saveModel.setDept(doctorHospitalDOs.get(0).getDeptCode());
                                saveModel.setDeptName(doctorHospitalDOs.get(0).getDeptName());
                            }
                            if(map.get("code").toString().equalsIgnoreCase(saveModel.getDept())){
                                vedioZJ+=1;
                            }
                        }
                    }
                    jsonObject.put("topic",topic);//图文
                    jsonObject.put("vedio",vedio);//视频
                    jsonObject.put("synegy",synegy);//协同
                    jsonObject.put("topicZJ",topicZJ);//专家
                    jsonObject.put("vedioZJ",vedioZJ);//视频
                    jsonObject.put("other",other);//其他
                    jsonObject.put("doctorName","-");//医生名字
                    jsonObject.put("doctorJob","-");//医生职称
                    jsonObject.put("deptCode",map.get("code"));
                    jsonObject.put("deptName",map.get("name"));
                    array.add(jsonObject);
                }
            }else if (level==5){
                Set<JSONObject> set = new HashSet<>();
                for(SaveModel saveModel:topicModels){
                    JSONObject object1 = new JSONObject();
                    BaseDoctorDO doctorDO = doctorDao.findById(saveModel.getDoctor());
                    List<BaseDoctorHospitalDO> doctorHospitalDOs = doctorHospitalDao.findByDoctorCode(saveModel.getDoctor());
                    if (doctorHospitalDOs!=null&&doctorHospitalDOs.size()!=0){
                        object1.put("deptCode",doctorHospitalDOs.get(0).getDeptCode());
                        object1.put("deptName",doctorHospitalDOs.get(0).getDeptName());
                    }else {
                        object1.put("deptCode",null);
                        object1.put("deptName",null);
                    }
                    object1.put("doctor",doctorDO.getId());
                    object1.put("doctorName",doctorDO.getName());//
                    object1.put("doctorJob",doctorDO.getJobTitleName());//
                    object1.put("doctor",doctorDO.getId());
                    set.add(object1);
                }
                for (JSONObject jsonObject:set){
                    Long topic = 0L;
                    Long vedio =0L;
                    Long synegy = 0L;
                    Long topicZJ = 0L;
                    Long vedioZJ =0L;
                    Long other =0L;
                    for(SaveModel saveModel:topicModels){
                        if(jsonObject.getString("doctor").equalsIgnoreCase(saveModel.getDoctor())){
                            if (saveModel.getResult1()>0){
                                topic+=1;
                            }
                        }
                    }
                    for(SaveModel saveModel:vedioModels){
                        if(jsonObject.getString("doctor").equalsIgnoreCase(saveModel.getDoctor())){
                            if (saveModel.getResult1()>0){
                                vedio+=1;
                            }
                        }
                    }
                    for(SaveModel saveModel:synegyModels){
                        if(jsonObject.getString("doctor").equalsIgnoreCase(saveModel.getDoctor())){
                            if (saveModel.getResult1()>0){
                                synegy+=1;
                            }
                        }
                    }
                    for(SaveModel saveModel:specialistModels) {
                        if (jsonObject.getString("doctor").equalsIgnoreCase(saveModel.getDoctor())) {
                            if (saveModel.getResult1()>0){
                                topicZJ+=1;
                            }
                        }
                    }
                    for(SaveModel saveModel:specialistSPModels) {
                        if (jsonObject.getString("doctor").equalsIgnoreCase(saveModel.getDoctor())) {
                            if (saveModel.getResult1()>0){
                                vedioZJ+=1;
                            }
                        }
                    }
                    jsonObject.put("topic",topic);//图文
                    jsonObject.put("vedio",vedio);//视频
                    jsonObject.put("topicZJ",topicZJ);//图文
                    jsonObject.put("vedioZJ",vedioZJ);//视频
                    jsonObject.put("synegy",synegy);//协同
                    jsonObject.put("other",other);//其他
                    array.add(jsonObject);
                }
            }
            object.put("data",array);
        }
        return object;
    }


    /**
     * 获取2个数的百分比
     *
     * @param first
     * @param second
     * @param i
     * @return
     */
    public String getRange(int first, int second, int i) {
        if (second == 0 && first > 0) {
            return "100%";
        } else if (second == 0 && first == 0) {
            return "0%";
        }
        float size = (float) (first * 100) / second;
        DecimalFormat df = new DecimalFormat("0");//格式化小数，不足的补0
        String filesize = df.format(size);
        return filesize + "%";
    }

    public String getTwoRange(int first, int second, int i) {
        if (second == 0 && first > 0) {
            return "100%";
        } else if (second == 0 && first == 0) {
            return "0%";
        }
        float size = (float) (first * 100) / second;
        DecimalFormat df = new DecimalFormat("0.00");//格式化小数，不足的补0
        String filesize = df.format(size);
        return filesize + "%";
    }

    public Double getDoubleRange(Double first, Double second, int i) {
        if (second == 0 && first > 0) {
            return 100.0;
        } else if (second == 0 && first == 0) {
            return 0.0;
        }
        Double size =first / second;
        DecimalFormat df = new DecimalFormat("0.00");//格式化小数，不足的补0
        Double filesize = Double.parseDouble(df.format(size));
        return filesize ;
    }

    /**
     * 总体分析 折线图 按日--0级维度1级维度
     *
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param lowCode
     * @return
     * @throws ParseException
     */
    public JSONArray dateTotalStatistics2(String startDate, String endDate, String area, int level, String index, String lowCode, String timelevel,String lowCode2) throws Exception {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        List<SaveModel> saveModels = new ArrayList<>();
        //startDate = DateUtil.getNextDay(startDate,-1);
        if (StringUtils.isNotBlank(lowCode)) {
            if (StringUtils.isNoneBlank(lowCode2)){
                saveModels = elasticsearchUtil.findLineChartDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, SaveModel.interval_day, lowCode,lowCode2);
            }else {
                saveModels = elasticsearchUtil.findLineChartDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, SaveModel.interval_day, lowCode);
            }
        }else if(StringUtils.isNoneBlank(lowCode2)&&!StringUtils.isNoneBlank(lowCode)){
            saveModels = elasticsearchUtil.findLineChartDateQuotaLevel2OnlySlaveKey2(startDate, endDate, area, level, index, timelevel, SaveModel.interval_day,lowCode2);
        }else {
            saveModels = elasticsearchUtil.findLineChartDateQuotaLevel0(startDate, endDate, area, level, index, timelevel, SaveModel.interval_day);
        }
        List<JSONObject> result = new ArrayList<>();

//        if (saveModels != null && saveModels.size() >0) {
        List<Map<String, Object>> resultList = DateUtil.findDates(dateFormat.parse(startDate), dateFormat.parse(DateUtil.getNextDay(endDate, 1)));
//            result.clear();
        for (Map<String, Object> one : resultList) {
            JSONObject json = new JSONObject();
            json.put("range", one.get("date"));
            json.put("amount", 0);
            json.put("num",0.00);
            result.add(json);
        }
//        }
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        if (saveModels != null) {
            // 计算结果
            for (SaveModel saveModel : saveModels) {
                JSONObject json = new JSONObject();
                String range = null;
                if (saveModel.getQuotaDate() != null) {
                    range = df.format(saveModel.getQuotaDate());
                }
                double num = saveModel.getResult1();
                long amount = saveModel.getResult2().longValue();
                for(JSONObject obj : result){
                    if((obj.get("range")+"").equals(range)){
                        obj.put("amount", amount);
                        obj.put("num",decimalFormat.format(num));
                    }
                }

//                json.put("range", range);
//                json.put("amount", amount);
//                result.add(json);
            }
//            if (saveModels != null && saveModels.size() == 1 && saveModels.get(0).getHospital() == null) {
//                List<Map<String, Object>> resultList = DateUtil.findDates(dateFormat.parse(startDate), dateFormat.parse(DateUtil.getNextDay(endDate, 1)));
//                result.clear();
//                for (Map<String, Object> map : resultList) {
//                    JSONObject json = new JSONObject();
//                    json.put("range", map.get("date"));
//                    json.put("amount", 0);
//                    result.add(json);
//                }
//            }
//            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
//            Date startDate1 = sf.parse(startDate);
//            Date endDate1 = sf.parse(endDate);
//            long days = DateUtil.getDays(startDate1,endDate1);
//            Calendar calendar = Calendar.getInstance();
//            calendar.setTime(startDate1);
//            List<JSONObject> resultTemp = new ArrayList<>();
//            for(int i=1;i<=days;i++){
//                calendar.add(calendar.DATE,i);//把日期往后增加一天.整数往后推,负数往前移动
//                String dateString = sf.format(calendar.getTime());
//                Map<String, Object> map = new HashMap<>();
//                map.put("range",sf.format(calendar.getTime()));
//                map.put()
//            }

            // 排序
            result.sort(new Comparator<JSONObject>() {
                @Override
                public int compare(JSONObject o1, JSONObject o2) {
                    if (o1.getString("range").compareTo(o2.getString("range")) > 0) {
                        return 1;
                    } else if (o1.getString("range").compareTo(o2.getString("range")) < 0) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            });
            JSONArray jsonArray = new JSONArray();
            for (JSONObject object:result){
                jsonArray.add(object);
            }

            return jsonArray;
        } else {
            return new JSONArray();
        }
    }


    /**
     * 总体分析 折线图 按日--0级维度1级维度--两位小数
     *
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param lowCode
     * @return
     * @throws ParseException
     */
    public JSONArray dateTotalStatistics3(String startDate, String endDate, String area, int level, String index, String lowCode, String timelevel,String lowCode2) throws Exception {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        List<SaveModel> saveModels = new ArrayList<>();
        //startDate = DateUtil.getNextDay(startDate,-1);
        if (StringUtils.isNotBlank(lowCode)) {
            if (StringUtils.isNoneBlank(lowCode2)){
                saveModels = elasticsearchUtil.findLineChartDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, SaveModel.interval_day, lowCode,lowCode2);
            }else {
                saveModels = elasticsearchUtil.findLineChartDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, SaveModel.interval_day, lowCode);
            }
        }else if(StringUtils.isNoneBlank(lowCode2)&&!StringUtils.isNoneBlank(lowCode)){
            saveModels = elasticsearchUtil.findLineChartDateQuotaLevel2OnlySlaveKey2(startDate, endDate, area, level, index, timelevel, SaveModel.interval_day,lowCode2);
        }else {
            saveModels = elasticsearchUtil.findLineChartDateQuotaLevel0(startDate, endDate, area, level, index, timelevel, SaveModel.interval_day);
        }
        List<JSONObject> result = new ArrayList<>();

//        if (saveModels != null && saveModels.size() >0) {
        List<Map<String, Object>> resultList = DateUtil.findDates(dateFormat.parse(startDate), dateFormat.parse(DateUtil.getNextDay(endDate, 1)));
//            result.clear();
        for (Map<String, Object> one : resultList) {
            JSONObject json = new JSONObject();
            json.put("range", one.get("date"));
            json.put("amount", 0);
            json.put("num",0.00);
            result.add(json);
        }
//        }

        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        if (saveModels != null) {
            // 计算结果
            for (SaveModel saveModel : saveModels) {
                JSONObject json = new JSONObject();
                String range = null;
                if (saveModel.getQuotaDate() != null) {
                    range = df.format(saveModel.getQuotaDate());
                }
                double num = saveModel.getResult1();
                long amount = saveModel.getResult2().longValue();
                for(JSONObject obj : result){
                    if((obj.get("range")+"").equals(range)){
                        obj.put("amount", amount);
                        obj.put("num",decimalFormat.format(num));
                    }
                }

//                json.put("range", range);
//                json.put("amount", amount);
//                result.add(json);
            }
//            if (saveModels != null && saveModels.size() == 1 && saveModels.get(0).getHospital() == null) {
//                List<Map<String, Object>> resultList = DateUtil.findDates(dateFormat.parse(startDate), dateFormat.parse(DateUtil.getNextDay(endDate, 1)));
//                result.clear();
//                for (Map<String, Object> map : resultList) {
//                    JSONObject json = new JSONObject();
//                    json.put("range", map.get("date"));
//                    json.put("amount", 0);
//                    result.add(json);
//                }
//            }
//            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
//            Date startDate1 = sf.parse(startDate);
//            Date endDate1 = sf.parse(endDate);
//            long days = DateUtil.getDays(startDate1,endDate1);
//            Calendar calendar = Calendar.getInstance();
//            calendar.setTime(startDate1);
//            List<JSONObject> resultTemp = new ArrayList<>();
//            for(int i=1;i<=days;i++){
//                calendar.add(calendar.DATE,i);//把日期往后增加一天.整数往后推,负数往前移动
//                String dateString = sf.format(calendar.getTime());
//                Map<String, Object> map = new HashMap<>();
//                map.put("range",sf.format(calendar.getTime()));
//                map.put()
//            }

            // 排序
            result.sort(new Comparator<JSONObject>() {
                @Override
                public int compare(JSONObject o1, JSONObject o2) {
                    if (o1.getString("range").compareTo(o2.getString("range")) > 0) {
                        return 1;
                    } else if (o1.getString("range").compareTo(o2.getString("range")) < 0) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            });
            JSONArray jsonArray = new JSONArray();
            for (JSONObject object:result){
                jsonArray.add(object);
            }

            return jsonArray;
        } else {
            return new JSONArray();
        }
    }



    /**
     * 按周统计 折线图
     *
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param lowCode
     * @return
     * @throws Exception
     */
    private JSONArray weekTotalStatistics(String startDate, String endDate, String area, int level, String index, String lowCode, String timelevel) throws Exception {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        // 起始日期
        Calendar start = Calendar.getInstance();
        start.setTime(DateUtil.strToDate(startDate, DateUtil.YYYY_MM_DD));
        // 第一个统计周期结束日期
        String firstEnd = "";
        // 结束日期
        Calendar end = Calendar.getInstance();
        //因为统计时间是统计到当前时间的前一天，所以这里的时间是提前一天
        Calendar temp = Calendar.getInstance();
        temp.setTime(DateUtil.strToDate(endDate, DateUtil.YYYY_MM_DD));
//        temp.add(Calendar.DAY_OF_MONTH, -1);
        end.setTime(temp.getTime());
        // 起始日期为周几
        int week = start.get(Calendar.DAY_OF_WEEK);
        int incre = 7 - week + 1;

        // 日期集合
        List<Calendar> days = new ArrayList<>();
        days.add(start);
        boolean flag = true;
        int i = 0;

        if (startDate.compareTo(endDate) == 0) {
            flag = false;
            days.add(end);
            firstEnd = df.format(end.getTime());
        }

        // 计算统计日期
        while (flag) {
            Calendar next = Calendar.getInstance();
            next.setTime(days.get(days.size() - 1).getTime());

            if (i == 0) {
                if (incre != 7) {
                    next.add(Calendar.DATE, incre);
                }
            } else {
                next.add(Calendar.DATE, 7);
            }
            if (next.getTime().before(DateUtil.strToDate(endDate, "yyyy-MM-dd"))) {
                days.add(next);
                if (i == 0) {
                    firstEnd = df.format(next.getTime());
                }
            } else {
                days.add(end);
                flag = false;
                if (i == 0) {
                    firstEnd = df.format(end.getTime());
                }
            }

            i++;
        }

        // 结果集
        Map<String, JSONObject> countResult = new HashMap<>();

//        Date dd = df.parse();

        // 算出每个查询周期
        for (int j = 0; j < days.size() - 1; j++) {
            String startStr = "";
            String endStr = df.format(days.get(j + 1).getTime());

            // 起始、截止日期
            if (j == 0) {
                startStr = df.format(days.get(j).getTime());
            } else {
                Calendar cal = Calendar.getInstance();
                cal.setTime(days.get(j).getTime());
                cal.add(Calendar.DATE, 1);
                startStr = df.format(cal.getTime());
            }

            JSONObject range = new JSONObject();
            range.put("range", endStr);
            range.put("amount", 0);
            range.put("num",0.00);
            countResult.put(endStr, range);


//            if(!DateUtil.getSundayOfThisDate(new Date()).equals(df.format(new Date()))){
//                JSONObject range2 = new JSONObject();
//                range2.put("range", endDate);
//                range2.put("amount", 0);
//                countResult.put(df.format(new Date()), range2);
//            };
        }

        if (startDate.equals(df.format(new Date()))) {
            Calendar preDate = Calendar.getInstance();
            preDate.setTime(df.parse(endDate));
            preDate.add(Calendar.DATE, -1);

            startDate = df.format(preDate.getTime());
        }

        List<SaveModel> saveModels = new ArrayList<>();
        if (StringUtils.isNotBlank(lowCode)) {
            saveModels = elasticsearchUtil.findLineChartDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, SaveModel.interval_day, lowCode);
        } else {
            saveModels = elasticsearchUtil.findLineChartDateQuotaLevel0(startDate, endDate, area, level, index, timelevel, SaveModel.interval_day);
        }
        if (saveModels != null) {
            // 计算结果
            for (SaveModel saveModel : saveModels) {
                String range = "";
                if (saveModel.getQuotaDate() != null) {
                    Calendar quotaDate = Calendar.getInstance();
                    quotaDate.setTime(saveModel.getQuotaDate());
                    /*int thisWeek = start.get(Calendar.DAY_OF_WEEK);
                    int thisIncre = 7 - week;*/
                    quotaDate.add(Calendar.DATE, 6);
                    range = df.format(quotaDate.getTime());

                }
                JSONObject json = countResult.get(range);
//                //因为上述时间集提前一天  但是前端是显示当前时间，所以这里给调整回去
//                if (range.equals(df.format(temp.getTime()))) {
//                    json.put("range", endDate);
//                }
                DecimalFormat decimalFormat = new DecimalFormat("0.00");
                if (json != null) {
                    long amount = saveModel.getResult2().longValue();
                    double num = saveModel.getResult1();
                    long previousAmount = Long.valueOf(json.get("amount").toString());
                    double previousNum = Double.parseDouble(json.get("num").toString());
                    json.put("amount", amount+previousAmount);
                    json.put("num",decimalFormat.format(num+previousNum));
                }
            }

            List<JSONObject> result = new ArrayList<>(countResult.values());

            // 排序
            result.sort(new Comparator<JSONObject>() {
                @Override
                public int compare(JSONObject o1, JSONObject o2) {
                    if (o1.getString("range").compareTo(o2.getString("range")) > 0) {
                        return 1;
                    } else if (o1.getString("range").compareTo(o2.getString("range")) < 0) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            });
            JSONArray jsonArray = new JSONArray();
            for (JSONObject object:result){
                jsonArray.add(object);
            }

            return jsonArray;
        } else {
            return new JSONArray();
        }
    }

    /**
     * 按周统计 折线图
     *
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param lowCode
     * @return
     * @throws Exception
     */
    private JSONArray weekTotalStatisticsDf(String startDate, String endDate, String area, int level, String index, String lowCode, String timelevel) throws Exception {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        // 起始日期
        Calendar start = Calendar.getInstance();
        start.setTime(DateUtil.strToDate(startDate, DateUtil.YYYY_MM_DD));
        // 第一个统计周期结束日期
        String firstEnd = "";
        // 结束日期
        Calendar end = Calendar.getInstance();
        //因为统计时间是统计到当前时间的前一天，所以这里的时间是提前一天
        Calendar temp = Calendar.getInstance();
        temp.setTime(DateUtil.strToDate(endDate, DateUtil.YYYY_MM_DD));
//        temp.add(Calendar.DAY_OF_MONTH, -1);
        end.setTime(temp.getTime());
        // 起始日期为周几
        int week = start.get(Calendar.DAY_OF_WEEK);
        int incre = 7 - week + 1;

        // 日期集合
        List<Calendar> days = new ArrayList<>();
        days.add(start);
        boolean flag = true;
        int i = 0;

        if (startDate.compareTo(endDate) == 0) {
            flag = false;
            days.add(end);
            firstEnd = df.format(end.getTime());
        }

        // 计算统计日期
        while (flag) {
            Calendar next = Calendar.getInstance();
            next.setTime(days.get(days.size() - 1).getTime());

            if (i == 0) {
                if (incre != 7) {
                    next.add(Calendar.DATE, incre);
                }
            } else {
                next.add(Calendar.DATE, 7);
            }
            if (next.getTime().before(DateUtil.strToDate(endDate, "yyyy-MM-dd"))) {
                days.add(next);
                if (i == 0) {
                    firstEnd = df.format(next.getTime());
                }
            } else {
                days.add(end);
                flag = false;
                if (i == 0) {
                    firstEnd = df.format(end.getTime());
                }
            }

            i++;
        }

        // 结果集
        Map<String, JSONObject> countResult = new HashMap<>();

//        Date dd = df.parse();

        // 算出每个查询周期
        for (int j = 0; j < days.size() - 1; j++) {
            String startStr = "";
            String endStr = df.format(days.get(j + 1).getTime());

            // 起始、截止日期
            if (j == 0) {
                startStr = df.format(days.get(j).getTime());
            } else {
                Calendar cal = Calendar.getInstance();
                cal.setTime(days.get(j).getTime());
                cal.add(Calendar.DATE, 1);
                startStr = df.format(cal.getTime());
            }

            JSONObject range = new JSONObject();
            range.put("range", endStr);
            range.put("amount", 0);
            range.put("num",0.00);
            countResult.put(endStr, range);


//            if(!DateUtil.getSundayOfThisDate(new Date()).equals(df.format(new Date()))){
//                JSONObject range2 = new JSONObject();
//                range2.put("range", endDate);
//                range2.put("amount", 0);
//                countResult.put(df.format(new Date()), range2);
//            };
        }

        if (startDate.equals(df.format(new Date()))) {
            Calendar preDate = Calendar.getInstance();
            preDate.setTime(df.parse(endDate));
            preDate.add(Calendar.DATE, -1);

            startDate = df.format(preDate.getTime());
        }


        List<SaveModel> saveModels = new ArrayList<>();
        if (StringUtils.isNotBlank(lowCode)) {
            saveModels = elasticsearchUtil.findLineChartDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, SaveModel.interval_week, lowCode);
        } else {
            saveModels = elasticsearchUtil.findLineChartDateQuotaLevel0(startDate, endDate, area, level, index, timelevel, SaveModel.interval_week);
        }
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        if (saveModels != null) {
            // 计算结果
            for (SaveModel saveModel : saveModels) {
                String range = "";
                if (saveModel.getQuotaDate() != null) {
                    Calendar quotaDate = Calendar.getInstance();
                    quotaDate.setTime(saveModel.getQuotaDate());
                    quotaDate.add(Calendar.DATE, 6);
                    range = df.format(quotaDate.getTime());

                }
                JSONObject json = countResult.get(range);
//                //因为上述时间集提前一天  但是前端是显示当前时间，所以这里给调整回去
//                if (range.equals(df.format(temp.getTime()))) {
//                    json.put("range", endDate);
//                }
                if (json != null) {
                    long amount = saveModel.getResult2().longValue();
                    double num = saveModel.getResult1();
                    json.put("amount", amount);
                    json.put("num",decimalFormat.format(num));
                }
            }

            List<JSONObject> result = new ArrayList<>(countResult.values());

            // 排序
            result.sort(new Comparator<JSONObject>() {
                @Override
                public int compare(JSONObject o1, JSONObject o2) {
                    if (o1.getString("range").compareTo(o2.getString("range")) > 0) {
                        return 1;
                    } else if (o1.getString("range").compareTo(o2.getString("range")) < 0) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            });
            JSONArray jsonArray = new JSONArray();
            for (JSONObject object:result){
                jsonArray.add(object);
            }

            return jsonArray;
        } else {
            return new JSONArray();
        }
    }

    private JSONArray weekTotalStatistics2(String startDate, String endDate, String area, int level, String index, String lowCode, String timelevel,String lowCode2) throws Exception {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        // 起始日期
        Calendar start = Calendar.getInstance();
        start.setTime(DateUtil.strToDate(startDate, DateUtil.YYYY_MM_DD));
        // 第一个统计周期结束日期
        String firstEnd = "";
        // 结束日期
        Calendar end = Calendar.getInstance();
        //因为统计时间是统计到当前时间的前一天，所以这里的时间是提前一天
        Calendar temp = Calendar.getInstance();
        temp.setTime(DateUtil.strToDate(endDate, DateUtil.YYYY_MM_DD));
//        temp.add(Calendar.DAY_OF_MONTH, -1);
        end.setTime(temp.getTime());
        // 起始日期为周几
        int week = start.get(Calendar.DAY_OF_WEEK);
        int incre = 7 - week + 1;

        // 日期集合
        List<Calendar> days = new ArrayList<>();
        days.add(start);
        boolean flag = true;
        int i = 0;

        if (startDate.compareTo(endDate) == 0) {
            flag = false;
            days.add(end);
            firstEnd = df.format(end.getTime());
        }

        // 计算统计日期
        while (flag) {
            Calendar next = Calendar.getInstance();
            next.setTime(days.get(days.size() - 1).getTime());

            if (i == 0) {
                if (incre != 7) {
                    next.add(Calendar.DATE, incre);
                }
            } else {
                next.add(Calendar.DATE, 7);
            }
            if (next.getTime().before(DateUtil.strToDate(endDate, "yyyy-MM-dd"))) {
                days.add(next);
                if (i == 0) {
                    firstEnd = df.format(next.getTime());
                }
            } else {
                days.add(end);
                flag = false;
                if (i == 0) {
                    firstEnd = df.format(end.getTime());
                }
            }

            i++;
        }

        // 结果集
        Map<String, JSONObject> countResult = new HashMap<>();

//        Date dd = df.parse();

        // 算出每个查询周期
        for (int j = 0; j < days.size() - 1; j++) {
            String startStr = "";
            String endStr = df.format(days.get(j + 1).getTime());

            // 起始、截止日期
            if (j == 0) {
                startStr = df.format(days.get(j).getTime());
            } else {
                Calendar cal = Calendar.getInstance();
                cal.setTime(days.get(j).getTime());
                cal.add(Calendar.DATE, 1);
                startStr = df.format(cal.getTime());
            }

            JSONObject range = new JSONObject();
            range.put("range", endStr);
            range.put("amount", 0);
            range.put("num",0.00);
            countResult.put(endStr, range);


//            if(!DateUtil.getSundayOfThisDate(new Date()).equals(df.format(new Date()))){
//                JSONObject range2 = new JSONObject();
//                range2.put("range", endDate);
//                range2.put("amount", 0);
//                countResult.put(df.format(new Date()), range2);
//            };
        }

        if (startDate.equals(df.format(new Date()))) {
            Calendar preDate = Calendar.getInstance();
            preDate.setTime(df.parse(endDate));
            preDate.add(Calendar.DATE, -1);

            startDate = df.format(preDate.getTime());
        }


        List<SaveModel> saveModels = new ArrayList<>();
        if (StringUtils.isNotBlank(lowCode)) {
            if (StringUtils.isNoneBlank(lowCode2)){
                saveModels = elasticsearchUtil.findLineChartDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, SaveModel.interval_week, lowCode,lowCode2);
            }else {
                saveModels = elasticsearchUtil.findLineChartDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, SaveModel.interval_week, lowCode);
            }

        }else if(StringUtils.isNoneBlank(lowCode2)&&StringUtils.isBlank(lowCode)){
            saveModels = elasticsearchUtil.findLineChartDateQuotaLevel2OnlySlaveKey2(startDate, endDate, area, level, index, timelevel, SaveModel.interval_week,lowCode2);
        }
        else {
            saveModels = elasticsearchUtil.findLineChartDateQuotaLevel0(startDate, endDate, area, level, index, timelevel, SaveModel.interval_week);
        }
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        if (saveModels != null) {
            // 计算结果
            for (SaveModel saveModel : saveModels) {
                String range = "";
                if (saveModel.getQuotaDate() != null) {
                    Calendar quotaDate = Calendar.getInstance();
                    quotaDate.setTime(saveModel.getQuotaDate());
                    quotaDate.add(Calendar.DATE, 6);
                    range = df.format(quotaDate.getTime());

                }
                JSONObject json = countResult.get(range);
//                //因为上述时间集提前一天  但是前端是显示当前时间，所以这里给调整回去
//                if (range.equals(df.format(temp.getTime()))) {
//                    json.put("range", endDate);
//                }

                if (json != null) {
                    long amount = saveModel.getResult2().longValue();
                    double num = saveModel.getResult1();
                    json.put("amount", amount);
                    json.put("num",decimalFormat.format(num));
                }
            }

            List<JSONObject> result = new ArrayList<>(countResult.values());

            // 排序
            result.sort(new Comparator<JSONObject>() {
                @Override
                public int compare(JSONObject o1, JSONObject o2) {
                    if (o1.getString("range").compareTo(o2.getString("range")) > 0) {
                        return 1;
                    } else if (o1.getString("range").compareTo(o2.getString("range")) < 0) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            });
            JSONArray jsonArray = new JSONArray();
            for (JSONObject object:result){
                jsonArray.add(object);
            }

            return jsonArray;
        } else {
            return new JSONArray();
        }
    }


    /**
     * 两位小数
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param lowCode
     * @param timelevel
     * @param lowCode2
     * @return
     * @throws Exception
     */
    private JSONArray weekTotalStatistics3(String startDate, String endDate, String area, int level, String index, String lowCode, String timelevel,String lowCode2) throws Exception {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        // 起始日期
        Calendar start = Calendar.getInstance();
        start.setTime(DateUtil.strToDate(startDate, DateUtil.YYYY_MM_DD));
        // 第一个统计周期结束日期
        String firstEnd = "";
        // 结束日期
        Calendar end = Calendar.getInstance();
        //因为统计时间是统计到当前时间的前一天，所以这里的时间是提前一天
        Calendar temp = Calendar.getInstance();
        temp.setTime(DateUtil.strToDate(endDate, DateUtil.YYYY_MM_DD));
//        temp.add(Calendar.DAY_OF_MONTH, -1);
        end.setTime(temp.getTime());
        // 起始日期为周几
        int week = start.get(Calendar.DAY_OF_WEEK);
        int incre = 7 - week + 1;

        // 日期集合
        List<Calendar> days = new ArrayList<>();
        days.add(start);
        boolean flag = true;
        int i = 0;

        if (startDate.compareTo(endDate) == 0) {
            flag = false;
            days.add(end);
            firstEnd = df.format(end.getTime());
        }

        // 计算统计日期
        while (flag) {
            Calendar next = Calendar.getInstance();
            next.setTime(days.get(days.size() - 1).getTime());

            if (i == 0) {
                if (incre != 7) {
                    next.add(Calendar.DATE, incre);
                }
            } else {
                next.add(Calendar.DATE, 7);
            }
            if (next.getTime().before(DateUtil.strToDate(endDate, "yyyy-MM-dd"))) {
                days.add(next);
                if (i == 0) {
                    firstEnd = df.format(next.getTime());
                }
            } else {
                days.add(end);
                flag = false;
                if (i == 0) {
                    firstEnd = df.format(end.getTime());
                }
            }

            i++;
        }

        // 结果集
        Map<String, JSONObject> countResult = new HashMap<>();

//        Date dd = df.parse();

        // 算出每个查询周期
        for (int j = 0; j < days.size() - 1; j++) {
            String startStr = "";
            String endStr = df.format(days.get(j + 1).getTime());

            // 起始、截止日期
            if (j == 0) {
                startStr = df.format(days.get(j).getTime());
            } else {
                Calendar cal = Calendar.getInstance();
                cal.setTime(days.get(j).getTime());
                cal.add(Calendar.DATE, 1);
                startStr = df.format(cal.getTime());
            }

            JSONObject range = new JSONObject();
            range.put("range", endStr);
            range.put("amount", 0);
            range.put("num",0.00);
            countResult.put(endStr, range);


//            if(!DateUtil.getSundayOfThisDate(new Date()).equals(df.format(new Date()))){
//                JSONObject range2 = new JSONObject();
//                range2.put("range", endDate);
//                range2.put("amount", 0);
//                countResult.put(df.format(new Date()), range2);
//            };
        }

        if (startDate.equals(df.format(new Date()))) {
            Calendar preDate = Calendar.getInstance();
            preDate.setTime(df.parse(endDate));
            preDate.add(Calendar.DATE, -1);

            startDate = df.format(preDate.getTime());
        }


        List<SaveModel> saveModels = new ArrayList<>();
        if (StringUtils.isNotBlank(lowCode)) {
            if (StringUtils.isNoneBlank(lowCode2)){
                saveModels = elasticsearchUtil.findLineChartDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, SaveModel.interval_week, lowCode,lowCode2);
            }else {
                saveModels = elasticsearchUtil.findLineChartDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, SaveModel.interval_week, lowCode);
            }

        }else if(StringUtils.isNoneBlank(lowCode2)&&StringUtils.isBlank(lowCode)){
            saveModels = elasticsearchUtil.findLineChartDateQuotaLevel2OnlySlaveKey2(startDate, endDate, area, level, index, timelevel, SaveModel.interval_week,lowCode2);
        }
        else {
            saveModels = elasticsearchUtil.findLineChartDateQuotaLevel0(startDate, endDate, area, level, index, timelevel, SaveModel.interval_week);
        }

        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        if (saveModels != null) {
            // 计算结果
            for (SaveModel saveModel : saveModels) {
                String range = "";
                if (saveModel.getQuotaDate() != null) {
                    Calendar quotaDate = Calendar.getInstance();
                    quotaDate.setTime(saveModel.getQuotaDate());
                    quotaDate.add(Calendar.DATE, 6);
                    range = df.format(quotaDate.getTime());

                }
                JSONObject json = countResult.get(range);
//                //因为上述时间集提前一天  但是前端是显示当前时间，所以这里给调整回去
//                if (range.equals(df.format(temp.getTime()))) {
//                    json.put("range", endDate);
//                }
                if (json != null) {
                    long amount = saveModel.getResult2().longValue();
                    double num = saveModel.getResult1();
                    json.put("amount", amount);
                    json.put("num",decimalFormat.format(num));
                }
            }

            List<JSONObject> result = new ArrayList<>(countResult.values());

            // 排序
            result.sort(new Comparator<JSONObject>() {
                @Override
                public int compare(JSONObject o1, JSONObject o2) {
                    if (o1.getString("range").compareTo(o2.getString("range")) > 0) {
                        return 1;
                    } else if (o1.getString("range").compareTo(o2.getString("range")) < 0) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            });
            JSONArray jsonArray = new JSONArray();
            for (JSONObject object:result){
                jsonArray.add(object);
            }

            return jsonArray;
        } else {
            return new JSONArray();
        }
    }


    /**
     * 按月统计 折线图
     *
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param lowCode
     * @return
     * @throws Exception
     */
    private JSONArray monthTotalStatistics2(String startDate, String endDate, String area, int level, String index, String lowCode, String timelevel,String lowCode2) throws Exception {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        // 起始日期
        Calendar start = Calendar.getInstance();
        start.setTime(DateUtil.strToDate(startDate, DateUtil.YYYY_MM_DD));
        // 结束日期
        Calendar end = Calendar.getInstance();
        //因为统计时间是统计到当前时间的前一天，所以这里的时间是提前一天
        Calendar temp = Calendar.getInstance();
        temp.setTime(DateUtil.strToDate(endDate, DateUtil.YYYY_MM_DD));
//        temp.add(Calendar.DAY_OF_MONTH, -1);
        end.setTime(temp.getTime());

        // 日期集合
        List<Calendar> days = new ArrayList<>();
        days.add(start);

        boolean flag = true;
        int k = 0;

        if (startDate.compareTo(endDate) == 0) {
            flag = false;
       /*     days.add(end);*/
        }

        // 统计日期计算
        while (flag) {
            Calendar next = Calendar.getInstance();
            next.setTime(days.get(days.size() - 1).getTime());
            if (k == 0) {
                next.add(Calendar.MONTH, 1);
            } else {
                next.add(Calendar.MONTH, 1);
            }
            /*next.set(Calendar.DAY_OF_MONTH, 1);
            next.add(Calendar.DAY_OF_MONTH, -1);*/

            if (next.getTime().before(DateUtil.strToDate(endDate, "yyyy-MM-dd"))) {
                days.add(next);
            } else {
         /*       days.add(end);*/
                flag = false;
            }
            k++;
        }

        // 统计结果
        Map<String, JSONObject> countResult = new HashMap<>();

        for (int i = 0; i < days.size(); i++) {
            String endStr = df.format(days.get(i).getTime());

            JSONObject range = new JSONObject();

            range.put("range", endStr);
            range.put("amount", 0);
            range.put("num",0.00);

            countResult.put(endStr, range);
        }

        if (startDate.equals(df.format(new Date()))) {
            Calendar preDate = Calendar.getInstance();
            preDate.setTime(df.parse(endDate));

            startDate = df.format(preDate.getTime());
        }
        List<SaveModel> saveModels = new ArrayList<>();
        if (StringUtils.isNotBlank(lowCode)) {
            if (StringUtils.isNoneBlank(lowCode2)){
                saveModels = elasticsearchUtil.findLineChartDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, SaveModel.interval_month, lowCode,lowCode2);
            }else {
                saveModels = elasticsearchUtil.findLineChartDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, SaveModel.interval_month, lowCode);
            }
        } else if(StringUtils.isNoneBlank(lowCode2)&&StringUtils.isBlank(lowCode)){
            saveModels = elasticsearchUtil.findLineChartDateQuotaLevel2OnlySlaveKey2(startDate, endDate, area, level, index, timelevel, SaveModel.interval_month,lowCode2);

        } else {
            saveModels = elasticsearchUtil.findLineChartDateQuotaLevel0(startDate, endDate, area, level, index, timelevel, SaveModel.interval_month);
        }

        if (saveModels != null) {
            // 计算结果
            for (SaveModel saveModel : saveModels) {
                String range = "";
                if (saveModel.getQuotaDate() != null) {
                    range = df.format(saveModel.getQuotaDate());
                }
                JSONObject json = countResult.get(range);
                //因为上述时间集提前一天  但是前端是显示当前时间，所以这里给调整回去
                /*if (range.equals(df.format(temp.getTime()))) {
                    json.put("range", endDate);
                }*/
                DecimalFormat decimalFormat = new DecimalFormat("0.00");
                if (json != null) {
                    long amount = saveModel.getResult2().longValue();
                    double num = saveModel.getResult1();
                    json.put("amount", amount);
                    json.put("num",decimalFormat.format(num));
                }
            }

            List<JSONObject> result = new ArrayList<>(countResult.values());

            // 排序
            result.sort(new Comparator<JSONObject>() {
                @Override
                public int compare(JSONObject o1, JSONObject o2) {
                    if (o1.getString("range").compareTo(o2.getString("range")) > 0) {
                        return 1;
                    } else if (o1.getString("range").compareTo(o2.getString("range")) < 0) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            });
            JSONArray jsonArray = new JSONArray();
            for (JSONObject object:result){
                jsonArray.add(object);
            }

            return jsonArray;
        } else {
            return new JSONArray();
        }
    }


    /**
     * 按月统计 折线图---两位小数
     *
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param lowCode
     * @return
     * @throws Exception
     */
    private JSONArray monthTotalStatistics3(String startDate, String endDate, String area, int level, String index, String lowCode, String timelevel,String lowCode2) throws Exception {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        // 起始日期
        Calendar start = Calendar.getInstance();
        start.setTime(DateUtil.strToDate(startDate, DateUtil.YYYY_MM_DD));
        // 结束日期
        Calendar end = Calendar.getInstance();
        //因为统计时间是统计到当前时间的前一天，所以这里的时间是提前一天
        Calendar temp = Calendar.getInstance();
        temp.setTime(DateUtil.strToDate(endDate, DateUtil.YYYY_MM_DD));
//        temp.add(Calendar.DAY_OF_MONTH, -1);
        end.setTime(temp.getTime());

        // 日期集合
        List<Calendar> days = new ArrayList<>();
        days.add(start);

        boolean flag = true;
        int k = 0;

        if (startDate.compareTo(endDate) == 0) {
            flag = false;
       /*     days.add(end);*/
        }

        // 统计日期计算
        while (flag) {
            Calendar next = Calendar.getInstance();
            next.setTime(days.get(days.size() - 1).getTime());
            if (k == 0) {
                next.add(Calendar.MONTH, 1);
            } else {
                next.add(Calendar.MONTH, 1);
            }
            /*next.set(Calendar.DAY_OF_MONTH, 1);
            next.add(Calendar.DAY_OF_MONTH, -1);*/

            if (next.getTime().before(DateUtil.strToDate(endDate, "yyyy-MM-dd"))) {
                days.add(next);
            } else {
         /*       days.add(end);*/
                flag = false;
            }
            k++;
        }

        // 统计结果
        Map<String, JSONObject> countResult = new HashMap<>();

        for (int i = 0; i < days.size(); i++) {
            String endStr = df.format(days.get(i).getTime());

            JSONObject range = new JSONObject();

            range.put("range", endStr);
            range.put("amount", 0);
            range.put("num",0.00);

            countResult.put(endStr, range);
        }

        if (startDate.equals(df.format(new Date()))) {
            Calendar preDate = Calendar.getInstance();
            preDate.setTime(df.parse(endDate));

            startDate = df.format(preDate.getTime());
        }
        List<SaveModel> saveModels = new ArrayList<>();
        if (StringUtils.isNotBlank(lowCode)) {
            if (StringUtils.isNoneBlank(lowCode2)){
                saveModels = elasticsearchUtil.findLineChartDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, SaveModel.interval_month, lowCode,lowCode2);
            }else {
                saveModels = elasticsearchUtil.findLineChartDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, SaveModel.interval_month, lowCode);
            }
        } else if(StringUtils.isNoneBlank(lowCode2)&&StringUtils.isBlank(lowCode)){
            saveModels = elasticsearchUtil.findLineChartDateQuotaLevel2OnlySlaveKey2(startDate, endDate, area, level, index, timelevel, SaveModel.interval_month,lowCode2);

        } else {
            saveModels = elasticsearchUtil.findLineChartDateQuotaLevel0(startDate, endDate, area, level, index, timelevel, SaveModel.interval_month);
        }

        DecimalFormat decimalFormat = new DecimalFormat("0.00");

        if (saveModels != null) {
            // 计算结果
            for (SaveModel saveModel : saveModels) {
                String range = "";
                if (saveModel.getQuotaDate() != null) {
                    range = df.format(saveModel.getQuotaDate());
                }
                JSONObject json = countResult.get(range);
                //因为上述时间集提前一天  但是前端是显示当前时间，所以这里给调整回去
                /*if (range.equals(df.format(temp.getTime()))) {
                    json.put("range", endDate);
                }*/
                if (json != null) {
                    long amount = saveModel.getResult2().longValue();
                    double num = saveModel.getResult1();
                    json.put("amount", amount);
                    json.put("num",decimalFormat.format(num));
                }
            }

            List<JSONObject> result = new ArrayList<>(countResult.values());

            // 排序
            result.sort(new Comparator<JSONObject>() {
                @Override
                public int compare(JSONObject o1, JSONObject o2) {
                    if (o1.getString("range").compareTo(o2.getString("range")) > 0) {
                        return 1;
                    } else if (o1.getString("range").compareTo(o2.getString("range")) < 0) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            });
            JSONArray jsonArray = new JSONArray();
            for (JSONObject object:result){
                jsonArray.add(object);
            }

            return jsonArray;
        } else {
            return new JSONArray();
        }
    }


    /**
     * 按月统计 折线图-排班
     *
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param lowCode
     * @return
     * @throws Exception
     */
    private JSONArray monthTotalStatistics2AndMonth(String startDate, String endDate, String area, int level, String index, String lowCode, String timelevel) throws Exception {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        // 起始日期
        Calendar start = Calendar.getInstance();
        start.setTime(DateUtil.strToDate(startDate, DateUtil.YYYY_MM_DD));
        // 结束日期
        Calendar end = Calendar.getInstance();
        //因为统计时间是统计到当前时间的前一天，所以这里的时间是提前一天
        Calendar temp = Calendar.getInstance();
        temp.setTime(DateUtil.strToDate(endDate, DateUtil.YYYY_MM_DD));
//        temp.add(Calendar.DAY_OF_MONTH, -1);
        end.setTime(temp.getTime());

        // 日期集合
        List<Calendar> days = new ArrayList<>();
        days.add(start);

        boolean flag = true;
        int k = 0;

        if (startDate.compareTo(endDate) == 0) {
            flag = false;
       /*     days.add(end);*/
        }

        // 统计日期计算
        while (flag) {
            Calendar next = Calendar.getInstance();
            next.setTime(days.get(days.size() - 1).getTime());
            if (k == 0) {
                next.add(Calendar.MONTH, 1);
            } else {
                next.add(Calendar.MONTH, 1);
            }
            /*next.set(Calendar.DAY_OF_MONTH, 1);
            next.add(Calendar.DAY_OF_MONTH, -1);*/

            if (next.getTime().before(DateUtil.strToDate(endDate, "yyyy-MM-dd"))) {
                days.add(next);
            } else {
         /*       days.add(end);*/
                flag = false;
            }
            k++;
        }

        // 统计结果
        Map<String, JSONObject> countResult = new HashMap<>();

        for (int i = 0; i < days.size(); i++) {
            String endStr = df.format(days.get(i).getTime());

            JSONObject range = new JSONObject();

            range.put("range", endStr);
            range.put("amount", 0);
            range.put("num",0.00);

            countResult.put(endStr, range);
        }

        if (startDate.equals(df.format(new Date()))) {
            Calendar preDate = Calendar.getInstance();
            preDate.setTime(df.parse(endDate));

            startDate = df.format(preDate.getTime());
        }
        List<SaveModel> saveModels = new ArrayList<>();
        if (StringUtils.isNotBlank(lowCode)) {
            saveModels = elasticsearchUtil.findDateQuotaLevel0AndPaibanLine(startDate, endDate, area, level, index, timelevel, SaveModel.interval_month, lowCode);
        } else {
            saveModels = elasticsearchUtil.findDateQuotaLevel0AndPaibanLine(startDate, endDate, area, level, index, timelevel, SaveModel.interval_month,null);
        }
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        if (saveModels != null) {
            // 计算结果
            for (SaveModel saveModel : saveModels) {
                String range = "";
                if (saveModel.getQuotaDate() != null) {
                    range = df.format(saveModel.getQuotaDate());
                }
                JSONObject json = countResult.get(range);
                //因为上述时间集提前一天  但是前端是显示当前时间，所以这里给调整回去
                /*if (range.equals(df.format(temp.getTime()))) {
                    json.put("range", endDate);
                }*/
                if (json != null) {
                    long amount = saveModel.getResult2().longValue();
                    double num = saveModel.getResult1();
                    json.put("amount", amount);
                    json.put("num",decimalFormat.format(num));
                }
            }

            List<JSONObject> result = new ArrayList<>(countResult.values());

            // 排序
            result.sort(new Comparator<JSONObject>() {
                @Override
                public int compare(JSONObject o1, JSONObject o2) {
                    if (o1.getString("range").compareTo(o2.getString("range")) > 0) {
                        return 1;
                    } else if (o1.getString("range").compareTo(o2.getString("range")) < 0) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            });
            JSONArray jsonArray = new JSONArray();
            for (JSONObject object:result){
                jsonArray.add(object);
            }

            return jsonArray;
        } else {
            return new JSONArray();
        }
    }


    /**
     * 专科咨询统计总量
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @param area 区域
     * @param level
     * @param index
     * @return
     * @throws Exception
     */
    public JSONObject getSpecialConsultHead(String startDate, String endDate, String area, int level, String index) throws Exception {
        //总量
        SaveModel saveModel = null;
        //已回复
        SaveModel saveModel1 = null;
        //已结束
        SaveModel saveModel2 = null;
        //未回复
        SaveModel saveModel3 = null;
        //居民取消
        SaveModel saveModel4 = null;
        //进行中
        SaveModel saveModel5 = null;
        saveModel = elasticsearchUtil.findOneDateQuotaLevel0(endDate, endDate, area, level, "7", SaveModel.timeLevel_DDL);
        saveModel1 = elasticsearchUtil.findOneDateQuotaLevel1(endDate, area, level, "6", SaveModel.timeLevel_DDL,"1");
        saveModel3 = elasticsearchUtil.findOneDateQuotaLevel1(endDate, area, level, "6", SaveModel.timeLevel_DDL,"0");
        saveModel4 = elasticsearchUtil.findOneDateQuotaLevel1(endDate, area, level, "7", SaveModel.timeLevel_DDL,"-1");
        saveModel5 = elasticsearchUtil.findOneDateQuotaLevel1(endDate, area, level, "7", SaveModel.timeLevel_DDL,"0");
        saveModel2 = elasticsearchUtil.findOneDateQuotaLevel1(endDate, area, level, "7", SaveModel.timeLevel_DDL,"1");
        JSONObject object = new JSONObject();
        object.put("specialConsultTotal",saveModel.getResult1());
        object.put("haveReplyTotal",saveModel1.getResult1());
        object.put("endTotal",saveModel2.getResult1());
        object.put("notReplyTotal",saveModel3.getResult1());
        object.put("cancelTotal",saveModel4.getResult1());
        object.put("comingTotal",saveModel5.getResult1());
        object.put("notReplyRate",getRange(saveModel3.getResult1().intValue(),saveModel.getResult1().intValue(),2));//未回复率
        return object;
    }


    /**
     * 专科咨询统计曲线
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param interval
     * @param level2_type
     * @return
     * @throws Exception
     */
    public JSONObject getSpecialConsultLine(String startDate, String endDate, String area, int level, String index,int interval, String level2_type) throws Exception {
        //问诊量
        JSONObject object = new JSONObject();
        if (interval==1){
            JSONArray array = dateTotalStatistics2(startDate,endDate,area,level,index,null,SaveModel.timeLevel_ZL,null);
            object.put("data",array);
        }else if (interval==2){
            JSONArray array = weekTotalStatistics(startDate,endDate,area,level,index,null,SaveModel.timeLevel_ZL);
            object.put("data",array);
        }else if (interval==3){
            JSONArray array = monthTotalStatistics2(startDate,endDate,area,level,index,null,SaveModel.timeLevel_ZL,null);
            object.put("data",array);
        }
        return object;
    }


    /**
     * 专科咨询统计表格
     * @param startTime
     * @param endTime
     * @param level
     * @param area
     * @param lowLevel
     * @return
     * @throws Exception
     */
    public JSONObject getConsultingStatisticsList(String startTime,String endTime,int level, String area, String lowLevel) throws Exception {
        JSONObject result = new JSONObject();
//        timeKey= "2017-11-01 00:00:00";
        //已结束
        List<SaveModel> endTotal = elasticsearchUtil.findListDateQuotaLevel1(endTime, endTime, area, level, "7", SaveModel.timeLevel_DDL, lowLevel,"1");
        //咨询总数
        List<SaveModel> total = elasticsearchUtil.findListDateQuotaLevel0(endTime, endTime, area, level, "6", SaveModel.timeLevel_DDL, lowLevel);
        //未回复数
        List<SaveModel> noRelyTotal = elasticsearchUtil.findListDateQuotaLevel1(endTime, endTime, area, level, "6", SaveModel.timeLevel_DDL, lowLevel,"0");
//        JSONArray rely = new JSONArray(relyVal);
//        JSONArray total = new JSONArray(relyTotal);
//        JSONArray noRely = new JSONArray(noRelyTotal);
        result.put("resultList", getCoutList(level, lowLevel, endTotal, total, noRelyTotal));
        return result;
    }



    public List<Map<String, Object>> getCoutList1(Integer level, String lowLevel, List<SaveModel> endConsult, List<SaveModel> total, List<SaveModel> noReceive) {
        Map<String, Object> relyMap = new HashMap<>();
        Map<String, Object> totalMap = new HashMap<>();
        Map<String, Object> noReceiveMap = new HashMap<>();
        org.json.JSONObject result = new org.json.JSONObject();
        String low_level = StringUtils.isEmpty(lowLevel) ? String.valueOf(level + 1) : lowLevel;
        //转换结束数
        for (SaveModel saveModel : endConsult) {
            if (SaveModel.doctorLevel.equals(low_level)) {
                relyMap.put(saveModel.getDoctor(), saveModel);
            } else if (SaveModel.deptLevel.equals(low_level)) {
                relyMap.put(saveModel.getDept(), saveModel);
            }else if (SaveModel.OrgLevel.equals(low_level)) {
                relyMap.put(saveModel.getHospital(), saveModel);
            }
        }
        ;

        //转换总咨询数
        for (SaveModel saveModel : total) {
            if (SaveModel.doctorLevel.equals(low_level)) {
                totalMap.put(saveModel.getDoctor(), saveModel);
            } else if (SaveModel.deptLevel.equals(low_level)) {
                totalMap.put(saveModel.getDept(), saveModel);
            }else if (SaveModel.OrgLevel.equals(low_level)) {
                totalMap.put(saveModel.getHospital(), saveModel);
            }
        }
        ;
        //转换已结束
        for (SaveModel saveModel : noReceive) {
            if (SaveModel.doctorLevel.equals(low_level)) {
                noReceiveMap.put(saveModel.getDoctor(), saveModel);
            } else if (SaveModel.deptLevel.equals(low_level)) {
                noReceiveMap.put(saveModel.getDept(), saveModel);
            }else if (SaveModel.OrgLevel.equals(low_level)) {
                noReceiveMap.put(saveModel.getHospital(), saveModel);
            }
        }
        ;
        List<Map<String, Object>> resultMaps = new ArrayList<>();
        for (String key : totalMap.keySet()) {
            Map<String, Object> rs = new HashMap<>();
            SaveModel relyRs = (SaveModel) relyMap.get(key);
            SaveModel totalRs = (SaveModel) totalMap.get(key);
            SaveModel onRelyRs = (SaveModel) noReceiveMap.get(key);
            if (relyRs == null || totalRs == null || onRelyRs == null) {
                continue;
            }
            //合并结果集
            Integer totalNm = totalRs.getResult2().intValue();
            Integer endNm = relyRs.getResult2().intValue();
            Integer noRelyNm = onRelyRs.getResult2().intValue();
//            rs.put("name", relyRs.get(area+"Name"));
            if (SaveModel.doctorLevel.equals(low_level)) {
                rs.put("name", relyRs.getDoctorName());
            } else if (SaveModel.deptLevel.equals(low_level)) {
                rs.put("name", relyRs.getDeptName());
            } else if (SaveModel.OrgLevel.equals(low_level)) {
                rs.put("name", relyRs.getHospitalName());
            }
            rs.put("noReceiveCount", noRelyNm);
            rs.put("endCount", endNm);
            rs.put("total", totalNm);
            rs.put("code", key);
            if (totalNm != null && totalNm != 0) {
                if (endNm != null && endNm != 0) {
                    double rr = (double) endNm / totalNm * 100;
                    DecimalFormat df = new DecimalFormat("0.00");
                    rs.put("endRate", df.format(rr) + "%");
                    rs.put("endDoubleRate", rr);
                } else {
                    rs.put("endRate", "0.00%");
                    rs.put("endDoubleRate", 0.0);
                }
                if (noRelyNm != null && noRelyNm != 0) {
                    double rr = (double) noRelyNm / totalNm * 100;
                    DecimalFormat df = new DecimalFormat("0.00");
                    rs.put("noRelyRate", df.format(rr) + "%");
                    rs.put("noRelyDoubleRate", rr);
                } else {
                    rs.put("noRelyRate", "0.00%");
                    rs.put("noRelyDoubleRate", 0.0);
                }

            } else {
                rs.put("endRate", "0.00%");
                rs.put("endDoubleRate", 0.0);
                rs.put("noRelyRate", "0.00%");
                rs.put("noRelyDoubleRate", 0.0);
            }
            resultMaps.add(rs);
        }
        //根据为回复数排序
        Collections.sort(resultMaps, new Comparator<Map<String, Object>>() {

            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                return (Integer) o1.get("total") < (Integer) o2.get("total") ? 1 : ((Integer) o1.get("total") == (Integer) o2.get("total") ? 0 : -1);
            }
        });
        return resultMaps;
    }

    public List<Map<String, Object>> getCoutList(Integer level, String lowLevel, List<SaveModel> endConsult, List<SaveModel> total, List<SaveModel> noRely) {
        Map<String, Object> relyMap = new HashMap<>();
        Map<String, Object> totalMap = new HashMap<>();
        Map<String, Object> noRelyMap = new HashMap<>();
        org.json.JSONObject result = new org.json.JSONObject();
        String low_level = StringUtils.isEmpty(lowLevel) ? String.valueOf(level + 1) : lowLevel;
        //转换结束数
        for (SaveModel saveModel : endConsult) {
            if (SaveModel.doctorLevel.equals(low_level)) {
                relyMap.put(saveModel.getDoctor(), saveModel);
            } else if (SaveModel.deptLevel.equals(low_level)) {
                relyMap.put(saveModel.getDept(), saveModel);
            }else if (SaveModel.OrgLevel.equals(low_level)) {
                relyMap.put(saveModel.getHospital(), saveModel);
            }
        }
        ;

        //转换总咨询数
        for (SaveModel saveModel : total) {
            if (SaveModel.doctorLevel.equals(low_level)) {
                totalMap.put(saveModel.getDoctor(), saveModel);
            } else if (SaveModel.deptLevel.equals(low_level)) {
                totalMap.put(saveModel.getDept(), saveModel);
            }else if (SaveModel.OrgLevel.equals(low_level)) {
                totalMap.put(saveModel.getHospital(), saveModel);
            }
        }
        ;
        //转换已结束
        for (SaveModel saveModel : noRely) {
            if (SaveModel.doctorLevel.equals(low_level)) {
                noRelyMap.put(saveModel.getDoctor(), saveModel);
            } else if (SaveModel.deptLevel.equals(low_level)) {
                noRelyMap.put(saveModel.getDept(), saveModel);
            }else if (SaveModel.OrgLevel.equals(low_level)) {
                noRelyMap.put(saveModel.getHospital(), saveModel);
            }
        }
        ;
        List<Map<String, Object>> resultMaps = new ArrayList<>();
        for (String key : totalMap.keySet()) {
            Map<String, Object> rs = new HashMap<>();
            SaveModel relyRs = (SaveModel) relyMap.get(key);
            SaveModel totalRs = (SaveModel) totalMap.get(key);
            SaveModel onRelyRs = (SaveModel) noRelyMap.get(key);
            if (relyRs == null || totalRs == null || onRelyRs == null) {
                continue;
            }
            //合并结果集
            Integer totalNm = totalRs.getResult2().intValue();
            Integer endNm = relyRs.getResult2().intValue();
            Integer noRelyNm = onRelyRs.getResult2().intValue();
//            rs.put("name", relyRs.get(area+"Name"));
            if (SaveModel.doctorLevel.equals(low_level)) {
                rs.put("name", relyRs.getDoctorName());
            } else if (SaveModel.deptLevel.equals(low_level)) {
                rs.put("name", relyRs.getDeptName());
            } else if (SaveModel.OrgLevel.equals(low_level)) {
                rs.put("name", relyRs.getHospitalName());
            }
            rs.put("noRelyCount", noRelyNm);
            rs.put("endCount", endNm);
            rs.put("total", totalNm);
            rs.put("code", key);
            if (totalNm != null && totalNm != 0) {
                if (endNm != null && endNm != 0) {
                    double rr = (double) endNm / totalNm * 100;
                    DecimalFormat df = new DecimalFormat("0.00");
                    rs.put("endRate", df.format(rr) + "%");
                    rs.put("endDoubleRate", rr);
                } else {
                    rs.put("endRate", "0.00%");
                    rs.put("endDoubleRate", 0.0);
                }
                if (noRelyNm != null && noRelyNm != 0) {
                    double rr = (double) noRelyNm / totalNm * 100;
                    DecimalFormat df = new DecimalFormat("0.00");
                    rs.put("noRelyRate", df.format(rr) + "%");
                    rs.put("noRelyDoubleRate", rr);
                } else {
                    rs.put("noRelyRate", "0.00%");
                    rs.put("noRelyDoubleRate", 0.0);
                }

            } else {
                rs.put("endRate", "0.00%");
                rs.put("endDoubleRate", 0.0);
                rs.put("noRelyRate", "0.00%");
                rs.put("noRelyDoubleRate", 0.0);
            }
            resultMaps.add(rs);
        }
        //根据为回复数排序
        Collections.sort(resultMaps, new Comparator<Map<String, Object>>() {

            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                return (Integer) o1.get("total") < (Integer) o2.get("total") ? 1 : ((Integer) o1.get("total") == (Integer) o2.get("total") ? 0 : -1);
            }
        });
        return resultMaps;
    }


    /**
     * 服务评分平均分
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @return
     * @throws Exception
     */
    public JSONObject getScoreHead(String startDate, String endDate, String area, int level, String index) throws Exception {
        //总评分
        SaveModel saveModel = null;

        saveModel = elasticsearchUtil.findOneDateQuotaLevel0(endDate, endDate, area, level, index, SaveModel.timeLevel_DDL);
        JSONObject object = new JSONObject();
        Double scoreTotal = saveModel.getResult1();//总评分
        Double people = saveModel.getResult2();//评价总人数
        object.put("scoreTotal",scoreTotal);//总评分
        object.put("people",people);//总人数
        object.put("scoreRate",getDoubleRange(scoreTotal,people,0));//平均评分
        return object;
    }


    /**
     * 服务评分曲线
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param interval
     * @param level2_type
     * @return
     * @throws Exception
     */
    public JSONObject getScoreLine(String startDate, String endDate, String area, int level, String index,int interval, String level2_type) throws Exception {
        //服务评分
        JSONObject object = new JSONObject();
        JSONArray array = new JSONArray();
        if (interval==1){
            array = dateTotalStatistics2(startDate,endDate,area,level,index,null,SaveModel.timeLevel_ZL,null);
        }else if (interval==2){
            array = weekTotalStatistics7(startDate,endDate,area,level,index,null,SaveModel.timeLevel_ZL);
        }else if (interval==3){
            array = monthTotalStatistics2(startDate,endDate,area,level,index,null,SaveModel.timeLevel_ZL,null);
        }
        for (int i=0;i<array.size();i++){
            JSONObject jsonObject = array.getJSONObject(i);
            Long amount = jsonObject.getLong("amount");
            Double num = jsonObject.getDouble("num");
            jsonObject.put("scoreRate",getDoubleRange(num,amount.doubleValue(),0));
        }
        object.put("data",array);
        return object;
    }


    public JSONObject getScoreList(String startTime,String endTime,int level, String area, String lowLevel) throws Exception {
        JSONObject result1 = new JSONObject();

        //评价总分
        List<SaveModel> total = elasticsearchUtil.findListDateQuotaLevel0(endTime, endTime, area, level, "9", SaveModel.timeLevel_DDL, lowLevel);
        Map<String, Object> totalMap = new HashMap<>();
        org.json.JSONObject result = new org.json.JSONObject();
        String low_level = StringUtils.isEmpty(lowLevel) ? String.valueOf(level + 1) : lowLevel;


        //转换总咨询数
        for (SaveModel saveModel : total) {
            if (SaveModel.doctorLevel.equals(low_level)) {
                totalMap.put(saveModel.getDoctor(), saveModel);
            } else if (SaveModel.deptLevel.equals(low_level)) {
                totalMap.put(saveModel.getDept(), saveModel);
            }else if (SaveModel.OrgLevel.equals(low_level)) {
                totalMap.put(saveModel.getHospital(), saveModel);
            }
        }
        ;
        List<Map<String, Object>> resultMaps = new ArrayList<>();
        for (String key : totalMap.keySet()) {
            Map<String, Object> rs = new HashMap<>();
            SaveModel totalRs = (SaveModel) totalMap.get(key);
            if (totalRs == null) {
                continue;
            }
            //合并结果集
            Double totalNm = totalRs.getResult2();//总人数
            Double scoreNm = totalRs.getResult1();//总分数
            if (SaveModel.doctorLevel.equals(low_level)) {
                rs.put("name", totalRs.getDoctorName());
            } else if (SaveModel.deptLevel.equals(low_level)) {
                rs.put("name", totalRs.getDeptName());
            } else if (SaveModel.OrgLevel.equals(low_level)) {
                rs.put("name", totalRs.getHospitalName());
            }
            rs.put("total", totalNm);
            rs.put("scoreRate",getDoubleRange(scoreNm,totalNm,0));
            rs.put("code", key);
            resultMaps.add(rs);
        }
        //根据为评价比例排序
        Collections.sort(resultMaps, new Comparator<Map<String, Object>>() {

            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                return (Double) o1.get("scoreRate") < (Double) o2.get("scoreRate") ? 1 : ((Double) o1.get("scoreRate") == (Double) o2.get("scoreRate") ? 0 : -1);
            }
        });
        result1.put("resultList", resultMaps);
        return result1;
    }


    /**
     * 医生排班
     * @param startTime
     * @param endTime
     * @param index
     * @param level
     * @param area
     * @return
     * @throws Exception
     */
    public JSONObject getScheduleTotal(String startTime,String endTime,String index,Integer level, String area) throws Exception {
        JSONObject jsonObject = new JSONObject();
        String condition = "";
        if (SaveModel.cityLevel.equalsIgnoreCase(level.toString())){
            condition +="";
        }else if (SaveModel.OrgLevel.equalsIgnoreCase(level.toString())){
            condition +=" and dh.org_code ='"+area+"' ";
        }else if (SaveModel.townLevel.equalsIgnoreCase(level.toString())){
            condition +=" ";
        }else if (SaveModel.deptLevel.equalsIgnoreCase(level.toString())){
            condition +=" and dh.dept_code = '"+area+"'";
        }else if (SaveModel.doctorLevel.equalsIgnoreCase(level.toString())){
            condition +=" and dh.doctor_code = '"+area+"'";
        }
        String sql = "SELECT COUNT(*) as \"total\" FROM `base_doctor_role` dr LEFT JOIN base_doctor_hospital dh ON dr.doctor_code = dh.doctor_code where dr.role_code='specialist' "+condition;
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        Long doctorCount = 0L;
        if (mapList!=null&&mapList.size()!=0){
            doctorCount = Long.parseLong(mapList.get(0).get("total").toString());
        }
        List<SaveModel> saveModels = elasticsearchUtil.findLineChartDateQuotaLevel0(startTime, endTime, area, level, index, SaveModel.timeLevel_ZL, SaveModel.interval_day);
        Set<String> set = new HashSet<>();
        Long days = 0L;
        for (SaveModel saveModel1:saveModels){
            if(saveModel1.getResult1()!=0){
                days+=1;
            }
        }
        List<SaveModel> saveModels1 = elasticsearchUtil.findDateQuotaLevel0(startTime, endTime, area, level, index, SaveModel.timeLevel_ZL, SaveModel.interval_day,SaveModel.doctorLevel);
        for (SaveModel saveModel1:saveModels1){
            if(saveModel1.getResult1()!=0){
                set.add(saveModel1.getDoctor());
            }
        }
        Integer total = set.size();
        jsonObject.put("rate",getTwoRange(total,doctorCount.intValue(),0));//排班比例
        jsonObject.put("doctorCount",doctorCount);
        jsonObject.put("days",days);
        jsonObject.put("total",total);

        return  jsonObject;
    }


    /**
     * 通用查询曲线
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param interval 1按日统计，2按周统计，3按月统计
     * @return
     * @throws Exception
     */
    public JSONObject getScheduleLine(String startDate, String endDate, String area, int level, String index,int interval) throws Exception {
        //问诊量
        JSONObject object = new JSONObject();
        if (interval==1){
            JSONArray array = dateTotalStatistics2(startDate,endDate,area,level,index,null,SaveModel.timeLevel_ZL,null);
            object.put("data",array);
        }else if (interval==2){
            JSONArray array = weekTotalStatistics7(startDate,endDate,area,level,index,null,SaveModel.timeLevel_ZL);
            object.put("data",array);
        }else if (interval==3){
            JSONArray array = monthTotalStatistics2AndMonth(startDate,endDate,area,level,index,null,SaveModel.timeLevel_ZL);
            object.put("data",array);
        }
        return object;
    }


    public JSONObject getScheduleList(String startTime,String endTime,String index,int level, String area, String lowLevel) throws Exception {
        JSONObject result1 = new JSONObject();
        List<SaveModel> total = elasticsearchUtil.findDateQuotaLevel0(startTime, endTime, area, level, index, SaveModel.timeLevel_ZL,null, lowLevel);
        List<SaveModel> total1 = elasticsearchUtil.findDateQuotaLevel0AndPaibanList(startTime, endTime, area, level, index, SaveModel.timeLevel_ZL,null, lowLevel);
        Map<String, Object> totalMap = new HashMap<>();
        String low_level = StringUtils.isEmpty(lowLevel) ? String.valueOf(level + 1) : lowLevel;
        List<String> codes = new ArrayList<>();
        for (SaveModel saveModel:total){
            for (SaveModel saveModel1:total1){
                if (SaveModel.doctorLevel.equals(low_level)) {
                    if (saveModel.getDoctor().equalsIgnoreCase(saveModel1.getDoctor())){
                        saveModel.setResult1(saveModel1.getResult1());
                        saveModel.setResult2(saveModel1.getResult2());
                        codes.add(saveModel1.getDoctor());
                    }
                } else if (SaveModel.deptLevel.equals(low_level)) {
                    if (saveModel.getDept().equalsIgnoreCase(saveModel1.getDept())){
                        saveModel.setResult1(saveModel1.getResult1());
                        saveModel.setResult2(saveModel1.getResult2());
                        codes.add(saveModel1.getDept());
                    }
                }else if (SaveModel.OrgLevel.equals(low_level)) {
                    if (saveModel.getHospital().equalsIgnoreCase(saveModel1.getHospital())){
                        saveModel.setResult1(saveModel1.getResult1());
                        saveModel.setResult2(saveModel1.getResult2());
                        codes.add(saveModel1.getHospital());
                    }
                }
            }
        }
        for (SaveModel saveModel:total){
            if (SaveModel.doctorLevel.equals(low_level)) {
                if (!codes.contains(saveModel.getDoctor())){
                    saveModel.setResult1(0.0);
                    saveModel.setResult2(0.0);

                }
            } else if (SaveModel.deptLevel.equals(low_level)) {
                if (!codes.contains(saveModel.getDept())){
                    saveModel.setResult1(0.0);
                    saveModel.setResult2(0.0);

                }
            }else if (SaveModel.OrgLevel.equals(low_level)) {
                if (!codes.contains(saveModel.getHospital())){
                    saveModel.setResult1(0.0);
                    saveModel.setResult2(0.0);

                }
            }
        }
        for (SaveModel saveModel : total) {
            if (SaveModel.doctorLevel.equals(low_level)) {
                totalMap.put(saveModel.getDoctor(), saveModel);
            } else if (SaveModel.deptLevel.equals(low_level)) {
                totalMap.put(saveModel.getDept(), saveModel);
            }else if (SaveModel.OrgLevel.equals(low_level)) {
                totalMap.put(saveModel.getHospital(), saveModel);
            }
        }
        ;
        List<Map<String, Object>> resultMaps = new ArrayList<>();
        for (String key : totalMap.keySet()) {
            Map<String, Object> rs = new HashMap<>();
            SaveModel totalRs = (SaveModel) totalMap.get(key);
            if (totalRs == null) {
                continue;
            }
            //合并结果集
            Double totalNm = totalRs.getResult2();//总人数
            Double scoreNm = totalRs.getResult1();//总分数
            if (SaveModel.doctorLevel.equals(low_level)) {
                rs.put("name", totalRs.getDoctorName());
                BaseDoctorDO doctorDO = doctorDao.findById(totalRs.getDoctor());
                rs.put("doctorJob",doctorDO.getJobTitleName());
            } else if (SaveModel.deptLevel.equals(low_level)) {
                rs.put("name", totalRs.getDeptName());
            } else if (SaveModel.OrgLevel.equals(low_level)) {
                rs.put("name", totalRs.getHospitalName());
            }
            rs.put("total", totalNm);
            rs.put("scoreRate",getDoubleRange(scoreNm,totalNm,0));
            rs.put("code", key);
            resultMaps.add(rs);
        }
        //根据为回复数排序
       /* Collections.sort(resultMaps, new Comparator<Map<String, Object>>() {

            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                return (Double) o1.get("total") < (Double) o2.get("total") ? 1 : ((Double) o1.get("total") == (Double) o2.get("total") ? 0 : -1);
            }
        });*/
        Collections.sort(resultMaps, new Comparator<Map<String,Object>>() {
            @Override
            public int compare(Map<String,Object> o1, Map<String,Object> o2) {
                Double total1 = (Double) o1.get("total");
                Double total2 = (Double) o2.get("total");
                if (total1 - total2 > 0) {
                    return -1;
                } else if (total1 - total2 < 0) {
                    return 1;
                }
                return 0;
            }
        });
        result1.put("resultList", resultMaps);
        return result1;
    }




    /**
     * 咨询统计总量
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @param area 区域
     * @param level
     * @param index 专家咨询6，图文复诊11，专家协同13，视频复诊15
     * @return
     * @throws Exception
     */
    public JSONObject getConsultHead(String startDate, String endDate, String area, int level, String index,String lowCode) throws Exception {
        JSONObject object = new JSONObject();
        if (index.equalsIgnoreCase("6")){
            //总量
            SaveModel saveModel = null;
            //已回复
            SaveModel saveModel1 = null;
            //已结束
            SaveModel saveModel2 = null;
            //未回复
            SaveModel saveModel3 = null;
            //居民取消
            SaveModel saveModel4 = null;
            //进行中
            SaveModel saveModel5 = null;
            String index1= (Integer.parseInt(index)+1)+"";
            saveModel = elasticsearchUtil.findOneDateQuotaLevel0(startDate, endDate, area, level, index1, SaveModel.timeLevel_ZL);
            saveModel1 = elasticsearchUtil.findOneDateQuotaLevel1(startDate,endDate, area, level, index, SaveModel.timeLevel_ZL,"1");
            saveModel3 = elasticsearchUtil.findOneDateQuotaLevel1(startDate,endDate, area, level, index, SaveModel.timeLevel_ZL,"0");
            saveModel4 = elasticsearchUtil.findOneDateQuotaLevel1(startDate,endDate, area, level, index1, SaveModel.timeLevel_ZL,"-1");
            saveModel5 = elasticsearchUtil.findOneDateQuotaLevel1(startDate,endDate, area, level, index1, SaveModel.timeLevel_ZL,"0");
            saveModel2 = elasticsearchUtil.findOneDateQuotaLevel1(startDate,endDate, area, level, index1, SaveModel.timeLevel_ZL,"1");
            object.put("consultTotal",saveModel.getResult1());
            object.put("haveReplyTotal",saveModel1.getResult1());
            object.put("endTotal",saveModel2.getResult1());
            object.put("notReplyTotal",saveModel3.getResult1());
            object.put("cancelTotal",saveModel4.getResult1());
            object.put("comingTotal",saveModel5.getResult1());
            object.put("notReplyRate",getRange(saveModel3.getResult1().intValue(),saveModel.getResult1().intValue(),2));//未回复率
        }else {
            //总量
            SaveModel saveModel = null;
            //已接诊
            SaveModel saveModel1 = null;
            //未接诊
            SaveModel saveModel2 = null;
            //已结束
            SaveModel saveModel3 = null;
            //居民取消
            SaveModel saveModel4 = null;
         /*   //进行中
            SaveModel saveModel5 = null;*/
            String index1= (Integer.parseInt(index)+1)+"";
            //居民取消
            List<SaveModel> concleTotal = elasticsearchUtil.findListDateQuotaLevel2(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL, null,lowCode,"-1");
            //咨询总数
            List<SaveModel> total = elasticsearchUtil.findListDateQuotaLevel1(startDate, endDate, area, level, index1, SaveModel.timeLevel_ZL, null,lowCode);
            //已结束
            List<SaveModel> endTotal = elasticsearchUtil.findListDateQuotaLevel2(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL, null,lowCode,"3");
            //已接诊
            List<SaveModel> haveReceiveTotal = elasticsearchUtil.findListDateQuotaLevel2(startDate, endDate, area, level, index1, SaveModel.timeLevel_ZL, null,lowCode,"1");
            //未接诊
            List<SaveModel> noReceiveTotal = elasticsearchUtil.findListDateQuotaLevel2(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL, null,lowCode,"0");
            saveModel = total.get(0);//elasticsearchUtil.bfindOneDateQuotaLevel12(startDate, endDate, area, level, index1, SaveModel.timeLevel_ZL,lowCode,"");
            saveModel1 = haveReceiveTotal.get(0);//elasticsearchUtil.bfindOneDateQuotaLevel12(startDate,endDate, area, level, index1, SaveModel.timeLevel_ZL,lowCode,"1");
            saveModel3 = endTotal.get(0);//elasticsearchUtil.bfindOneDateQuotaLevel12(startDate,endDate, area, level, index, SaveModel.timeLevel_ZL,lowCode,"3");
            saveModel4 = concleTotal.get(0);//elasticsearchUtil.bfindOneDateQuotaLevel12(startDate,endDate, area, level, index, SaveModel.timeLevel_ZL,lowCode,"-1");
/*
            saveModel5 = elasticsearchUtil.findOneDateQuotaLevel1(startDate, area, level, index1, SaveModel.timeLevel_ZL,"0");
*/
            saveModel2 = noReceiveTotal.get(0);elasticsearchUtil.bfindOneDateQuotaLevel12(startDate,endDate, area, level, index, SaveModel.timeLevel_ZL,lowCode,"0");
            object.put("consultTotal",saveModel.getResult1());//咨询总量
            object.put("haveReceiveTotal",saveModel1.getResult1());//已接诊
            object.put("noReceiveTotal",saveModel2.getResult1());//未接诊
            object.put("endTotal",saveModel3.getResult1());//已结束
            object.put("cancelTotal",saveModel4.getResult1());//居民取消
/*            object.put("comingTotal",saveModel5.getResult1());*/
            object.put("notReceiveRate",getRange(saveModel2.getResult1().intValue(),saveModel.getResult1().intValue(),2));//未接诊比例
        }

        return object;
    }


    /**
     * 咨询统计曲线
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index 专家咨询6，图文复诊11，专家协同13，视频复诊15
     * @param interval
     * @param level2_type
     * @return
     * @throws Exception
     */
    public JSONObject getConsultLine(String startDate, String endDate, String area, int level, String index,int interval, String level2_type) throws Exception {
        String index1= (Integer.parseInt(index)+1)+"";
        //问诊量
        JSONObject object = new JSONObject();
        if (interval==1){
            JSONArray array = dateTotalStatistics2(startDate,endDate,area,level,index1,null,SaveModel.timeLevel_ZL,null);
            object.put("data",array);
        }else if (interval==2){
            JSONArray array = weekTotalStatistics7(startDate,endDate,area,level,index1,null,SaveModel.timeLevel_ZL);
            object.put("data",array);
        }else if (interval==3){
            JSONArray array = monthTotalStatistics2(startDate,endDate,area,level,index1,null,SaveModel.timeLevel_ZL,null);
            object.put("data",array);
        }
        return object;
    }


    /**
     * 咨询统计表格
     * @param startTime
     * @param endTime
     * @param level
     * @param area
     * @param lowLevel
     * @param  index 专家咨询6，图文复诊11，专家协同13，视频复诊15
     * @return
     * @throws Exception
     */
    public JSONObject getConsultingList(String startTime,String endTime,int level, String area, String lowLevel,String index) throws Exception {
        JSONObject result = new JSONObject();
        if(index.equalsIgnoreCase("6")){
            String index1= (Integer.parseInt(index)+1)+"";
            //已结束
            List<SaveModel> endTotal = elasticsearchUtil.findListDateQuotaLevel1(startTime, endTime, area, level, index1, SaveModel.timeLevel_ZL, lowLevel,"1");
            //咨询总数
            List<SaveModel> total = elasticsearchUtil.findListDateQuotaLevel0(startTime, endTime, area, level, index1, SaveModel.timeLevel_ZL, lowLevel);
            //未回复数
            List<SaveModel> noRelyTotal = elasticsearchUtil.findListDateQuotaLevel1(startTime, endTime, area, level, index, SaveModel.timeLevel_ZL, lowLevel,"0");
            result.put("resultList", getCoutList(level, lowLevel, endTotal, total, noRelyTotal));
        }else {
            String index1= (Integer.parseInt(index)+1)+"";
            //未接诊
            List<SaveModel> noReceiveTotal = elasticsearchUtil.findListDateQuotaLevel1(startTime, endTime, area, level, index1, SaveModel.timeLevel_ZL, lowLevel,"0");
            //咨询总数
            List<SaveModel> total = elasticsearchUtil.findListDateQuotaLevel0(startTime, endTime, area, level, index1, SaveModel.timeLevel_ZL, lowLevel);
            //已结束
            List<SaveModel> endTotal = elasticsearchUtil.findListDateQuotaLevel1(startTime, endTime, area, level, index, SaveModel.timeLevel_ZL, lowLevel,"1,2,3");
            result.put("resultList", getCoutList1(level, lowLevel, endTotal, total, noReceiveTotal));
        }

        return result;
    }


    /**
     * app端首页门诊量统计
     * @param startDate
     * @param endDate
     * @param area
     * @param level 专家咨询6，图文复诊11，专家协同13，视频复诊15
     * @param index
     * @return
     * @throws Exception
     */
    public JSONObject getConsultTotalApp(String startDate, String endDate, String area, int level, String index) throws Exception {
        JSONObject object = new JSONObject();
        String str[] = new String[]{};
        if (StringUtils.isNoneBlank(index)){
            str =index.split(",");
        }
        for (int i=0;i<str.length;i++){
            String index1 = (Integer.parseInt(str[i])+1)+"";
            SaveModel saveModel = elasticsearchUtil.findOneDateQuotaLevel0(startDate, endDate, area, level,index1 , SaveModel.timeLevel_ZL);
            object.put("index_"+str[i],saveModel.getResult1());
        }
        return object;
    }


    /**
     * app端门诊量统计维度-圆形比例
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @return
     * @throws Exception
     */
    public JSONObject getConsultCircularApp(String startDate, String endDate, String area, int level) throws Exception {

        JSONObject object = new JSONObject();
        //协同门诊
        SaveModel saveModel1 = null;
        saveModel1 = elasticsearchUtil.findOneDateQuotaLevel1(startDate, endDate, area, level, "14", SaveModel.timeLevel_ZL,"12");
        //图文复诊
        SaveModel saveModel2 = null;
        saveModel2 = elasticsearchUtil.findOneDateQuotaLevel1(startDate, endDate, area, level, "12", SaveModel.timeLevel_ZL,"9");
        //视频复诊
        SaveModel saveModel3 = null;
        saveModel3 = elasticsearchUtil.findOneDateQuotaLevel1(startDate, endDate, area, level, "16", SaveModel.timeLevel_ZL,"16");
        Double specialistCount =0.0;
        //专科咨询
        SaveModel saveModel4 = null;
        saveModel4 = elasticsearchUtil.findOneDateQuotaLevel1(startDate, endDate, area, level, "12", SaveModel.timeLevel_ZL,"1");
        specialistCount = saveModel4.getResult1();//专家咨询数量
        Double specialistSPCount =0.0;
        //专科咨询
        SaveModel saveModel5 = null;
        saveModel5 = elasticsearchUtil.findOneDateQuotaLevel1(startDate, endDate, area, level, "16", SaveModel.timeLevel_ZL,"17");
        specialistSPCount = saveModel5.getResult1();//专家咨询数量

        Double synergyCount = saveModel1.getResult1();//协同门诊数量
        Double topicCount = saveModel2.getResult1();//图文复诊数量
        Double videoCount = saveModel3.getResult1();//视频复诊数量
        Double total = specialistCount+synergyCount+topicCount+videoCount+specialistSPCount;//总量
        object.put("specialistCount",specialistCount);//专家咨询数
        object.put("specialistRate",getRange(specialistCount.intValue(),total.intValue(),0));
        object.put("specialistSPCount",specialistSPCount);//专家咨询sp数
        object.put("specialistSPRate",getRange(specialistSPCount.intValue(),total.intValue(),0));
        object.put("synergyCount",synergyCount);//专家咨询数
        object.put("synergyRate",getRange(synergyCount.intValue(),total.intValue(),0));
        object.put("topicCount",topicCount);//图文复诊数量
        object.put("topicRate",getRange(topicCount.intValue(),total.intValue(),0));
        object.put("videoCount",videoCount);//视频复诊数量
        object.put("videoRate",getRange(videoCount.intValue(),total.intValue(),0));
        object.put("total",total);
        return object;
    }


    /**
     * app端门诊量统计-按照日周月
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param interval
     * @param level2_type
     * @return
     * @throws Exception
     */
    public JSONObject getConsultLineApp(String startDate, String endDate, String area, int level, String index,int interval, String level2_type) throws Exception {
        //问诊量
        JSONObject object = new JSONObject();
        if (interval==1){
            JSONArray array = dateTotalStatistics2(startDate,endDate,area,level,index,null,SaveModel.timeLevel_ZL,null);
            object.put("data",array);
        }else if (interval==2){
            JSONArray array = weekTotalStatistics7(startDate,endDate,area,level,index,null,SaveModel.timeLevel_ZL);
            object.put("data",array);
        }else if (interval==3){
            JSONArray array = monthTotalStatistics2(startDate,endDate,area,level,index,null,SaveModel.timeLevel_ZL,null);
            object.put("data",array);
        }
        return object;
    }


    /**
     * 门诊量统计-app端
     * @param startTime
     * @param endTime
     * @param level
     * @param area
     * @param lowLevel
     * @param index
     * @return
     * @throws Exception
     */
    public JSONObject getConsultListApp(String startTime,String endTime,int level, String area, String lowLevel,String index) throws Exception {
        JSONObject result1 = new JSONObject();

        //门诊量总数
        List<SaveModel> total = elasticsearchUtil.findListDateQuotaLevel0(startTime, endTime, area, level, index, SaveModel.timeLevel_ZL, lowLevel);
        Map<String, Object> totalMap = new HashMap<>();
        org.json.JSONObject result = new org.json.JSONObject();
        String low_level = StringUtils.isEmpty(lowLevel) ? String.valueOf(level + 1) : lowLevel;


        //转换总咨询数
        for (SaveModel saveModel : total) {
            if (SaveModel.doctorLevel.equals(low_level)) {
                totalMap.put(saveModel.getDoctor(), saveModel);
            } else if (SaveModel.deptLevel.equals(low_level)) {
                totalMap.put(saveModel.getDept(), saveModel);
            }else if (SaveModel.OrgLevel.equals(low_level)) {
                totalMap.put(saveModel.getHospital(), saveModel);
            }
        }
        ;
        List<Map<String, Object>> resultMaps = new ArrayList<>();
        for (String key : totalMap.keySet()) {
            Map<String, Object> rs = new HashMap<>();
            SaveModel totalRs = (SaveModel) totalMap.get(key);
            if (totalRs == null) {
                continue;
            }
            //合并结果集
            Double totalNm = totalRs.getResult2();//总人数
            Double consultNm = totalRs.getResult1();//总分数
            if (SaveModel.doctorLevel.equals(low_level)) {
                rs.put("name", totalRs.getDoctorName());
            } else if (SaveModel.deptLevel.equals(low_level)) {
                rs.put("name", totalRs.getDeptName());
            } else if (SaveModel.OrgLevel.equals(low_level)) {
                rs.put("name", totalRs.getHospitalName());
            }
            rs.put("total", totalNm);
            rs.put("consultRate",getDoubleRange(consultNm,totalNm,0));
            rs.put("code", key);
            resultMaps.add(rs);
        }
        //根据为评价比例排序
        Collections.sort(resultMaps, new Comparator<Map<String, Object>>() {

            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                return (Double) o1.get("total") < (Double) o2.get("total") ? 1 : ((Double) o1.get("total") == (Double) o2.get("total") ? 0 : -1);
            }
        });
        result1.put("resultList", resultMaps);
        return result1;
    }



    /**
     * 咨询统计曲线-PC
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index 专家咨询6，图文复诊11，专家协同13，视频复诊15
     * @param interval
     * @param level2_type
     * @return
     * @throws Exception
     */
    public JSONObject getConsultLinePC(String startDate, String endDate, String area, int level, String index,int interval, String level2_type,String lowCode) throws Exception {
        String index1= (Integer.parseInt(index)+1)+"";
        //问诊量
        JSONObject object = new JSONObject();
        if (interval==1){
            if (index.equalsIgnoreCase("6")){
                JSONArray array = dateTotalStatistics2(startDate,endDate,area,level,index1,null,SaveModel.timeLevel_ZL,null);
                object.put("totalData",array);//新增量
                JSONArray array1 = dateTotalStatistics2(startDate,endDate,area,level,index,"0",SaveModel.timeLevel_ZL,null);//未回复
                object.put("noReplyData",array1);//未回复
                JSONArray array2 = dateTotalStatistics2(startDate,endDate,area,level,index,"1",SaveModel.timeLevel_ZL,null);//已回复
                object.put("replyData",array2);//已回复
                JSONArray array3 = dateTotalStatistics2(startDate,endDate,area,level,index1,"0",SaveModel.timeLevel_ZL,null);//进行中
                object.put("commingData",array3);//进行中
                JSONArray array4 = dateTotalStatistics2(startDate,endDate,area,level,index1,"1",SaveModel.timeLevel_ZL,null);//已完成
                object.put("endData",array4);//已完成
            }else {
                JSONArray array = dateTotalStatistics2(startDate,endDate,area,level,index1,lowCode,SaveModel.timeLevel_ZL,null);
                object.put("totalData",array);//新增量
                JSONArray array1 = dateTotalStatistics2(startDate,endDate,area,level,index1,lowCode,SaveModel.timeLevel_ZL,"0");//未接诊
                object.put("noReceiveData",array1);//未接诊
                JSONArray array2 = dateTotalStatistics2(startDate,endDate,area,level,index1,lowCode,SaveModel.timeLevel_ZL,"1");//已接诊
                object.put("haveReceiveData",array2);//已接诊
                JSONArray array3 = dateTotalStatistics2(startDate,endDate,area,level,index,lowCode,SaveModel.timeLevel_ZL,"-1");//患者取消
                object.put("concleData",array3);//患者取消
                JSONArray array4 = dateTotalStatistics2(startDate,endDate,area,level,index,lowCode,SaveModel.timeLevel_ZL,"3");//已结束
                object.put("endData",array4);//已结束
            }

        }else if (interval==2){
            if (index.equalsIgnoreCase("6")){
                JSONArray array = weekTotalStatistics8(startDate,endDate,area,level,index1,null,SaveModel.timeLevel_ZL,null);
                object.put("totalData",array);//新增量
                JSONArray array1 = weekTotalStatistics7(startDate,endDate,area,level,index,"0",SaveModel.timeLevel_ZL);//未回复
                object.put("noReplyData",array1);;//未回复
                JSONArray array2 = weekTotalStatistics7(startDate,endDate,area,level,index,"1",SaveModel.timeLevel_ZL);//已回复
                object.put("replyData",array2);//已回复
                JSONArray array3 = weekTotalStatistics7(startDate,endDate,area,level,index1,"0",SaveModel.timeLevel_ZL);//进行中
                object.put("commingData",array3);//进行中
                JSONArray array4 = weekTotalStatistics7(startDate,endDate,area,level,index1,"1",SaveModel.timeLevel_ZL);//已完成
                object.put("endData",array3);//进行中
            }else {
                JSONArray array = weekTotalStatistics8(startDate,endDate,area,level,index1,lowCode,SaveModel.timeLevel_ZL,null);
                object.put("totalData",array);//新增量
                JSONArray array1 = weekTotalStatistics8(startDate,endDate,area,level,index1,lowCode,SaveModel.timeLevel_ZL,"0");//未接诊
                object.put("noReceiveData",array1);;//未接诊
                JSONArray array2 = weekTotalStatistics8(startDate,endDate,area,level,index1,lowCode,SaveModel.timeLevel_ZL,"1");//已接诊
                object.put("haveReceiveData",array2);//已接诊
                JSONArray array3 = weekTotalStatistics8(startDate,endDate,area,level,index,lowCode,SaveModel.timeLevel_ZL,"-1");//患者取消
                object.put("concleData",array3);//患者取消
                JSONArray array4 = weekTotalStatistics8(startDate,endDate,area,level,index,lowCode,SaveModel.timeLevel_ZL,"3");//已结束
                object.put("endData",array4);//已结束
            }

        }else if (interval==3){
            if (index.equalsIgnoreCase("6")){
                JSONArray array = monthTotalStatistics2(startDate,endDate,area,level,index1,null,SaveModel.timeLevel_ZL,null);
                object.put("totalData",array);
                JSONArray array1 = monthTotalStatistics2(startDate,endDate,area,level,index,"0",SaveModel.timeLevel_ZL,null);
                object.put("noReplyData",array1);
                JSONArray array2 = monthTotalStatistics2(startDate,endDate,area,level,index,"1",SaveModel.timeLevel_ZL,null);
                object.put("replyData",array2);
                JSONArray array3 = monthTotalStatistics2(startDate,endDate,area,level,index1,"0",SaveModel.timeLevel_ZL,null);
                object.put("commingData",array3);
                JSONArray array4 = monthTotalStatistics2(startDate,endDate,area,level,index1,"1",SaveModel.timeLevel_ZL,null);
                object.put("endData",array4);
            }else {
                JSONArray array = monthTotalStatistics2(startDate,endDate,area,level,index1,lowCode,SaveModel.timeLevel_ZL,null);
                object.put("totalData",array);
                JSONArray array1 = monthTotalStatistics2(startDate,endDate,area,level,index1,lowCode,SaveModel.timeLevel_ZL,"0");
                object.put("noReceiveData",array1);
                JSONArray array2 = monthTotalStatistics2(startDate,endDate,area,level,index1,lowCode,SaveModel.timeLevel_ZL,"1");
                object.put("haveReceiveData",array2);
                JSONArray array3 = monthTotalStatistics2(startDate,endDate,area,level,index,lowCode,SaveModel.timeLevel_ZL,"-1");
                object.put("concleData",array3);
                JSONArray array4 = monthTotalStatistics2(startDate,endDate,area,level,index,lowCode,SaveModel.timeLevel_ZL,"3");
                object.put("endData",array4);
            }

        }
        return object;
    }


    /**
     * 咨询统计表格-PC
     * @param startTime
     * @param endTime
     * @param level
     * @param area
     * @param lowLevel
     * @param  index 专家咨询6，图文复诊11，专家协同13，视频复诊15
     * @return
     * @throws Exception
     */
    public JSONObject getConsultingListPC(String startTime,String endTime,int level, String area, String lowLevel,String index,String lowCode) throws Exception {
        JSONObject result = new JSONObject();
        String index1= (Integer.parseInt(index)+1)+"";
//        timeKey= "2017-11-01 00:00:00";
        if(index.equalsIgnoreCase("6")){
            //已结束
            List<SaveModel> endTotal = elasticsearchUtil.findListDateQuotaLevel2(startTime, endTime, area, level, index1, SaveModel.timeLevel_ZL, lowLevel,lowCode,"1");
            //进行中
            List<SaveModel> comingTotal = elasticsearchUtil.findListDateQuotaLevel1(startTime, endTime, area, level, index1, SaveModel.timeLevel_ZL, lowLevel,"0");
            //咨询总数
            List<SaveModel> total = elasticsearchUtil.findListDateQuotaLevel0(startTime, endTime, area, level, index1, SaveModel.timeLevel_ZL, lowLevel);
            //未回复数
            List<SaveModel> noRelyTotal = elasticsearchUtil.findListDateQuotaLevel1(startTime, endTime, area, level, index, SaveModel.timeLevel_ZL, lowLevel,"0");
            //已回复数
            List<SaveModel> relyTotal = elasticsearchUtil.findListDateQuotaLevel1(startTime, endTime, area, level, index, SaveModel.timeLevel_ZL, lowLevel,"1");
            result.put("resultList", getCoutListPC(level, lowLevel, endTotal, total, noRelyTotal,relyTotal,comingTotal));
        }else {
            //已结束
            List<SaveModel> endTotal = elasticsearchUtil.findListDateQuotaLevel2(startTime, endTime, area, level, index, SaveModel.timeLevel_ZL, lowLevel,lowCode,"3");
            //居民取消
            List<SaveModel> concleTotal = elasticsearchUtil.findListDateQuotaLevel2(startTime, endTime, area, level, index, SaveModel.timeLevel_ZL, lowLevel,lowCode,"-1");
            //咨询总数
            List<SaveModel> total = elasticsearchUtil.findListDateQuotaLevel1(startTime, endTime, area, level, index1, SaveModel.timeLevel_ZL, lowLevel,lowCode);
            logger.info("total"+total==null?"0":String.valueOf(total.size())+";"+total.get(0).getResult1());
            //已接诊
            List<SaveModel> haveReceiveTotal = elasticsearchUtil.findListDateQuotaLevel2(startTime, endTime, area, level, index1, SaveModel.timeLevel_ZL, lowLevel,lowCode,"1");
            //未接诊
            List<SaveModel> noReceiveTotal = elasticsearchUtil.findListDateQuotaLevel2(startTime, endTime, area, level, index1, SaveModel.timeLevel_ZL, lowLevel,lowCode,"0");
            logger.info("noReceiveTotal"+noReceiveTotal==null?"0":String.valueOf(noReceiveTotal.size())+";"+noReceiveTotal.get(0).getResult1());
                result.put("resultList", getCoutListPC1(level, lowLevel, endTotal, total, haveReceiveTotal,noReceiveTotal,concleTotal));
    }


        return result;
    }

    /**
     * 在线复诊、协同复诊转换
     * @param level
     * @param lowLevel
     * @param endConsult
     * @param total
     * @return
     */
    public List<Map<String, Object>> getCoutListPC1(Integer level, String lowLevel, List<SaveModel> endConsult, List<SaveModel> total, List<SaveModel> haveReceive,List<SaveModel> noReceive,List<SaveModel> concle) {
        Map<String, Object> endMap = new HashMap<>();
        Map<String, Object> totalMap = new HashMap<>();
        Map<String, Object> noReceiveMap = new HashMap<>();
        Map<String, Object> concleMap = new HashMap<>();
        Map<String, Object> haveReceiveMap = new HashMap<>();

        org.json.JSONObject result = new org.json.JSONObject();
        String low_level = StringUtils.isEmpty(lowLevel) ? String.valueOf(level + 1) : lowLevel;
        //转换结束数
        for (SaveModel saveModel : endConsult) {
            if (SaveModel.doctorLevel.equals(low_level)) {
                endMap.put(saveModel.getDoctor(), saveModel);
            } else if (SaveModel.deptLevel.equals(low_level)) {
                endMap.put(saveModel.getDept(), saveModel);
            }else if (SaveModel.OrgLevel.equals(low_level)) {
                endMap.put(saveModel.getHospital(), saveModel);
            }
        }

        //转换已接诊
        for (SaveModel saveModel : haveReceive) {
            if (SaveModel.doctorLevel.equals(low_level)) {
                haveReceiveMap.put(saveModel.getDoctor(), saveModel);
            } else if (SaveModel.deptLevel.equals(low_level)) {
                haveReceiveMap.put(saveModel.getDept(), saveModel);
            }else if (SaveModel.OrgLevel.equals(low_level)) {
                haveReceiveMap.put(saveModel.getHospital(), saveModel);
            }
        }


        //转换总咨询数
        for (SaveModel saveModel : total) {
            if (SaveModel.doctorLevel.equals(low_level)) {
                totalMap.put(saveModel.getDoctor(), saveModel);
            } else if (SaveModel.deptLevel.equals(low_level)) {
                totalMap.put(saveModel.getDept(), saveModel);
            }else if (SaveModel.OrgLevel.equals(low_level)) {
                totalMap.put(saveModel.getHospital(), saveModel);
            }
        }

        //转换未接诊
        for (SaveModel saveModel : noReceive) {
            if (SaveModel.doctorLevel.equals(low_level)) {
                noReceiveMap.put(saveModel.getDoctor(), saveModel);
            } else if (SaveModel.deptLevel.equals(low_level)) {
                noReceiveMap.put(saveModel.getDept(), saveModel);
            }else if (SaveModel.OrgLevel.equals(low_level)) {
                noReceiveMap.put(saveModel.getHospital(), saveModel);
            }
        }

        //转换已取消
        for (SaveModel saveModel : concle) {
            if (SaveModel.doctorLevel.equals(low_level)) {
                concleMap.put(saveModel.getDoctor(), saveModel);
            } else if (SaveModel.deptLevel.equals(low_level)) {
                concleMap.put(saveModel.getDept(), saveModel);
            }else if (SaveModel.OrgLevel.equals(low_level)) {
                concleMap.put(saveModel.getHospital(), saveModel);
            }
        }


        List<Map<String, Object>> resultMaps = new ArrayList<>();
        for (String key : totalMap.keySet()) {
            Map<String, Object> rs = new HashMap<>();
            SaveModel endRs = (SaveModel) endMap.get(key);
            SaveModel totalRs = (SaveModel) totalMap.get(key);
            SaveModel concleRs = (SaveModel) concleMap.get(key);
            SaveModel noReceiveRs = (SaveModel) noReceiveMap.get(key);
            SaveModel haveReceiveRs = (SaveModel) haveReceiveMap.get(key);
            endRs = endRs==null?new SaveModel():endRs;
            totalRs = totalRs==null?new SaveModel():totalRs;
            concleRs = concleRs==null?new SaveModel():concleRs;
            noReceiveRs = noReceiveRs==null?new SaveModel():noReceiveRs;
            haveReceiveRs = haveReceiveRs==null?new SaveModel():haveReceiveRs;
            /*if (endRs == null || totalRs == null || concleRs == null || noReceiveRs==null || haveReceiveRs == null) {
                continue;
            }*/
            //合并结果集
            Integer totalNm = totalRs.getResult2().intValue();
            Integer endNm = endRs.getResult2().intValue();
            Integer concleNm = concleRs.getResult2().intValue();
            Integer noReceiveNm = noReceiveRs.getResult2().intValue();
            Integer haveReceiveNm = haveReceiveRs.getResult2().intValue();
//            rs.put("name", relyRs.get(area+"Name"));
            if (SaveModel.doctorLevel.equals(low_level)) {
                rs.put("name", totalRs.getDoctorName());
            } else if (SaveModel.deptLevel.equals(low_level)) {
                rs.put("name", totalRs.getDeptName());
            } else if (SaveModel.OrgLevel.equals(low_level)) {
                rs.put("name", totalRs.getHospitalName());
            }
            rs.put("concleCount", concleNm);
            rs.put("endCount", endNm);
            rs.put("total", totalNm);
            rs.put("noReceiveCount", noReceiveNm);
            rs.put("haveReceiveCount", haveReceiveNm);
            rs.put("endAndReciveCount",endNm+haveReceiveNm);
            rs.put("code", key);
            resultMaps.add(rs);
        }
        //根据为咨询总数排序
        Collections.sort(resultMaps, new Comparator<Map<String, Object>>() {

            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                return (Integer) o1.get("total") < (Integer) o2.get("total") ? 1 : ((Integer) o1.get("total") == (Integer) o2.get("total") ? 0 : -1);
            }
        });
        return resultMaps;
    }

    public List<Map<String, Object>> getCoutListPC(Integer level, String lowLevel, List<SaveModel> endConsult, List<SaveModel> total, List<SaveModel> noRely,List<SaveModel> reply,List<SaveModel> coming) {
        Map<String, Object> endMap = new HashMap<>();
        Map<String, Object> totalMap = new HashMap<>();
        Map<String, Object> noRelyMap = new HashMap<>();
        Map<String, Object> relyMap = new HashMap<>();
        Map<String, Object> comingMap = new HashMap<>();

        org.json.JSONObject result = new org.json.JSONObject();
        String low_level = StringUtils.isEmpty(lowLevel) ? String.valueOf(level + 1) : lowLevel;
        //转换结束数
        for (SaveModel saveModel : endConsult) {
            if (SaveModel.doctorLevel.equals(low_level)) {
                endMap.put(saveModel.getDoctor(), saveModel);
            } else if (SaveModel.deptLevel.equals(low_level)) {
                endMap.put(saveModel.getDept(), saveModel);
            }else if (SaveModel.OrgLevel.equals(low_level)) {
                endMap.put(saveModel.getHospital(), saveModel);
            }
        }

        //转换进行数
        for (SaveModel saveModel : coming) {
            if (SaveModel.doctorLevel.equals(low_level)) {
                comingMap.put(saveModel.getDoctor(), saveModel);
            } else if (SaveModel.deptLevel.equals(low_level)) {
                comingMap.put(saveModel.getDept(), saveModel);
            }else if (SaveModel.OrgLevel.equals(low_level)) {
                comingMap.put(saveModel.getHospital(), saveModel);
            }
        }


        //转换总咨询数
        for (SaveModel saveModel : total) {
            if (SaveModel.doctorLevel.equals(low_level)) {
                totalMap.put(saveModel.getDoctor(), saveModel);
            } else if (SaveModel.deptLevel.equals(low_level)) {
                totalMap.put(saveModel.getDept(), saveModel);
            }else if (SaveModel.OrgLevel.equals(low_level)) {
                totalMap.put(saveModel.getHospital(), saveModel);
            }
        }

        //转换未回复
        for (SaveModel saveModel : noRely) {
            if (SaveModel.doctorLevel.equals(low_level)) {
                noRelyMap.put(saveModel.getDoctor(), saveModel);
            } else if (SaveModel.deptLevel.equals(low_level)) {
                noRelyMap.put(saveModel.getDept(), saveModel);
            }else if (SaveModel.OrgLevel.equals(low_level)) {
                noRelyMap.put(saveModel.getHospital(), saveModel);
            }
        }

        //转换已回复
        for (SaveModel saveModel : reply) {
            if (SaveModel.doctorLevel.equals(low_level)) {
                relyMap.put(saveModel.getDoctor(), saveModel);
            } else if (SaveModel.deptLevel.equals(low_level)) {
                relyMap.put(saveModel.getDept(), saveModel);
            }else if (SaveModel.OrgLevel.equals(low_level)) {
                relyMap.put(saveModel.getHospital(), saveModel);
            }
        }


        List<Map<String, Object>> resultMaps = new ArrayList<>();
        for (String key : totalMap.keySet()) {
            Map<String, Object> rs = new HashMap<>();
            SaveModel endRs = (SaveModel) endMap.get(key);
            SaveModel totalRs = (SaveModel) totalMap.get(key);
            SaveModel onRelyRs = (SaveModel) noRelyMap.get(key);
            SaveModel relyRs = (SaveModel) relyMap.get(key);
            SaveModel comingRs = (SaveModel) relyMap.get(key);

            if (endRs == null || totalRs == null || onRelyRs == null || relyRs==null || comingRs == null) {
                continue;
            }
            //合并结果集
            Integer totalNm = totalRs.getResult2().intValue();
            Integer endNm = endRs.getResult2().intValue();
            Integer noRelyNm = onRelyRs.getResult2().intValue();
            Integer relyNm = relyRs.getResult2().intValue();
            Integer comingNm = comingRs.getResult2().intValue();
//            rs.put("name", relyRs.get(area+"Name"));
            if (SaveModel.doctorLevel.equals(low_level)) {
                rs.put("name", endRs.getDoctorName());
            } else if (SaveModel.deptLevel.equals(low_level)) {
                rs.put("name", endRs.getDeptName());
            } else if (SaveModel.OrgLevel.equals(low_level)) {
                rs.put("name", endRs.getHospitalName());
            }
            rs.put("noRelyCount", noRelyNm);
            rs.put("endCount", endNm);
            rs.put("total", totalNm);
            rs.put("relyCount", relyNm);
            rs.put("comingCount", comingNm);
            rs.put("code", key);
            if (totalNm != null && totalNm != 0) {
                if (endNm != null && endNm != 0) {
                    double rr = (double) endNm / totalNm * 100;
                    DecimalFormat df = new DecimalFormat("0.00");
                    rs.put("endRate", df.format(rr) + "%");
                    rs.put("endDoubleRate", rr);
                } else {
                    rs.put("endRate", "0.00%");
                    rs.put("endDoubleRate", 0.0);
                }
                if (noRelyNm != null && noRelyNm != 0) {
                    double rr = (double) noRelyNm / totalNm * 100;
                    DecimalFormat df = new DecimalFormat("0.00");
                    rs.put("noRelyRate", df.format(rr) + "%");
                    rs.put("noRelyDoubleRate", rr);
                } else {
                    rs.put("noRelyRate", "0.00%");
                    rs.put("noRelyDoubleRate", 0.0);
                }

            } else {
                rs.put("endRate", "0.00%");
                rs.put("endDoubleRate", 0.0);
                rs.put("noRelyRate", "0.00%");
                rs.put("noRelyDoubleRate", 0.0);
            }
            resultMaps.add(rs);
        }
        //根据为咨询总数排序
        Collections.sort(resultMaps, new Comparator<Map<String, Object>>() {

            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                return (Integer) o1.get("total") < (Integer) o2.get("total") ? 1 : ((Integer) o1.get("total") == (Integer) o2.get("total") ? 0 : -1);
            }
        });
        return resultMaps;
    }





    /**
     *
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index 6专家，13协同，17、在线复诊
     * @param timeLevel
     * @return
     * @throws Exception
     */
    public JSONObject getIndexTotalApp(String startDate, String endDate, String area, int level, String index,String timeLevel) throws Exception {
        JSONObject object = new JSONObject();
        String str[] = new String[]{};
        if (StringUtils.isNoneBlank(index)){
            str =index.split(",");
        }
        for (int i=0;i<str.length;i++){
            String index1 = (Integer.parseInt(str[i])+1)+"";
            if (index1.equalsIgnoreCase("12")){
                SaveModel saveModel1 = null;//图文
                SaveModel saveModel2 = null;//视频
                if (timeLevel.equalsIgnoreCase(SaveModel.timeLevel_ZL)){
                    saveModel1 = elasticsearchUtil.findOneDateQuotaLevel1(startDate, endDate, area, level,"12" , SaveModel.timeLevel_ZL,"9");
                    saveModel2 = elasticsearchUtil.findOneDateQuotaLevel1(startDate, endDate, area, level,"16" , SaveModel.timeLevel_ZL,"16");
                }else if (timeLevel.equalsIgnoreCase(SaveModel.timeLevel_DDL)){
                    saveModel1 = elasticsearchUtil.findOneDateQuotaLevel1(endDate, endDate, area, level,"12" , SaveModel.timeLevel_DDL,"9");
                    saveModel2 = elasticsearchUtil.findOneDateQuotaLevel1(endDate, endDate, area, level,"16" , SaveModel.timeLevel_DDL,"16");
                }
                Double topicTotal = saveModel1.getResult1();
                Double vedioTotal = saveModel2.getResult1();
                object.put("index_11_15",vedioTotal+topicTotal);//在线复诊
            }else {
                SaveModel saveModel = null;
                if (timeLevel.equalsIgnoreCase(SaveModel.timeLevel_ZL)){
                    saveModel = elasticsearchUtil.findOneDateQuotaLevel0(startDate, endDate, area, level,index1 , SaveModel.timeLevel_ZL);
                }else if (timeLevel.equalsIgnoreCase(SaveModel.timeLevel_DDL)){
                    saveModel = elasticsearchUtil.findOneDateQuotaLevel0(endDate, endDate, area, level,index1 , SaveModel.timeLevel_DDL);
                }
                object.put("index_"+str[i],saveModel.getResult1());
            }

        }
        return object;
    }

    /**
     * 按日期柱状图统计处方量
     *
     *
     * @param startDate
     * @param endDate
     * @param area
     * @param level 2科室
     * @param index
     * @param level2_type 4 医院
     * @return
     * @throws Exception
     */
    public JSONObject getPrescriptionLineBy(String startDate, String endDate, String area, int level, String index,int interval, String level2_type) throws Exception {
        logger.info("service index:"+index+" and level2_type:"+level2_type+" and level:"+level);
        String[] indexes = index.split(",");
        String index3 = indexes.length>=3?indexes[2]:"20";
        JSONArray resultArray = new JSONArray();
        //问诊量
        JSONObject object = new JSONObject();
        if (interval==1){
            //图文
            JSONArray array = dateTotalStatistics2(startDate,endDate,area,level,indexes[1],null,SaveModel.timeLevel_ZL,"1");
            object.put("data",array);
            //视频
            JSONArray array1 = dateTotalStatistics2(startDate,endDate,area,level,indexes[1],null,SaveModel.timeLevel_ZL,"2");
            object.put("data2",array1);
            JSONArray arraytotal = dateTotalStatistics2(startDate,endDate,area,level,indexes[1],null,SaveModel.timeLevel_ZL,null);
            object.put("data3",arraytotal);
        }else if (interval==2){
            JSONArray array = weekTotalStatistics2(startDate,endDate,area,level,indexes[1],null,SaveModel.timeLevel_ZL,"1");
            JSONArray array1 = weekTotalStatistics2(startDate,endDate,area,level,indexes[1],null,SaveModel.timeLevel_ZL,"2");
            JSONArray arraytotal = weekTotalStatistics2(startDate,endDate,area,level,indexes[1],null,SaveModel.timeLevel_ZL,null);
            object.put("data",array);
            object.put("data2",array1);
            object.put("data3",arraytotal);
        }else if (interval==3){
            JSONArray array = monthTotalStatistics2(startDate,endDate,area,level,indexes[1],null,SaveModel.timeLevel_ZL,"1");
            JSONArray array1 = monthTotalStatistics2(startDate,endDate,area,level,indexes[1],null,SaveModel.timeLevel_ZL,"2");
            JSONArray arraytotal = monthTotalStatistics2(startDate,endDate,area,level,indexes[1],null,SaveModel.timeLevel_ZL,null);
            object.put("data",array);
            object.put("data2",array1);
            object.put("data3",arraytotal);
        }
        if (StringUtils.isNoneBlank(level2_type)){
            //问诊量表格
            List<SaveModel> outpatientList = elasticsearchUtil.findDateQuotaLevel1(startDate, endDate, area, level, indexes[0], SaveModel.timeLevel_ZL,"","",level2_type);
            //开具处方数量
            Double preNum = 0.0;
            Double outNum = 0.0;
            Double isPayNum = 0.0;//已支付的处方数量
            String prescriptionRate ="";
            String prescriptionPayRate = "";
            List<SaveModel> precriptionList = elasticsearchUtil.findDateQuotaLevel1(startDate, endDate, area, level, indexes[1], SaveModel.timeLevel_ZL,"","",level2_type);
            List<SaveModel> precriptionIsPayList = elasticsearchUtil.findDateQuotaLevel1(startDate, endDate, area, level, index3, SaveModel.timeLevel_ZL,"1","",level2_type);

            if(SaveModel.OrgLevel.equals(level2_type)){
                for(SaveModel saveModel:precriptionList){
                    preNum = saveModel.getResult1();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("hospitalCode",saveModel.getHospital());
                    jsonObject.put("hospitalName",saveModel.getHospitalName());
                    jsonObject.put("specialist",saveModel.getResult1());
                    for(SaveModel saveModel1:outpatientList){
                        String out=saveModel1.getHospital()==null?"":saveModel1.getHospital();
                        String pre=saveModel.getHospital()==null?"":saveModel.getHospital();
                        if(out.equalsIgnoreCase(pre)){
                            outNum = saveModel1.getResult1();
                            prescriptionRate = getRange(preNum.intValue(),outNum.intValue(),0);
                            jsonObject.put("prescriptionRate",prescriptionRate);
                            break;
                        }
                    }
                    for (SaveModel saveModel2:precriptionIsPayList){
                        String isPay=saveModel2.getHospital()==null?"":saveModel2.getHospital();
                        String pre=saveModel.getHospital()==null?"":saveModel.getHospital();
                        if(isPay.equalsIgnoreCase(pre)){
                            isPayNum = saveModel2.getResult1();
                            prescriptionPayRate = getRange(isPayNum.intValue(),preNum.intValue(),0);
                            jsonObject.put("prescriptionPayRate",prescriptionPayRate);
                            break;
                        }
                    }
                    if(null==saveModel.getHospital()){
                        resultArray =new JSONArray();
                    }else {
                        resultArray.add(jsonObject);
                    }
                }
            }
            if(SaveModel.doctorLevel.equals(level2_type)){
                for(SaveModel saveModel:precriptionList){
                    preNum = saveModel.getResult1();
                    JSONObject jsonObject = new JSONObject();
                    String doctorCode = saveModel.getDoctor();
                    BaseDoctorDO baseDoctorDO = doctorDao.findById(doctorCode);
                    if(null!=baseDoctorDO){
                        jsonObject.put("jobTitleCode",baseDoctorDO.getJobTitleCode());
                        jsonObject.put("jobTitleName",baseDoctorDO.getJobTitleName());
                    }
                    jsonObject.put("hospitalCode",saveModel.getHospital());
                    jsonObject.put("hospitalName",saveModel.getHospitalName());
                    jsonObject.put("deptNo",saveModel.getDept());
                    jsonObject.put("deptName",saveModel.getDeptName());
                    jsonObject.put("specialist",saveModel.getResult1());
                    jsonObject.put("doctorName",saveModel.getDoctorName());
                    jsonObject.put("doctorCode",saveModel.getDoctor());
                    for(SaveModel saveModel1:outpatientList){
                        String outdoc=saveModel1.getDoctor()==null?"":saveModel1.getDoctor();
                        String predoc=saveModel.getDoctor()==null?"":saveModel.getDoctor();
                        if(outdoc.equalsIgnoreCase(predoc)){
                            outNum = saveModel1.getResult1();
                            prescriptionRate = getRange(preNum.intValue(),outNum.intValue(),0);
                            jsonObject.put("prescriptionRate",prescriptionRate);
                            break;
                        }
                    }
                    for (SaveModel saveModel2:precriptionIsPayList){
                        String isPay=saveModel2.getDoctor()==null?"":saveModel2.getDoctor();
                        String pre=saveModel.getDoctor()==null?"":saveModel.getDoctor();
                        if(isPay.equalsIgnoreCase(pre)){
                            isPayNum = saveModel2.getResult1();
                            prescriptionPayRate = getRange(isPayNum.intValue(),preNum.intValue(),0);
                            jsonObject.put("prescriptionPayRate",prescriptionPayRate);
                            break;
                        }
                    }
                    if(null==saveModel.getDoctor()){
                        resultArray =new JSONArray();
                    }else {
                        resultArray.add(jsonObject);
                    }
                }

            }
            if(SaveModel.deptLevel.equals(level2_type)){
                for(SaveModel saveModel:precriptionList){
                    preNum = saveModel.getResult1();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("hospitalCode",saveModel.getHospital());
                    jsonObject.put("hospitalName",saveModel.getHospitalName());
                    jsonObject.put("deptNo",saveModel.getDept());
                    jsonObject.put("deptName",saveModel.getDeptName());
                    jsonObject.put("specialist",saveModel.getResult1());
                    for(SaveModel saveModel1:outpatientList){
                        String out=saveModel1.getDept()==null?"":saveModel1.getDept();
                        String pre=saveModel.getDept()==null?"":saveModel.getDept();
                        if(out.equalsIgnoreCase(pre)){
                            outNum = saveModel1.getResult1();
                            prescriptionRate = getRange(preNum.intValue(),outNum.intValue(),0);
                            jsonObject.put("prescriptionRate",prescriptionRate);
                            break;
                        }
                    }
                    for (SaveModel saveModel2:precriptionIsPayList){
                        String isPay=saveModel2.getDept()==null?"":saveModel2.getDept();
                        String pre=saveModel.getDept()==null?"":saveModel.getDept();
                        if(isPay.equalsIgnoreCase(pre)){
                            isPayNum = saveModel2.getResult1();
                            prescriptionPayRate = getRange(isPayNum.intValue(),preNum.intValue(),0);
                            jsonObject.put("prescriptionPayRate",prescriptionPayRate);
                            break;
                        }
                    }
                    if(null==saveModel.getDept()){
                        resultArray =new JSONArray();
                    }else {
                        resultArray.add(jsonObject);
                    }
                }

            }
        }else {
            //问诊量表格
            List<SaveModel> outpatientList = elasticsearchUtil.findDateQuotaLevel1(startDate, endDate, area, level, indexes[0], SaveModel.timeLevel_ZL,"","","4");
            //开具处方数量
            Double preNum = 0.0;
            Double outNum = 0.0;
            Double isPayNum = 0.0;//已支付的处方数量
            String prescriptionRate ="";
            String prescriptionPayRate = "";
            List<SaveModel> precriptionList = elasticsearchUtil.findDateQuotaLevel1(startDate, endDate, area, level, indexes[1], SaveModel.timeLevel_ZL,"","","4");
            List<SaveModel> precriptionIsPayList = elasticsearchUtil.findDateQuotaLevel1(startDate, endDate, area, level, index3, SaveModel.timeLevel_ZL,"1","","4");
            for(SaveModel saveModel:precriptionList){
                preNum = saveModel.getResult1();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("hospitalCode",saveModel.getHospital());
                jsonObject.put("hospitalName",saveModel.getHospitalName());
                jsonObject.put("deptNo",saveModel.getDept());
                jsonObject.put("deptName",saveModel.getDeptName());
                jsonObject.put("specialist",saveModel.getResult1());
                jsonObject.put("doctorName",saveModel.getDoctorName());
                jsonObject.put("doctorCode",saveModel.getDoctor());
                for(SaveModel saveModel1:outpatientList){
                    String out=saveModel1.getHospital()==null?"":saveModel1.getHospital();
                    String pre=saveModel.getHospital()==null?"":saveModel.getHospital();
                    if(out.equalsIgnoreCase(pre)){
                        outNum = saveModel1.getResult1();
                        prescriptionRate = getRange(preNum.intValue(),outNum.intValue(),0);
                        jsonObject.put("prescriptionRate",prescriptionRate);
                        break;
                    }
                }
                for (SaveModel saveModel2:precriptionIsPayList){
                    String isPay=saveModel2.getHospital()==null?"":saveModel2.getHospital();
                    String pre=saveModel.getHospital()==null?"":saveModel.getHospital();
                    if(isPay.equalsIgnoreCase(pre)){
                        isPayNum = saveModel2.getResult1();
                        prescriptionPayRate = getRange(isPayNum.intValue(),preNum.intValue(),0);
                        jsonObject.put("prescriptionPayRate",prescriptionPayRate);
                        break;
                    }
                }
                if(null==saveModel.getHospital()){
                    resultArray =new JSONArray();
                }else {
                    resultArray.add(jsonObject);
                }
            }
        }
        List<JSONObject> bindArrayResult = JSONArray.parseArray(resultArray.toJSONString(), JSONObject.class);
        System.out.println("排序前："+bindArrayResult);
        Collections.sort(bindArrayResult, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                double a = o1.getDouble("specialist");
                double b = o2.getDouble("specialist");
                if (a > b) {
                    return -1;
                } else if(a == b) {
                    return 0;
                } else
                    return 1;
            }
        });
        JSONArray jsonArray = JSONArray.parseArray(bindArrayResult.toString());
        object.put("excelData",jsonArray);
        return object;
    }
    /**
     * 按日期柱状图 取药方式统计处方量
     *
     *
     * @param startDate
     * @param endDate
     * @param area
     * @param level 2科室
     * @param index
     * @param level2_type 4 医院
     * @return
     * @throws Exception
     */
    public JSONObject getPrescriptionLineByType(String startDate, String endDate, String area, int level, String index,int interval, String level2_type) throws Exception {
        logger.info("service index:"+index+" and level2_type:"+level2_type+" and level:"+level);
        String[] indexes = index.split(",");
        String index3 = indexes.length>=3?indexes[2]:"20";
        JSONArray resultArray = new JSONArray();
        //问诊量
        JSONObject object = new JSONObject();
        if (interval==1){
            //自取
            JSONArray array = dateTotalStatistics2(startDate,endDate,area,level,indexes[1],"1",SaveModel.timeLevel_ZL,"");
            object.put("data",array);
            //快递
            JSONArray array1 = dateTotalStatistics2(startDate,endDate,area,level,indexes[1],"0",SaveModel.timeLevel_ZL,null);
            object.put("data2",array1);
            JSONArray arraytotal = dateTotalStatistics2(startDate,endDate,area,level,indexes[1],null,SaveModel.timeLevel_ZL,null);
            object.put("data3",arraytotal);
        }else if (interval==2){
            JSONArray array = weekTotalStatistics2(startDate,endDate,area,level,indexes[1],"1",SaveModel.timeLevel_ZL,"");
            JSONArray array1 = weekTotalStatistics2(startDate,endDate,area,level,indexes[1],"0",SaveModel.timeLevel_ZL,"");
            object.put("data",array);
            object.put("data2",array1);
            JSONArray arraytotal = weekTotalStatistics2(startDate,endDate,area,level,indexes[1],null,SaveModel.timeLevel_ZL,null);
            object.put("data3",arraytotal);
        }else if (interval==3){
            JSONArray array = monthTotalStatistics2(startDate,endDate,area,level,indexes[1],"1",SaveModel.timeLevel_ZL,"");
            JSONArray array1 = monthTotalStatistics2(startDate,endDate,area,level,indexes[1],"0",SaveModel.timeLevel_ZL,"");
            object.put("data",array);
            object.put("data2",array1);
            JSONArray arraytotal = monthTotalStatistics2(startDate,endDate,area,level,indexes[1],null,SaveModel.timeLevel_ZL,null);
            object.put("data3",arraytotal);
        }
        if (StringUtils.isNoneBlank(level2_type)) {
            List<SaveModel> outpatientList = elasticsearchUtil.findDateQuotaLevel1(startDate, endDate, area, level, indexes[0], SaveModel.timeLevel_ZL, "", "", level2_type);
            //开具处方数量
            Double preNum = 0.0;
            Double outNum = 0.0;
            Double isPayNum = 0.0;//已支付的处方数量
            String prescriptionRate = "";
            String prescriptionPayRate = "";
            List<SaveModel> precriptionList = elasticsearchUtil.findDateQuotaLevel1(startDate, endDate, area, level, indexes[1], SaveModel.timeLevel_ZL, "", "", level2_type);
            List<SaveModel> precriptionIsPayList = elasticsearchUtil.findDateQuotaLevel1(startDate, endDate, area, level, index3, SaveModel.timeLevel_ZL,"1","",level2_type);
            if (SaveModel.OrgLevel.equals(level2_type)) {
                //问诊量表格
                for (SaveModel saveModel : precriptionList) {
                    preNum = saveModel.getResult1();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("hospitalCode", saveModel.getHospital());
                    jsonObject.put("hospitalName", saveModel.getHospitalName());
                    jsonObject.put("specialist", saveModel.getResult1());
                    for (SaveModel saveModel1 : outpatientList) {
                        String out=saveModel1.getHospital()==null?"":saveModel1.getHospital();
                        String pre=saveModel.getHospital()==null?"":saveModel.getHospital();
                        if(out.equalsIgnoreCase(pre)){
                            outNum = saveModel1.getResult1();
                            prescriptionRate = getRange(preNum.intValue(), outNum.intValue(), 0);
                            jsonObject.put("prescriptionRate", prescriptionRate);
                            break;
                        }
                    }
                    for (SaveModel saveModel2:precriptionIsPayList){
                        String isPay=saveModel2.getHospital()==null?"":saveModel2.getHospital();
                        String pre=saveModel.getHospital()==null?"":saveModel.getHospital();
                        if(isPay.equalsIgnoreCase(pre)){
                            isPayNum = saveModel2.getResult1();
                            prescriptionPayRate = getRange(isPayNum.intValue(),preNum.intValue(),0);
                            jsonObject.put("prescriptionPayRate",prescriptionPayRate);
                            break;
                        }
                    }
                    if(null==saveModel.getHospital()){
                        resultArray =new JSONArray();
                    }else {
                        resultArray.add(jsonObject);
                    }
                }
            }
            if (SaveModel.doctorLevel.equals(level2_type)) {
                for (SaveModel saveModel : precriptionList) {
                    preNum = saveModel.getResult1();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("hospitalCode", saveModel.getHospital());
                    jsonObject.put("hospitalName", saveModel.getHospitalName());
                    jsonObject.put("deptNo", saveModel.getDept());
                    jsonObject.put("deptName", saveModel.getDeptName());
                    jsonObject.put("specialist", saveModel.getResult1());
                    jsonObject.put("doctorName", saveModel.getDoctorName());
                    jsonObject.put("doctorCode", saveModel.getDoctor());
                    for (SaveModel saveModel1 : outpatientList) {
                        String out=saveModel1.getDoctor()==null?"":saveModel1.getDoctor();
                        String pre=saveModel.getDoctor()==null?"":saveModel.getDoctor();
                        if(out.equalsIgnoreCase(pre)){
                            outNum = saveModel1.getResult1();
                            prescriptionRate = getRange(preNum.intValue(), outNum.intValue(), 0);
                            jsonObject.put("prescriptionRate", prescriptionRate);
                            break;
                        }
                    }
                    for (SaveModel saveModel2:precriptionIsPayList){
                        String isPay=saveModel2.getDoctor()==null?"":saveModel2.getDoctor();
                        String pre=saveModel.getDoctor()==null?"":saveModel.getDoctor();
                        if(isPay.equalsIgnoreCase(pre)){
                            isPayNum = saveModel2.getResult1();
                            prescriptionPayRate = getRange(isPayNum.intValue(),preNum.intValue(),0);
                            jsonObject.put("prescriptionPayRate",prescriptionPayRate);
                            break;
                        }
                    }
                    if(null==saveModel.getDoctor()){
                        resultArray =new JSONArray();
                    }else {
                        resultArray.add(jsonObject);
                    }
                }

            }
            if (SaveModel.deptLevel.equals(level2_type)) {
                for (SaveModel saveModel : precriptionList) {
                    preNum = saveModel.getResult1();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("hospitalCode", saveModel.getHospital());
                    jsonObject.put("hospitalName", saveModel.getHospitalName());
                    jsonObject.put("deptNo", saveModel.getDept());
                    jsonObject.put("deptName", saveModel.getDeptName());
                    jsonObject.put("name", saveModel.getHospitalName());
                    jsonObject.put("specialist", saveModel.getResult1());
                    for (SaveModel saveModel1 : outpatientList) {
                        String out=saveModel1.getDept()==null?"":saveModel1.getDept();
                        String pre=saveModel.getDept()==null?"":saveModel.getDept();
                        if(out.equalsIgnoreCase(pre)){
                            outNum = saveModel1.getResult1();
                            prescriptionRate = getRange(preNum.intValue(), outNum.intValue(), 0);
                            jsonObject.put("prescriptionRate", prescriptionRate);
                            break;
                        }
                    }
                    for (SaveModel saveModel2:precriptionIsPayList){
                        String isPay=saveModel2.getDept()==null?"":saveModel2.getDept();
                        String pre=saveModel.getDept()==null?"":saveModel.getDept();
                        if(isPay.equalsIgnoreCase(pre)){
                            isPayNum = saveModel2.getResult1();
                            prescriptionPayRate = getRange(isPayNum.intValue(),preNum.intValue(),0);
                            jsonObject.put("prescriptionPayRate",prescriptionPayRate);
                            break;
                        }
                    }
                    if(null==saveModel.getDept()){
                        resultArray =new JSONArray();
                    }else {
                        resultArray.add(jsonObject);
                    }
                }

            }
        }else{
            List<SaveModel> outpatientList = elasticsearchUtil.findDateQuotaLevel1(startDate, endDate, area, level, indexes[0], SaveModel.timeLevel_ZL, "", "", "4");
            //开具处方数量
            Double preNum = 0.0;
            Double outNum = 0.0;
            Double isPayNum = 0.0;//已支付的处方数量
            String prescriptionRate = "";
            String prescriptionPayRate = "";
            List<SaveModel> precriptionList = elasticsearchUtil.findDateQuotaLevel1(startDate, endDate, area, level, indexes[1], SaveModel.timeLevel_ZL, "", "", "4");
            List<SaveModel> precriptionIsPayList = elasticsearchUtil.findDateQuotaLevel1(startDate, endDate, area, level, index3, SaveModel.timeLevel_ZL,"1","","4");
            for (SaveModel saveModel : precriptionList) {
                preNum = saveModel.getResult1();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("hospitalCode", saveModel.getHospital());
                jsonObject.put("hospitalName", saveModel.getHospitalName());
                jsonObject.put("deptNo", saveModel.getDept());
                jsonObject.put("deptName", saveModel.getDeptName());
                jsonObject.put("specialist", saveModel.getResult1());
                jsonObject.put("doctorName", saveModel.getDoctorName());
                jsonObject.put("doctorCode", saveModel.getDoctor());
                for (SaveModel saveModel1 : outpatientList) {
                    String out=saveModel1.getHospital()==null?"":saveModel1.getHospital();
                    String pre=saveModel.getHospital()==null?"":saveModel.getHospital();
                    if(out.equalsIgnoreCase(pre)){
                        outNum = saveModel1.getResult1();
                        prescriptionRate = getRange(preNum.intValue(), outNum.intValue(), 0);
                        jsonObject.put("prescriptionRate", prescriptionRate);
                        break;
                    }
                }
                for (SaveModel saveModel2:precriptionIsPayList){
                    String isPay=saveModel2.getHospital()==null?"":saveModel2.getHospital();
                    String pre=saveModel.getHospital()==null?"":saveModel.getHospital();
                    if(isPay.equalsIgnoreCase(pre)){
                        isPayNum = saveModel2.getResult1();
                        prescriptionPayRate = getRange(isPayNum.intValue(),preNum.intValue(),0);
                        jsonObject.put("prescriptionPayRate",prescriptionPayRate);
                        break;
                    }
                }
                if(null==saveModel.getHospital()){
                    resultArray =new JSONArray();
                }else {
                    resultArray.add(jsonObject);
                }
            }
        }
        object.put("excelData",resultArray);
        return object;
    }

    /**
     * app端头部收入统计
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @return
     */
    public  JSONObject appIndexHead(String startDate, String endDate, String area, int level, String index) throws Exception {
        JSONObject object = new JSONObject();
        String nowStartDate = DateUtil.getStringDateShort();
        String monthStartDate = DateUtil.getFristDayOfMonth();
        String monthEndDate = DateUtil.getLastDayOfMonth();
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        //今日收入总收入
        SaveModel nowPrice = elasticsearchUtil.findOneDateQuotaLevel0(nowStartDate, nowStartDate, area, level, index, SaveModel.timeLevel_ZL);
        object.put("nowPrice",decimalFormat.format(nowPrice.getResult1()));
        //本月总收入
        SaveModel nowMonthPrice = elasticsearchUtil.findOneDateQuotaLevel0(monthStartDate, monthEndDate, area, level, index, SaveModel.timeLevel_ZL);
        object.put("nowMonthPrice",decimalFormat.format(nowPrice.getResult1()));
        SaveModel totalPrice = elasticsearchUtil.findOneDateQuotaLevel0(nowStartDate, nowStartDate, area, level, index, SaveModel.timeLevel_DDL);
        object.put("totalPrice",decimalFormat.format(totalPrice.getResult1()));
        return object;
    }


    public  JSONObject appIndexCenter(String startDate, String endDate, String area, int level, String index) throws Exception {
        JSONObject object = new JSONObject();
        //图文复诊
        SaveModel topicTotal = elasticsearchUtil.findOneDateQuotaLevel1(startDate, endDate, area, level, "12", SaveModel.timeLevel_ZL,"9");
        object.put("topicTotal",topicTotal.getResult1());
        //视频复诊
        SaveModel videoTotal = elasticsearchUtil.findOneDateQuotaLevel1(startDate, endDate, area, level, "16", SaveModel.timeLevel_ZL,"16");
        object.put("videoTotal",videoTotal.getResult1());
        //专家咨询twzxData
        SaveModel specialistTotal = elasticsearchUtil.findOneDateQuotaLevel1(startDate, endDate, area, level, "12", SaveModel.timeLevel_ZL,"1");
        object.put("twzxTotal",specialistTotal.getResult1());
        //专家咨询twzxData
        SaveModel specialistSPTotal = elasticsearchUtil.findOneDateQuotaLevel1(startDate, endDate, area, level, "16", SaveModel.timeLevel_ZL,"17");
        object.put("spzxTotal",specialistSPTotal.getResult1());
        //专科协同
        SaveModel synergyTotal = elasticsearchUtil.findOneDateQuotaLevel1(startDate, endDate, area, level, "14", SaveModel.timeLevel_ZL,"12");
        object.put("synergyTotal",synergyTotal.getResult1());
        return object;
    }

    public  JSONObject appPriceHead(String startDate, String endDate, String area,int level, String index) throws Exception {
        JSONObject object = new JSONObject();
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        //图文复诊
        SaveModel topicTotal = elasticsearchUtil.findOneDateQuotaLevel2(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL,"1","1");
        object.put("topicTotal",decimalFormat.format(topicTotal.getResult1()));
        //视频复诊
        SaveModel videoTotal = elasticsearchUtil.findOneDateQuotaLevel2(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL,"1","2");
        object.put("videoTotal",decimalFormat.format(videoTotal.getResult1()));
        /*//专家咨询
        SaveModel specialistTotal = elasticsearchUtil.findOneDateQuotaLevel1(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL,"3");
        object.put("specialistTotal",decimalFormat.format(specialistTotal.getResult1()));*/
        //专家图文
        SaveModel specialistTW = elasticsearchUtil.findOneDateQuotaLevel2(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL,"3","1");
        object.put("specialistTW",decimalFormat.format(specialistTW.getResult1()));
        //专家视频
        SaveModel specialistSP = elasticsearchUtil.findOneDateQuotaLevel2(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL,"3","2");
        object.put("specialistSP",decimalFormat.format(specialistSP.getResult1()));

        //专科协同
        SaveModel synergyTotal = elasticsearchUtil.findOneDateQuotaLevel1(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL,"2");
        object.put("synergyTotal",decimalFormat.format(synergyTotal.getResult1()));
        //总收入
        SaveModel totalPrice = elasticsearchUtil.findOneDateQuotaLevel0(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL);
        object.put("totalPrice",decimalFormat.format(totalPrice.getResult1()));
        return object;
    }

    public  JSONObject appPrescriptionHead(String startDate, String endDate, String area,int level, String index) throws Exception {
        JSONObject object = new JSONObject();
        //图文复诊
        SaveModel topicTotal = elasticsearchUtil.findOneDateQuotaLevel2NoSlaveKey1(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL,"1");
        object.put("topicTotal",topicTotal.getResult1());
        //视频复诊
        SaveModel videoTotal = elasticsearchUtil.findOneDateQuotaLevel2NoSlaveKey1(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL,"2");
        object.put("videoTotal",videoTotal.getResult1());
        //快递
        SaveModel expressTotal = elasticsearchUtil.findOneDateQuotaLevel3NoSlaveKey2(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL,"0");
        object.put("express",expressTotal.getResult1());
        //自取
        SaveModel inviteTotal = elasticsearchUtil.findOneDateQuotaLevel3NoSlaveKey2(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL,"1");
        object.put("invite",inviteTotal.getResult1());
        //总计
        SaveModel specialistTotal = elasticsearchUtil.findOneDateQuotaLevel0(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL);
        object.put("total",specialistTotal.getResult1());
        return object;
    }


    public JSONObject appCenterCircular(String startDate, String endDate, String area, int level, String index,String flag) throws Exception {

        JSONObject object = new JSONObject();
        if (index.equalsIgnoreCase("3")||index.equalsIgnoreCase("3,21")||index.equalsIgnoreCase("21")){
            //协同门诊
            SaveModel saveModel1 = null;
            saveModel1 = elasticsearchUtil.findOneDateQuotaLevel1(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL, "2");
            //图文复诊
            SaveModel saveModel2 = null;
            //saveModel2 = elasticsearchUtil.findOneDateQuotaLevel2(endDate, endDate, area, level, index, SaveModel.timeLevel_DDL, "1","1");
            saveModel2 = elasticsearchUtil.findOneDateQuotaLevel2(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL, "1","1");
            //视频复诊
            SaveModel saveModel3 = null;
/*
    saveModel3 = elasticsearchUtil.findOneDateQuotaLevel2(endDate, endDate, area, level, index, SaveModel.timeLevel_DDL, "1","2");
*/
            saveModel3 = elasticsearchUtil.findOneDateQuotaLevel2(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL, "1","2");
            Double specialistCount =0.0;
            //专科咨询
            SaveModel saveModel4 = null;
            saveModel4 = elasticsearchUtil.findOneDateQuotaLevel2(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL, "3","1");
            specialistCount = saveModel4.getResult1();//专家咨询TW数量
            Double specialistCountSP =0.0;
            //专科咨询
            SaveModel saveModel6 = null;
            saveModel6 = elasticsearchUtil.findOneDateQuotaLevel2(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL, "3","2");
            specialistCountSP = saveModel6.getResult1();//专家咨询SP数量


            //总量
            SaveModel saveModel5 = null;
            saveModel5 = elasticsearchUtil.findOneDateQuotaLevel0(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL);


            Double synergyCount = saveModel1.getResult1();//协同门诊数量
            Double topicCount = saveModel2.getResult1();//图文复诊数量
            Double videoCount = saveModel3.getResult1();//视频复诊数量
            Double total = saveModel5.getResult1();//总量
            DecimalFormat decimalFormat = new DecimalFormat("0.00");
            object.put("specialistCount",decimalFormat.format(specialistCount));//专家咨询数
            object.put("specialistSPCount",decimalFormat.format(specialistCountSP));//专家咨询视频数
            object.put("specialistRate",getRange(specialistCount.intValue(),total.intValue(),0));
            object.put("specialistSPRate",getRange(specialistCountSP.intValue(),total.intValue(),0));
            object.put("synergyCount",decimalFormat.format(synergyCount));//专家咨询数
            object.put("synergyRate",getRange(synergyCount.intValue(),total.intValue(),0));
            object.put("topicCount",decimalFormat.format(topicCount));//图文复诊数量
            object.put("topicRate",getRange(topicCount.intValue(),total.intValue(),0));
            object.put("videoCount",decimalFormat.format(videoCount));//视频复诊数量
            object.put("videoRate",getRange(videoCount.intValue(),total.intValue(),0));
            object.put("total",decimalFormat.format(total));

        }else if (index.equalsIgnoreCase("20")){
            if (flag.equalsIgnoreCase("1")){
                //图文复诊
                SaveModel saveModel2 = null;
                saveModel2 = elasticsearchUtil.findOneDateQuotaLevel2NoSlaveKey1(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL, "1");
                //视频复诊
                SaveModel saveModel3 = null;
                saveModel3 = elasticsearchUtil.findOneDateQuotaLevel2NoSlaveKey1(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL, "2");
                //总数
                SaveModel saveModel1 = null;
                saveModel1 = elasticsearchUtil.findOneDateQuotaLevel0(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL);
                Double topicCount = saveModel2.getResult1();//图文复诊数量
                Double videoCount = saveModel3.getResult1();//视频复诊数量
                Double total = saveModel1.getResult1();//总量
                object.put("topicCount",topicCount);//图文复诊数量
                object.put("topicRate",getRange(topicCount.intValue(),total.intValue(),0));
                object.put("videoCount",videoCount);//视频复诊数量
                object.put("videoRate",getRange(videoCount.intValue(),total.intValue(),0));
                object.put("total",total);
            }else if (flag.equalsIgnoreCase("2")){
                //快递
                SaveModel saveModel2 = null;
                saveModel2 = elasticsearchUtil.findOneDateQuotaLevel3NoSlaveKey2(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL, "0");
                //自取
                SaveModel saveModel3 = null;
                saveModel3 = elasticsearchUtil.findOneDateQuotaLevel3NoSlaveKey2(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL, "1");
                //总数
                SaveModel saveModel1 = null;
                saveModel1 = elasticsearchUtil.findOneDateQuotaLevel0(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL);
                Double topicCount = saveModel2.getResult1();//图文复诊数量
                Double videoCount = saveModel3.getResult1();//视频复诊数量
                Double total = saveModel1.getResult1();//总量
                object.put("express",topicCount);//快递数量
                object.put("expressRate",getRange(topicCount.intValue(),total.intValue(),0));
                object.put("invite",videoCount);//自取数量
                object.put("inviteRate",getRange(videoCount.intValue(),total.intValue(),0));
                object.put("total",total);
            }


        }
        return object;
    }

    /**
     * 按周统计 折线图
     *
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param lowCode
     * @return
     * @throws Exception
     */
    private JSONArray weekTotalStatistics7(String startDate, String endDate, String area, int level, String index, String lowCode, String timelevel) throws Exception {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        // 起始日期
        Calendar start = Calendar.getInstance();
        start.setTime(DateUtil.strToDate(startDate, DateUtil.YYYY_MM_DD));
        // 第一个统计周期结束日期
        String firstEnd = "";
        // 结束日期
        Calendar end = Calendar.getInstance();
        //因为统计时间是统计到当前时间的前一天，所以这里的时间是提前一天
        Calendar temp = Calendar.getInstance();
        temp.setTime(DateUtil.strToDate(endDate, DateUtil.YYYY_MM_DD));
//        temp.add(Calendar.DAY_OF_MONTH, -1);
        end.setTime(temp.getTime());
        // 起始日期为周几
        int week = start.get(Calendar.DAY_OF_WEEK);
        int incre = 7 - week + 1;

        // 日期集合
        List<Calendar> days = new ArrayList<>();
        days.add(start);
        boolean flag = true;
        int i = 0;

        if (startDate.compareTo(endDate) == 0) {
            flag = false;
            days.add(end);
            firstEnd = df.format(end.getTime());
        }

        // 计算统计日期
        while (flag) {
            Calendar next = Calendar.getInstance();
            next.setTime(days.get(days.size() - 1).getTime());

            if (i == 0) {
                if (incre != 7) {
                    next.add(Calendar.DATE, incre);
                }
            } else {
                next.add(Calendar.DATE, 7);
            }
            if (next.getTime().before(DateUtil.strToDate(endDate, "yyyy-MM-dd"))) {
                days.add(next);
                if (i == 0) {
                    firstEnd = df.format(next.getTime());
                }
            } else {
                days.add(end);
                flag = false;
                if (i == 0) {
                    firstEnd = df.format(end.getTime());
                }
            }

            i++;
        }

        // 结果集
        Map<String, JSONObject> countResult = new HashMap<>();

//        Date dd = df.parse();

        // 算出每个查询周期
        for (int j = 0; j < days.size() - 1; j++) {
            String startStr = "";
            String endStr = df.format(days.get(j + 1).getTime());

            // 起始、截止日期
            if (j == 0) {
                startStr = df.format(days.get(j).getTime());
            } else {
                Calendar cal = Calendar.getInstance();
                cal.setTime(days.get(j).getTime());
                cal.add(Calendar.DATE, 1);
                startStr = df.format(cal.getTime());
            }

            JSONObject range = new JSONObject();
            range.put("range", endStr);
            range.put("amount", 0);
            range.put("num",0.00);
            countResult.put(endStr, range);


//            if(!DateUtil.getSundayOfThisDate(new Date()).equals(df.format(new Date()))){
//                JSONObject range2 = new JSONObject();
//                range2.put("range", endDate);
//                range2.put("amount", 0);
//                countResult.put(df.format(new Date()), range2);
//            };
        }

        if (startDate.equals(df.format(new Date()))) {
            Calendar preDate = Calendar.getInstance();
            preDate.setTime(df.parse(endDate));
            preDate.add(Calendar.DATE, -1);

            startDate = df.format(preDate.getTime());
        }

        List<SaveModel> saveModels = new ArrayList<>();
        if (StringUtils.isNotBlank(lowCode)) {
            saveModels = elasticsearchUtil.findLineChartDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, SaveModel.interval_day, lowCode);
        } else {
            saveModels = elasticsearchUtil.findLineChartDateQuotaLevel0(startDate, endDate, area, level, index, timelevel, SaveModel.interval_day);
        }
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        if (saveModels != null) {
            // 计算结果
            for (SaveModel saveModel : saveModels) {
                String range = "";
                if (saveModel.getQuotaDate() != null) {
                    Calendar quotaDate = Calendar.getInstance();
                    quotaDate.setTime(saveModel.getQuotaDate());
                    int thisWeek = quotaDate.get(Calendar.DAY_OF_WEEK);
                    switch (thisWeek){
                        case 1:
                            thisWeek =7;
                            break;
                        case 2:
                            thisWeek =1;
                            break;
                        case 3:
                            thisWeek =2;
                            break;
                        case 4:
                            thisWeek =3;
                            break;
                        case 5:
                            thisWeek =4;
                            break;
                        case 6:
                            thisWeek =5;
                            break;
                        case 7:
                            thisWeek =6;
                            break;
                    }
                    int thisIncre = 7 - thisWeek;
                    quotaDate.add(Calendar.DATE, thisIncre);
                    if(quotaDate.getTime().before(DateUtil.strToDate(endDate, "yyyy-MM-dd"))){
                        range = df.format(quotaDate.getTime());
                    }else {
                        range = df.format(DateUtil.strToDate(endDate, "yyyy-MM-dd"));
                    }


                }
                JSONObject json = countResult.get(range);
//                //因为上述时间集提前一天  但是前端是显示当前时间，所以这里给调整回去
//                if (range.equals(df.format(temp.getTime()))) {
//                    json.put("range", endDate);
//                }
                if (json != null) {
                    long amount = saveModel.getResult2().longValue();
                    double num = saveModel.getResult1();
                    long previousAmount = Long.valueOf(json.get("amount").toString());
                    double previousNum = Double.parseDouble(json.get("num").toString());
                    json.put("amount", amount+previousAmount);
                    json.put("num",decimalFormat.format(num+previousNum));
                }
            }

            List<JSONObject> result = new ArrayList<>(countResult.values());

            // 排序
            result.sort(new Comparator<JSONObject>() {
                @Override
                public int compare(JSONObject o1, JSONObject o2) {
                    if (o1.getString("range").compareTo(o2.getString("range")) > 0) {
                        return 1;
                    } else if (o1.getString("range").compareTo(o2.getString("range")) < 0) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            });
            JSONArray jsonArray = new JSONArray();
            for (JSONObject object:result){
                jsonArray.add(object);
            }

            return jsonArray;
        } else {
            return new JSONArray();
        }

    }
    /**
     * 两位小数
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param lowCode
     * @param timelevel
     * @param lowCode2
     * @return
     * @throws Exception
     */
    private JSONArray weekTotalStatistics8(String startDate, String endDate, String area, int level, String index, String lowCode, String timelevel,String lowCode2) throws Exception {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        // 起始日期
        Calendar start = Calendar.getInstance();
        start.setTime(DateUtil.strToDate(startDate, DateUtil.YYYY_MM_DD));
        // 第一个统计周期结束日期
        String firstEnd = "";
        // 结束日期
        Calendar end = Calendar.getInstance();
        //因为统计时间是统计到当前时间的前一天，所以这里的时间是提前一天
        Calendar temp = Calendar.getInstance();
        temp.setTime(DateUtil.strToDate(endDate, DateUtil.YYYY_MM_DD));
//        temp.add(Calendar.DAY_OF_MONTH, -1);
        end.setTime(temp.getTime());
        // 起始日期为周几
        int week = start.get(Calendar.DAY_OF_WEEK);
        int incre = 7 - week + 1;

        // 日期集合
        List<Calendar> days = new ArrayList<>();
        days.add(start);
        boolean flag = true;
        int i = 0;

        if (startDate.compareTo(endDate) == 0) {
            flag = false;
            days.add(end);
            firstEnd = df.format(end.getTime());
        }

        // 计算统计日期
        while (flag) {
            Calendar next = Calendar.getInstance();
            next.setTime(days.get(days.size() - 1).getTime());

            if (i == 0) {
                if (incre != 7) {
                    next.add(Calendar.DATE, incre);
                }
            } else {
                next.add(Calendar.DATE, 7);
            }
            if (next.getTime().before(DateUtil.strToDate(endDate, "yyyy-MM-dd"))) {
                days.add(next);
                if (i == 0) {
                    firstEnd = df.format(next.getTime());
                }
            } else {
                days.add(end);
                flag = false;
                if (i == 0) {
                    firstEnd = df.format(end.getTime());
                }
            }

            i++;
        }

        // 结果集
        Map<String, JSONObject> countResult = new HashMap<>();

//        Date dd = df.parse();

        // 算出每个查询周期
        for (int j = 0; j < days.size() - 1; j++) {
            String startStr = "";
            String endStr = df.format(days.get(j + 1).getTime());

            // 起始、截止日期
            if (j == 0) {
                startStr = df.format(days.get(j).getTime());
            } else {
                Calendar cal = Calendar.getInstance();
                cal.setTime(days.get(j).getTime());
                cal.add(Calendar.DATE, 1);
                startStr = df.format(cal.getTime());
            }

            JSONObject range = new JSONObject();
            range.put("range", endStr);
            range.put("amount", 0);
            range.put("num",0.00);
            countResult.put(endStr, range);


//            if(!DateUtil.getSundayOfThisDate(new Date()).equals(df.format(new Date()))){
//                JSONObject range2 = new JSONObject();
//                range2.put("range", endDate);
//                range2.put("amount", 0);
//                countResult.put(df.format(new Date()), range2);
//            };
        }

        if (startDate.equals(df.format(new Date()))) {
            Calendar preDate = Calendar.getInstance();
            preDate.setTime(df.parse(endDate));
            preDate.add(Calendar.DATE, -1);

            startDate = df.format(preDate.getTime());
        }


        List<SaveModel> saveModels = new ArrayList<>();
        if (StringUtils.isNotBlank(lowCode)) {
            if (StringUtils.isNoneBlank(lowCode2)){
                saveModels = elasticsearchUtil.findLineChartDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, SaveModel.interval_day, lowCode,lowCode2);
            }else {
                saveModels = elasticsearchUtil.findLineChartDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, SaveModel.interval_day, lowCode);
            }

        }else if(StringUtils.isNoneBlank(lowCode2)&&StringUtils.isBlank(lowCode)){
            saveModels = elasticsearchUtil.findLineChartDateQuotaLevel2OnlySlaveKey2(startDate, endDate, area, level, index, timelevel, SaveModel.interval_day,lowCode2);
        }
        else {
            saveModels = elasticsearchUtil.findLineChartDateQuotaLevel0(startDate, endDate, area, level, index, timelevel, SaveModel.interval_day);
        }

        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        if (saveModels != null) {
            // 计算结果
            for (SaveModel saveModel : saveModels) {
                String range = "";
                if (saveModel.getQuotaDate() != null) {
                    Calendar quotaDate = Calendar.getInstance();
                    quotaDate.setTime(saveModel.getQuotaDate());
                    int thisWeek = quotaDate.get(Calendar.DAY_OF_WEEK);
                    switch (thisWeek){
                        case 1:
                            thisWeek =7;
                            break;
                        case 2:
                            thisWeek =1;
                            break;
                        case 3:
                            thisWeek =2;
                            break;
                        case 4:
                            thisWeek =3;
                            break;
                        case 5:
                            thisWeek =4;
                            break;
                        case 6:
                            thisWeek =5;
                            break;
                        case 7:
                            thisWeek =6;
                            break;
                    }
                    int thisIncre = 7 - thisWeek;
                    quotaDate.add(Calendar.DATE, thisIncre);
                    if(quotaDate.getTime().before(DateUtil.strToDate(endDate, "yyyy-MM-dd"))){
                        range = df.format(quotaDate.getTime());
                    }else {
                        range = df.format(DateUtil.strToDate(endDate, "yyyy-MM-dd"));
                    }

                }
                JSONObject json = countResult.get(range);
//                //因为上述时间集提前一天  但是前端是显示当前时间，所以这里给调整回去
//                if (range.equals(df.format(temp.getTime()))) {
//                    json.put("range", endDate);
//                }
                if (json != null) {
                    long amount = saveModel.getResult2().longValue();
                    double num = saveModel.getResult1();
                    long previousAmount = Long.valueOf(json.get("amount").toString());
                    double previousNum = Double.parseDouble(json.get("num").toString());
                    json.put("amount", amount+previousAmount);
                    json.put("num",decimalFormat.format(num+previousNum));
                }
            }

            List<JSONObject> result = new ArrayList<>(countResult.values());

            // 排序
            result.sort(new Comparator<JSONObject>() {
                @Override
                public int compare(JSONObject o1, JSONObject o2) {
                    if (o1.getString("range").compareTo(o2.getString("range")) > 0) {
                        return 1;
                    } else if (o1.getString("range").compareTo(o2.getString("range")) < 0) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            });
            JSONArray jsonArray = new JSONArray();
            for (JSONObject object:result){
                jsonArray.add(object);
            }

            return jsonArray;
        } else {
            return new JSONArray();
        }
    }
}
