package com.yihu.wlyy.service.app.statistics;

import com.yihu.wlyy.entity.address.Town;
import com.yihu.wlyy.entity.doctor.team.admin.AdminTeam;
import com.yihu.wlyy.entity.organization.Hospital;
import com.yihu.wlyy.entity.statistics.PopulationBase;
import com.yihu.wlyy.repository.address.CityDao;
import com.yihu.wlyy.repository.address.TownDao;
import com.yihu.wlyy.repository.doctor.DoctorAdminTeamDao;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.organization.HospitalDao;
import com.yihu.wlyy.repository.statistics.PopulationBaseDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.util.DateUtil;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by lyr on 2016/08/16.
 */
@Service
public class StatisticsService extends BaseService {
    @Autowired
    CityDao cityDao;
    @Autowired
    TownDao townDao;
    @Autowired
    DoctorDao doctorDao;
    @Autowired
    HospitalDao hospitalDao;
    @Autowired
    DoctorAdminTeamDao adminTeamDao;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    PopulationBaseDao peopleNumDao;
    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 获取上次统计时间
     *
     * @return
     */
    public String getStatisticsTime() {
        String date = DateUtil.dateToStrLong(new Date());

        try {
            date = redisTemplate.opsForValue().get("quota:date");
        }catch (Exception e){
            e.printStackTrace();
        }

        return date;
    }


    /**
     * 获取时间戳
     *
     * @return
     */
    public String getQuotaTimeStamp() {
        return redisTemplate.opsForValue().get("quota:timeKey");
    }

    /**
     * 缓存人口数据到redis
     *
     * @return
     */
    public boolean peopleNumToRedis() {
        List<PopulationBase> peopleNums = peopleNumDao.findByYear(Calendar.getInstance().get(Calendar.YEAR));

        for (PopulationBase peopleNum : peopleNums) {
            redisTemplate.opsForValue().set("people:num:" + peopleNum.getCode(), new JSONObject(peopleNum).toString());
        }

        return true;
    }

    /**
     * 查询截止某个日期累计量
     *
     * @param endDate 截止日期
     * @param area    区域或机构代码
     * @param level   级别
     * @param level2_type   level2_type的类型
     * @return
     */
    public long getTotalAmount(String endDate, String area, int level, String index,String level2_type) {
        int todayAmount = 0;

        // 查询语句
        String sql = " select " +
                "     sum(result) amount" +
                " from  " +
                "     wlyy_quota_result " +
                " where " +
                "     quato_code = '" + index + "' " +
                "   and level1_type = ? and del = '1'" +
                "   and quota_date <= ? ";

        if (level == 4) {
            // 市级别
            sql += " and city = ? ";
        } else if (level == 3) {
            // 区、城镇级别
            sql += " and town = ? ";
        } else if (level == 2) {
            // 机构级别
            sql += " and org_code = ? ";
        } else if (level == 1) {
            sql += " and qkdoctor_code = ?";
        }

        if(StringUtils.isNoneEmpty(level2_type)){
            sql+=" and level2_type = '"+level2_type+"'";
        }

        Map<String, Object> result = jdbcTemplate.queryForMap(sql, new Object[]{level, endDate, area});

        // 截止日期包含当天，则从redis查询当天统计数据
        if (endDate.compareTo(new SimpleDateFormat("yyyy-MM-dd").format(new Date())) >= 0) {
            String val = "";
            try {
                val = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + getQuotaTimeStamp());
            }catch (Exception e){
                e.printStackTrace();
                val = "";
            }
            if (!StringUtils.isEmpty(val)) {
                JSONObject valJson = new JSONObject(val);
                if (valJson.has("num")) {
                    todayAmount = valJson.getInt("num");
                }
            }
        }

        if (result != null) {
            return (result.get("amount") != null ? Math.round(Double.valueOf(result.get("amount").toString())) : 0) + todayAmount;
        } else {
            return 0 + todayAmount;
        }
    }

    /**
     * 获取某个指标在某个期间的增长量
     *
     * @param startDate 起始时间
     * @param endDate   结束时间
     * @param area      区域或机构代码
     * @param level     级别
     * @return
     */
    public long getIntervalIncrement(String startDate, String endDate, String area, int level, String index) {
        int todayAmount = 0;

        // 查询语句
        String sql = " select " +
                "     sum(result) amount" +
                " from  " +
                "     wlyy_quota_result " +
                " where " +
                "     quato_code = '" + index + "' " +
                "   and level1_type = ? and del = '1'" +
                "   and quota_date >= ? " +
                "   and quota_date <= ? ";

        if (level == 4) {
            // 市级别
            sql += " and city = ? ";
        } else if (level == 3) {
            // 区、城镇级别
            sql += " and town = ? ";
        } else if (level == 2) {
            // 机构级别
            sql += " and org_code = ? ";
        } else if (level == 1) {
            sql += " and qkdoctor_code = ?";
        }

        Map<String, Object> result = jdbcTemplate.queryForMap(sql, new Object[]{level, startDate, endDate, area});

        // 截止日期包含当天，则从redis查询当天统计数据
        if (endDate.compareTo(new SimpleDateFormat("yyyy-MM-dd").format(new Date())) >= 0) {
            String val = "";
            try {
                val = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + getQuotaTimeStamp());
            }catch (Exception e){
                e.printStackTrace();
                val = "";
            }
            if (!StringUtils.isEmpty(val)) {
                JSONObject valJson = new JSONObject(val);
                if (valJson.has("num")) {
                    todayAmount = valJson.getInt("num");
                }
            }
        }

        if (result != null) {
            return (result.get("amount") != null ? Math.round(Double.valueOf(result.get("amount").toString())) : 0) + todayAmount;
        } else {
            return 0 + todayAmount;
        }
    }

    /**
     * 查询截止某个日期某个区域后机构各下级指标累计情况
     *
     * @param endDate 截止日期
     * @param area    区域或机构代码
     * @param level   级别
     * @return
     */
    public JSONArray getLowLevelTotalDetail(String endDate, String area, int level, String index, int sort, String lowLevel,String level2_type) throws Exception {
        String areaField = "";
        String lowLevelField = "";
        String lowLevelName = "";

        if (level == 4) {
            // 市级别
            areaField = "city";
            lowLevelField = "town";
            lowLevelName = "town_name";
        } else if (level == 3) {
            // 区、城镇级别
            areaField = "town";
            lowLevelField = "org_code";
            lowLevelName = "org_name";
        } else if (level == 2) {
            // 机构级别
            areaField = "org_code";
            lowLevelField = "qkdoctor_code";
            lowLevelName = "qkdoctor_name";
        } else if (level == 1) {
            throw new Exception("param level error");
        }

        if (!StringUtils.isEmpty(lowLevel)) {
            if (lowLevel.equals("3")) {
                lowLevelField = "town";
                lowLevelName = "town_name";
            } else if (lowLevel.equals("2")) {
                lowLevelField = "org_code";
                lowLevelName = "org_name";
            } else if (lowLevel.equals("1")) {
                lowLevelField = "qkdoctor_code";
                lowLevelName = "qkdoctor_name";
            } else {
                throw new Exception("param lowLevel error");
            }
        }

        String low_level = String.valueOf(StringUtils.isEmpty(lowLevel) ? (level - 1) : lowLevel);

        // 查询语句
        String sql = " select " +
                "     ifnull(" + lowLevelField + ",'') code " +
                "     ,ifnull(" + lowLevelName + ",'') 'name' " +
                "     ,ifnull(sum(result),0.0) amount" +
                " from  " +
                "     wlyy_quota_result " +
                " where " +
                "     quato_code = '" + index + "' " +
                "   and level1_type = ? and del = '1'" +
                "   and quota_date <= ? " +
                "   and " + areaField + " = ? " ;

        if(org.apache.commons.lang3.StringUtils.isNoneEmpty(level2_type)){
            sql+=" and level2_type = '"+level2_type+"'";
        }

        sql+=   " group by " + lowLevelField + "," + lowLevelName;

        if (sort == 1) {
            sql += " order by amount desc";
        } else {
            sql += " order by amount asc ";
        }

        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(sql, new Object[]{low_level, endDate, area});

        // 结果为空时,自建结果集
        if (resultList == null || resultList.size() < 1) {
            resultList = new ArrayList<>();
            if (low_level.equals("3")) {
                List<Town> towns = townDao.findByCityCode(area);
                if (towns != null) {
                    for (Town town : towns) {
                        Map<String, Object> obj = new HashMap<>();
                        obj.put("code", town.getCode());
                        obj.put("name", town.getName());
                        obj.put("amount", "0");
                        obj.put("rate", Double.valueOf("0.0000"));
                        obj.put("rateString", "0/0");
                        resultList.add(obj);
                    }
                }
            } else if (low_level.equals("2")) {
                List<Town> towns = new ArrayList<>();
                if (level == 4) {
                    towns = townDao.findByCityCode(area);
                } else if (level == 3) {
                    Town town = townDao.findByCode(area);
                    towns.add(town);
                }

                if (towns != null && towns.size() > 0) {
                    for (Town town : towns) {
                        List<Hospital> hospitals = hospitalDao.findByTownCode(town.getCode());

                        for (Hospital hos : hospitals) {
                            Map<String, Object> obj = new HashMap<>();
                            obj.put("code", hos.getCode());
                            obj.put("name", hos.getName());
                            obj.put("amount", "0");
                            resultList.add(obj);
                        }
                    }
                }
            } else if (low_level.equals("1")) {
                List<Hospital> hospitals = new ArrayList<>();
                if (level == 4) {
                    hospitals = hospitalDao.findByCity(area);
                } else if (level == 3) {
                    hospitals = hospitalDao.findByTownCode(area);
                } else {
                    Hospital hos = hospitalDao.findByCode(area);
                    if (hos != null) {
                        hospitals.add(hos);
                    }
                }

                if (hospitals != null && hospitals.size() > 0) {
                    for (Hospital hos : hospitals) {
                        List<AdminTeam> teams = adminTeamDao.findByOrgCode(hos.getCode());

                        for (AdminTeam team : teams) {
                            Map<String, Object> obj = new HashMap<>();
                            obj.put("code", String.valueOf(team.getId()));
                            obj.put("name", team.getName());
                            obj.put("amount", "0");
                            resultList.add(obj);
                        }
                    }
                }
            }
        }

        if (resultList != null) {
            DecimalFormat df = new DecimalFormat("0.0000");
            for (Map<String, Object> map : resultList) {
                map.put("amount", map.get("amount") != null ? Math.round(Double.valueOf(map.get("amount").toString())) : 0);
                // 截止日期包含当天，则从redis查询当天统计数据
                if (endDate.compareTo(new SimpleDateFormat("yyyy-MM-dd").format(new Date())) >= 0) {
                    String code = map.get("code") != null ? String.valueOf(map.get("code")) : "";
                    String val = "";
                    try {
                        val = redisTemplate.opsForValue().get("quota:" + index + ":" + low_level + ":" + code + ":" + getQuotaTimeStamp());
                    }catch (Exception e){
                        e.printStackTrace();
                        val = "";
                    }
                    if (!StringUtils.isEmpty(val)) {
                        JSONObject valJson = new JSONObject(val);
                        if (valJson.has("num")) {
                            map.put("amount", (long) map.get("amount") + valJson.getInt("num"));
                        }
                    }
                }

                if (!low_level.equals("1")) {
                    String redisNum = "";
                    try {
                        redisNum = redisTemplate.opsForValue().get("people:num:" + map.get("code").toString());
                    }catch (Exception e){
                        redisNum = "";
                    }
                    if (StringUtils.isEmpty(redisNum)) {
                        PopulationBase peopleNum = peopleNumDao.findByCodeAndYear(map.get("code").toString(), Calendar.getInstance().get(Calendar.YEAR));
                        if (peopleNum != null) {
                            map.put("rate", df.format(((long) map.get("amount") * 1.0000) / peopleNum.getNum() * 100));
                            map.put("rateString",map.get("amount")+"/"+peopleNum.getNum());
                        }
                    } else {
                        JSONObject peopleNum = new JSONObject(redisNum);
                        if (peopleNum != null) {
                            map.put("rate", df.format(((long) map.get("amount") * 1.0000) / peopleNum.getInt("num") * 100));
                            map.put("rateString",map.get("amount")+"/"+ peopleNum.getInt("num"));
                        }
                    }
                }
            }

            Collections.sort(resultList, new Comparator<Map<String, Object>>() {
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    long map1value = (long) o1.get("amount");
                    long map2value = (long) o2.get("amount");

                    if (map1value - map2value > 0) {
                        return sort == 1 ? -1 : 1;
                    } else if (map1value - map2value < 0) {
                        return sort == 1 ? 1 : -1;
                    } else {
                        return 0;
                    }
                }
            });

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

    /**
     * 查询某个日期范围内某个区域或机构各下级指标增量情况
     *
     * @param startDate 起始日期
     * @param endDate   结束日期
     * @param area      区域或机构代码
     * @param level     级别
     * @param index     指标
     * @return
     */
    public JSONArray getLowLevelIncrementDetail(String startDate, String endDate, String area, int level, String index, int sort, String lowLevel) throws Exception {
        String areaField = "";
        String lowLevelField = "";
        String lowLevelName = "";

        if (level == 4) {
            // 市级别
            areaField = "city";
            lowLevelField = "town";
            lowLevelName = "town_name";
        } else if (level == 3) {
            // 区、城镇级别
            areaField = "town";
            lowLevelField = "org_code";
            lowLevelName = "org_name";
        } else if (level == 2) {
            // 机构级别
            areaField = "org_code";
            lowLevelField = "qkdoctor_code";
            lowLevelName = "qkdoctor_name";
        } else if (level == 1) {
            throw new Exception("param level error");
        }

        if (!StringUtils.isEmpty(lowLevel)) {
            if (lowLevel.equals("3")) {
                lowLevelField = "town";
                lowLevelName = "town_name";
            } else if (lowLevel.equals("2")) {
                lowLevelField = "org_code";
                lowLevelName = "org_name";
            } else if (lowLevel.equals("1")) {
                lowLevelField = "qkdoctor_code";
                lowLevelName = "qkdoctor_name";
            } else {
                throw new Exception("param lowLevel error");
            }
        }

        String low_level = String.valueOf(StringUtils.isEmpty(lowLevel) ? (level - 1) : lowLevel);

        // 查询语句
        String sql = " select " +
                "     ifnull(" + lowLevelField + ",'') code " +
                "     ,ifnull(" + lowLevelName + ",'') 'name' " +
                "     ,ifnull(sum(result),0.0) amount" +
                " from  " +
                "     wlyy_quota_result " +
                " where " +
                "     quato_code = '" + index + "' " +
                "   and level1_type = ? and del = '1'" +
                "   and quota_date >= ? " +
                "   and quota_date <= ? " +
                "   and " + areaField + " = ? " +
                " group by " + lowLevelField + "," + lowLevelName;

        if (sort == 1) {
            sql += " order by amount desc";
        } else {
            sql += " order by amount asc ";
        }

        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(sql, new Object[]{low_level, startDate, endDate, area});

        // 结果为空时,自建结果集
        if (resultList == null || resultList.size() < 1) {
            resultList = new ArrayList<>();
            if (low_level.equals("3")) {
                List<Town> towns = townDao.findByCityCode(area);
                if (towns != null) {
                    for (Town town : towns) {
                        Map<String, Object> obj = new HashMap<>();
                        obj.put("code", town.getCode());
                        obj.put("name", town.getName());
                        obj.put("amount", "0");
                        obj.put("rate", Double.valueOf("0.0000"));
                        resultList.add(obj);
                    }
                }
            } else if (low_level.equals("2")) {
                List<Town> towns = new ArrayList<>();
                if (level == 4) {
                    towns = townDao.findByCityCode(area);
                } else if (level == 3) {
                    Town town = townDao.findByCode(area);
                    towns.add(town);
                }

                if (towns != null && towns.size() > 0) {
                    for (Town town : towns) {
                        List<Hospital> hospitals = hospitalDao.findByTownCode(town.getCode());

                        for (Hospital hos : hospitals) {
                            Map<String, Object> obj = new HashMap<>();
                            obj.put("code", hos.getCode());
                            obj.put("name", hos.getName());
                            obj.put("amount", "0");
                            resultList.add(obj);
                        }
                    }
                }
            } else if (low_level.equals("1")) {
                List<Hospital> hospitals = new ArrayList<>();
                if (level == 4) {
                    hospitals = hospitalDao.findByCity(area);
                } else if (level == 3) {
                    hospitals = hospitalDao.findByTownCode(area);
                } else {
                    Hospital hos = hospitalDao.findByCode(area);
                    if (hos != null) {
                        hospitals.add(hos);
                    }
                }

                if (hospitals != null && hospitals.size() > 0) {
                    for (Hospital hos : hospitals) {
                        List<AdminTeam> teams = adminTeamDao.findByOrgCode(hos.getCode());

                        for (AdminTeam team : teams) {
                            Map<String, Object> obj = new HashMap<>();
                            obj.put("code", String.valueOf(team.getId()));
                            obj.put("name", team.getName());
                            obj.put("amount", "0");
                            resultList.add(obj);
                        }
                    }
                }
            }
        }

        if (resultList != null) {
            for (Map<String, Object> map : resultList) {
                map.put("amount", map.get("amount") != null ? Math.round(Double.valueOf(map.get("amount").toString())) : 0);
                // 截止日期包含当天，则从redis查询当天统计数据
                if (endDate.compareTo(new SimpleDateFormat("yyyy-MM-dd").format(new Date())) >= 0) {
                    String code = map.get("code") != null ? String.valueOf(map.get("code")) : "";
                    String val = "";
                    try {
                        val = redisTemplate.opsForValue().get("quota:" + index + ":" + low_level + ":" + code + ":" + getQuotaTimeStamp());
                    }catch (Exception e){
                        e.printStackTrace();
                        val = "";
                    }
                    if (!StringUtils.isEmpty(val)) {
                        JSONObject valJson = new JSONObject(val);
                        if (valJson.has("num")) {
                            map.put("amount", (long) map.get("amount") + valJson.getInt("num"));
                        }
                    }
                }
            }

            Collections.sort(resultList, new Comparator<Map<String, Object>>() {
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    long map1value = (long) o1.get("amount");
                    long map2value = (long) o2.get("amount");

                    if (map1value - map2value > 0) {
                        return sort == 1 ? -1 : 1;
                    } else if (map1value - map2value < 0) {
                        return sort == 1 ? 1 : -1;
                    } else {
                        return 0;
                    }
                }
            });

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

    /**
     * 获取时间范围内按间隔统计指标增量
     *
     * @param startDate 起始时间
     * @param endDate   结束时间
     * @param interval  时间间隔
     * @param area      区域或机构代码
     * @param level     级别
     * @param index     指标
     * @return
     */
    public JSONArray getDateIncrementDetail(String startDate, String endDate, int interval, String area, int level, String index,String level2_type) throws Exception {
        if (interval == 1) {
            return dateStatistics(startDate, endDate, area, level, index,level2_type);
        } else if (interval == 2) {
            return weekStatistics(startDate, endDate, area, level, index,level2_type);
        } else if (interval == 3) {
            return monthStatistics(startDate, endDate, area, level, index,level2_type);
        }

        return new JSONArray();
    }

    /**
     * 按日统计
     *
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @return
     */
    private JSONArray dateStatistics(String startDate, String endDate, String area, int level, String index,String level2_type) {
        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String areaField = "";
        String sql = "";

        if (level == 4) {
            // 市级别
            areaField = "city";
        } else if (level == 3) {
            // 区、城镇级别
            areaField = "town";
        } else if (level == 2) {
            // 机构级别
            areaField = "org_code";
        } else if (level == 1) {
            // 机构级别
            areaField = "qkdoctor_code";
        }

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        // 起始日期
        Calendar start = Calendar.getInstance();
        start.setTime(DateUtil.strToDate(startDate, DateUtil.YYYY_MM_DD));
        //结束日期
        Calendar end = Calendar.getInstance();
        end.setTime(DateUtil.strToDate(endDate, DateUtil.YYYY_MM_DD));
        // 日期集合
        List<Calendar> days = new ArrayList<>();
        days.add(start);

        boolean flag = true;

        if (startDate.compareTo(endDate) == 0) {
            flag = false;
        }
        // 计算统计日期
        while (flag) {
            Calendar next = Calendar.getInstance();
            next.setTime(days.get(days.size() - 1).getTime());
            next.add(Calendar.DATE, 1);
            if (df.format(next.getTime()).compareTo(endDate) < 0) {
                days.add(next);
            } else {
                days.add(end);
                flag = false;
            }
        }

        Map<String, JSONObject> countResult = new HashMap<>();

        // 统计预计构建
        for (int i = 0; i < days.size(); i++) {
            String startStr = "";
            long amount = 0;

            startStr = df.format(days.get(i).getTime());

            // 当前范围包含当天，则需添加当天的统计数据
            if (startStr.compareTo(today) == 0) {
                String val = "";
                try {
                    val = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + getQuotaTimeStamp());
                }catch (Exception e){
                    e.printStackTrace();
                    val = "";
                }
                if (!StringUtils.isEmpty(val)) {
                    JSONObject valJson = new JSONObject(val);
                    if (valJson.has("num")) {
                        amount = (long) valJson.getInt("num");
                    }
                }
            }

            JSONObject range = new JSONObject();
            range.put("range", startStr);
            range.put("amount", amount);
            countResult.put(startStr, range);
        }

        sql = " select " +
                "     ifnull(quota_date,'') as 'range' " +
                "     ,ifnull(sum(result),0.0) amount " +
                " from  " +
                "     wlyy_quota_result " +
                " where " +
                "     quato_code = '" + index + "' " +
                "   and level1_type = '" + level + "' and del = '1' " +
                "   and quota_date >= '" + startDate + "' " +
                "   and quota_date <= '" + endDate + "' " +
                "   and " + areaField + " = '" + area + "' " ;
                if(StringUtils.isNotBlank(level2_type)){
                     sql=sql + " and level2_type ='"+level2_type+"' ";
                }
                sql=sql + "   group by quota_date ";


        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(sql);

        if (resultList != null) {
            for (Map<String, Object> map : resultList) {
                if (countResult.containsKey(map.get("range").toString())) {
                    JSONObject range = (JSONObject) countResult.get(map.get("range").toString());
                    long amount = range.getLong("amount");
                    long resultAmount = map.get("amount") != null ? Math.round(Double.valueOf(map.get("amount").toString())) : 0;
                    range.put("amount", amount + resultAmount);
                }
            }

            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;
                    }
                }
            });

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

    /**
     * 按周统计
     *
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @return
     */
    private JSONArray weekStatistics(String startDate, String endDate, String area, int level, String index,String level2_type) throws Exception {
        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String areaField = "";
        String sql = "";

        if (level == 4) {
            // 市级别
            areaField = "city";
        } else if (level == 3) {
            // 区、城镇级别
            areaField = "town";
        } else if (level == 2) {
            // 机构级别
            areaField = "org_code";
        } else if (level == 1) {
            // 机构级别
            areaField = "qkdoctor_code";
        }

        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();
        end.setTime(DateUtil.strToDate(endDate, DateUtil.YYYY_MM_DD));
        // 起始日期为周几
        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 (df.format(next.getTime()).compareTo(df.format(end.getTime())) < 0) {
                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<>();

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

            // 起始、截止日期
            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());
            }

            // 当前范围包含当天，则需添加当天的统计数据
            if (startStr.compareTo(today) <= 0 && endStr.compareTo(today) >= 0) {
                String val = "";
                try {
                    val = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + getQuotaTimeStamp());
                }catch (Exception e){
                    e.printStackTrace();
                    val = "";
                }
                if (!StringUtils.isEmpty(val)) {
                    JSONObject valJson = new JSONObject(val);
                    if (valJson.has("num")) {
                        amount = valJson.getInt("num");
                    }
                }
            }

            JSONObject range = new JSONObject();

            range.put("range", startStr);
            range.put("amount", amount);

            countResult.put(startStr + ":" + endStr, range);
        }

        // 查询时间范围内所有记录
        sql = " select " +
                "     ifnull(quota_date,'') as 'range' " +
                "     ,ifnull(sum(result),0.0) amount " +
                " from  " +
                "     wlyy_quota_result " +
                " where " +
                "     quato_code = '" + index + "' " +
                "   and level1_type = '" + level + "' and del = '1' " +
                "   and quota_date >= '" + startDate + "' " +
                "   and quota_date <= '" + endDate + "' " +
                "   and " + areaField + " = '" + area + "' " ;
                if(StringUtils.isNotBlank(level2_type)){
                    sql=sql + " and level2_type ='"+level2_type+"' ";
                }
                sql=sql + "   group by quota_date ";


        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(sql);

        if (resultList != null) {
            // 计算结果
            for (Map<String, Object> map : resultList) {
                long resultAmount = map.get("amount") != null ? Math.round(Double.valueOf(map.get("amount").toString())) : 0;
                String range = map.get("range").toString();

                if (org.apache.commons.lang3.StringUtils.isNotEmpty(range)) {
                    // 起始日期
                    String startStr = "";
                    // 结束日期
                    String endStr = "";

                    if (range.compareTo(startDate) >= 0 && range.compareTo(firstEnd) <= 0) {
                        startStr = startDate;
                        endStr = firstEnd;
                    } else {
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(df.parse(range));
                        int calWeek = cal.get(Calendar.DAY_OF_WEEK) - 2;

                        if (calWeek == -1) {
                            cal.add(Calendar.DATE, -6);
                        } else {
                            cal.add(Calendar.DATE, -calWeek);
                        }

                        startStr = df.format(cal.getTime());
                        cal.add(Calendar.DATE, 6);
                        endStr = df.format(cal.getTime());

                        if (endStr.compareTo(endDate) > 0) {
                            endStr = endDate;
                        }
                    }

                    JSONObject json = countResult.get(startStr + ":" + endStr);
                    json.put("amount", json.getLong("amount") + resultAmount);
                }
            }

            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;
                    }
                }
            });

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

    /**
     * 按月统计
     *
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @return
     * @throws Exception
     */
    private JSONArray monthStatistics(String startDate, String endDate, String area, int level, String index,String level2_type) throws Exception {
        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String areaField = "";
        String sql = "";

        if (level == 4) {
            // 市级别
            areaField = "city";
        } else if (level == 3) {
            // 区、城镇级别
            areaField = "town";
        } else if (level == 2) {
            // 机构级别
            areaField = "org_code";
        } else if (level == 1) {
            // 机构级别
            areaField = "qkdoctor_code";
        }

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        // 起始日期
        Calendar start = Calendar.getInstance();
        start.setTime(DateUtil.strToDate(startDate, DateUtil.YYYY_MM_DD));
        // 结束日期
        Calendar end = Calendar.getInstance();
        end.setTime(DateUtil.strToDate(endDate, DateUtil.YYYY_MM_DD));
        // 第一个结束日期
        String firstEnd = "";

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

        boolean flag = true;
        int k = 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 (k == 0) {
                next.add(Calendar.MONTH, 1);
            } else {
                next.add(Calendar.MONTH, 2);
            }
            next.set(Calendar.DAY_OF_MONTH, 1);
            next.add(Calendar.DAY_OF_MONTH, -1);

            if (df.format(next.getTime()).compareTo(df.format(end.getTime())) < 0) {
                days.add(next);
                if (k == 0) {
                    firstEnd = df.format(next.getTime());
                }
            } else {
                days.add(end);
                flag = false;
                if (k == 0) {
                    firstEnd = df.format(end.getTime());
                }
            }
            k++;
        }

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

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

            // 起始时间计算
            if (i == 0) {
                startStr = df.format(days.get(i).getTime());
            } else {
                Calendar cal = Calendar.getInstance();
                cal.setTime(days.get(i).getTime());
                cal.add(Calendar.DATE, 1);
                startStr = df.format(cal.getTime());
            }

            // 当天数据计算
            if (startStr.compareTo(today) <= 0 && endStr.compareTo(today) >= 0) {
                String val = "";
                try {
                    val = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + getQuotaTimeStamp());
                }catch (Exception e){
                    e.printStackTrace();
                    val = "";
                }
                if (!StringUtils.isEmpty(val)) {
                    JSONObject valJson = new JSONObject(val);
                    if (valJson.has("num")) {
                        amount = valJson.getInt("num");
                    }
                }
            }

            JSONObject range = new JSONObject();

            range.put("range", startStr);
            range.put("amount", amount);

            countResult.put(startStr + ":" + endStr, range);
        }

        // 查询时间范围内所有记录
        sql = " select " +
                "     ifnull(quota_date,'') as 'range' " +
                "     ,ifnull(sum(result),0.0) amount " +
                " from  " +
                "     wlyy_quota_result " +
                " where " +
                "     quato_code = '" + index + "' " +
                "   and level1_type = '" + level + "' and del = '1' " +
                "   and quota_date >= '" + startDate + "' " +
                "   and quota_date <= '" + endDate + "' " +
                "   and " + areaField + " = '" + area + "' ";
                if(StringUtils.isNotBlank(level2_type)){
                    sql=sql + " and level2_type ='"+level2_type+"' ";
                }
                sql=sql + "   group by quota_date ";

        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(sql);

        if (resultList != null) {
            // 计算结果
            for (Map<String, Object> map : resultList) {
                long resultAmount = map.get("amount") != null ? Math.round(Double.valueOf(map.get("amount").toString())) : 0;
                String range = map.get("range").toString();

                if (org.apache.commons.lang3.StringUtils.isNotEmpty(range)) {
                    // 起始日期
                    String startStr = "";
                    // 结束日期
                    String endStr = "";

                    if (range.compareTo(startDate) >= 0 && range.compareTo(firstEnd) <= 0) {
                        startStr = startDate;
                        endStr = firstEnd;
                    } else {
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(df.parse(range));
                        cal.set(Calendar.DATE, 1);

                        startStr = df.format(cal.getTime());
                        cal.add(Calendar.MONTH, 1);
                        cal.set(Calendar.DATE, 1);
                        cal.add(Calendar.DATE, -1);
                        endStr = df.format(cal.getTime());

                        if (endStr.compareTo(endDate) > 0) {
                            endStr = endDate;
                        }
                    }

                    JSONObject json = countResult.get(startStr + ":" + endStr);
                    json.put("amount", json.getLong("amount") + resultAmount);
                }
            }

            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;
                    }
                }
            });

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

    /**
     * 统计回复和未回复
     * @param level
     * @param code
     * @return
     * @throws Exception
     */
    public JSONObject getConsultingStatistics(int level ,String code)throws Exception{

        //获取总数
        String sqlTotal =  getConsultingStatisticsSQL(level,code,1);
        //获取已经回复
        String sqlReply =  getConsultingStatisticsSQL(level,code,2);
        //获取未回复
        String sqlnoReply =  getConsultingStatisticsSQL(level,code,3);

        JSONObject result = new JSONObject();

        Long total =  jdbcTemplate.queryForObject(sqlTotal,Long.class);
        Long reply =  jdbcTemplate.queryForObject(sqlReply,Long.class);
        Long noReply =  jdbcTemplate.queryForObject(sqlnoReply,Long.class);

        if(total == null||total == 0){
            result.put("total","0");
            result.put("replyCount","0");
            result.put("noReplyCount","0");
            result.put("replyRatio","0.00%");
            result.put("noReplyRatio","0.00%");
        }else{
            double rr = (double)reply/total*100;
            double nrr = (double)noReply/total*100;
            DecimalFormat df  = new DecimalFormat("###.00");

            result.put("total",total);
            result.put("replyCount",reply);
            result.put("noReplyCount",noReply);
            if(reply==0){
                result.put("replyRatio","0.00%");
            }else{
                result.put("replyRatio",df.format(rr)+"%");
            }
            if(noReply==0){
                result.put("noReplyRatio","0.00%");
            }else{
                result.put("noReplyRatio",df.format(nrr)+"%");
            }
        }
        return result;
    }

    public String getConsultingStatisticsSQL(int level,String code,int type){

        StringBuffer sql = new StringBuffer("SELECT count(1) " +
                "FROM ichat.topics t,ichat.participants p," +
                "(SELECT d1. CODE FROM " +
                " wlyy_admin_team t1," +
                " wlyy_admin_team_member m1," +
                " wlyy_doctor d1 " +
                " WHERE t1.id = m1.team_id AND d1.CODE = m1.doctor_code ");
        if (level == 4) {
            // 市级别
            sql.append(" AND d1.city = "+code);
        } else if (level == 3) {
            // 区、城镇级别
            sql.append(" AND d1.town = "+code);
        } else if (level == 2) {
            // 机构级别
            sql.append(" AND d1.hospital = "+code);
        } else if (level == 1) {
            // 机构团队级别
            sql.append(" AND t1.id = "+code);
        }
        sql.append(" GROUP BY T1.`name`,d1. CODE) dt " +
                "WHERE p.participant_id = dt.`CODE` AND p.session_id = t.session_id " +
                "AND t.create_time >= DATE_SUB(NOW(),INTERVAL -1 DAY) ");

        if(type == 1){
            //计算总数
        }else if(type == 2){
            //计算及时回复
            sql.append(" AND t.reply = 1 ");
        }else if(type == 3 ){
            //计算未回复
            sql.append(" AND t.reply = 0 ");
        }
        return sql.toString();
    }

    /**
     * 统计微信绑定率
     * @return
     */
    public JSONObject getBindingRate(){
        JSONObject result = new JSONObject();
        Long bindCout = jdbcTemplate.queryForObject(getBindingCountSQL(),Long.class);
        Long signCout = jdbcTemplate.queryForObject(getSignCountSQL(),Long.class);

        if((bindCout != null || bindCout != 0) && (signCout != null&&signCout != 0)){
            double rate = (double)bindCout/signCout*100;
            DecimalFormat df  = new DecimalFormat("###.00");
            result.put("bindRate",df.format(rate)+"%");
        }else{
            result.put("bindRate","0.00%");
        }
        return result;
    }

    /**
     * 获取绑定人数SQL
     * @return
     */
    public String getBindingCountSQL(){
        StringBuffer sql = new StringBuffer("SELECT COUNT(1) FROM wlyy_patient t WHERE t.openid IS NOT NULL");
        return sql.toString();
    }

    /**
     * 获取签约数SQL
     eturn
     */
    public String getSignCountSQL(){
        StringBuffer sql = new StringBuffer("SELECT COUNT(1) FROM wlyy_sign_family f WHERE f.type='2' AND f.`status`>0 AND f.expenses_status='1' ");
        return sql.toString();
    }

    /**
     * 统计回复和未回复
     * @param level
     * @return
     * @throws Exception
     */
    public JSONObject getConsultingStatisticsList(int level,String area,String lowLevel)throws Exception{

        JSONObject result = new JSONObject();

        //级别为市级,统计区级统计区和机构
        if(level == 4){

            if(StringUtils.isBlank(lowLevel)){
                String timeKey = redisTemplate.opsForValue().get("quota:timeKey");
                if(StringUtils.isBlank(timeKey)){
                    return null;
                }
                //及时回复数

                String relyVal = redisTemplate.opsForValue().get("quota:23:"+level+":"+area+":3:"+timeKey);
                if(StringUtils.isBlank(relyVal)){
                    return null;
                }
                JSONArray rely = new JSONArray(relyVal);

                //咨询总数
                String relyTotal = redisTemplate.opsForValue().get("quota:25:"+level+":"+area+":3:"+timeKey);
                if(StringUtils.isBlank(relyTotal)){
                    return null;
                }
                JSONArray total = new JSONArray(relyTotal);

                //未回复数
                String onRelyTotal = redisTemplate.opsForValue().get("quota:22:"+level+":"+area+":3:"+timeKey);
                if(StringUtils.isBlank(onRelyTotal)){
                    return null;
                }
                JSONArray onRely = new JSONArray(onRelyTotal);

                result.put("resultList",getCoutList(rely,total,onRely));
            }else{
                String timeKey = redisTemplate.opsForValue().get("quota:timeKey");
                if(StringUtils.isBlank(timeKey)){
                    return null;
                }
                //及时回复数

                String relyVal = redisTemplate.opsForValue().get("quota:23:"+level+":"+area+":2:"+timeKey);
                if(StringUtils.isBlank(relyVal)){
                    return null;
                }
                JSONArray rely = new JSONArray(relyVal);

                //咨询总数
                String relyTotal = redisTemplate.opsForValue().get("quota:25:"+level+":"+area+":2:"+timeKey);
                if(StringUtils.isBlank(relyTotal)){
                    return null;
                }
                JSONArray total = new JSONArray(relyTotal);

                //未回复数
                String onRelyTotal = redisTemplate.opsForValue().get("quota:22:"+level+":"+area+":2:"+timeKey);
                if(StringUtils.isBlank(onRelyTotal)){
                    return null;
                }
                JSONArray onRely = new JSONArray(onRelyTotal);

                result.put("resultList",getCoutList(rely,total,onRely));
            }


        }else if(level == 3){//区级底下的机构

            //quota:23:4:350200:2:1492939333191

            String timeKey = redisTemplate.opsForValue().get("quota:timeKey");
            if(StringUtils.isBlank(timeKey)){
                return null;
            }
            //及时回复数

            String relyVal = redisTemplate.opsForValue().get("quota:23:"+level+":"+area+":2:"+timeKey);
            if(StringUtils.isBlank(relyVal)){
                return null;
            }
            JSONArray rely = new JSONArray(relyVal);

            //咨询总数
            String relyTotal = redisTemplate.opsForValue().get("quota:25:"+level+":"+area+":2:"+timeKey);
            if(StringUtils.isBlank(relyTotal)){
                return null;
            }
            JSONArray total = new JSONArray(relyTotal);

            //未回复数
            String noRelyTotal = redisTemplate.opsForValue().get("quota:22:"+level+":"+area+":2:"+timeKey);
            if(StringUtils.isBlank(noRelyTotal)){
                return null;
            }
            JSONArray noRely = new JSONArray(noRelyTotal);
            result.put("resultList",getCoutList(rely,total,noRely));

        }else if(level == 2){//机构级别统计,统计所有团队

            //quota:23:4:350200:2:1492939333191

            String timeKey = redisTemplate.opsForValue().get("quota:timeKey");
            if(StringUtils.isBlank(timeKey)){
                return null;
            }
            //及时回复数

            String relyVal = redisTemplate.opsForValue().get("quota:23:"+level+":"+area+":1:"+timeKey);
            if(StringUtils.isBlank(relyVal)){
                return null;
            }
            JSONArray rely = new JSONArray(relyVal);

            //咨询总数
            String relyTotal = redisTemplate.opsForValue().get("quota:25:"+level+":"+area+":1:"+timeKey);
            if(StringUtils.isBlank(relyTotal)){
                return null;
            }
            JSONArray total = new JSONArray(relyTotal);

            //未回复数
            String noRelyTotal = redisTemplate.opsForValue().get("quota:22:"+level+":"+area+":1:"+timeKey);
            if(StringUtils.isBlank(noRelyTotal)){
                return null;
            }
            JSONArray noRely = new JSONArray(noRelyTotal);

            result.put("resultList",getCoutList(rely,total,noRely));
        }
        return result;
    }


    /**
     *  统计当前级别下数据
     * @param level
     * @param area
     * @return
     */
    public JSONObject getConsultingTitle(int level,String area){

        JSONObject result = new JSONObject();

        String timeKey = redisTemplate.opsForValue().get("quota:timeKey");
        if(StringUtils.isBlank(timeKey)){
            return null;
        }
        //及时回复数

        String relyVal = redisTemplate.opsForValue().get("quota:23:"+level+":"+area+":"+timeKey);
        if(StringUtils.isBlank(relyVal)){
            return null;
        }
        JSONObject relyObject =new JSONObject(relyVal);
        JSONArray rely = new JSONArray();
        rely.put(relyObject);
        //咨询总数
        String relyTotal = redisTemplate.opsForValue().get("quota:25:"+level+":"+area+":"+timeKey);
        if(StringUtils.isBlank(relyTotal)){
            return null;
        }
        JSONObject totalObject =new JSONObject(relyTotal);
        JSONArray total = new JSONArray();
        total.put(totalObject);
        //未回复数
        String onRelyTotal = redisTemplate.opsForValue().get("quota:22:"+level+":"+area+":"+timeKey);
        if(StringUtils.isBlank(onRelyTotal)){
            return null;
        }
        JSONObject onRelyObject =new JSONObject(onRelyTotal);
        JSONArray onRely = new JSONArray();
        onRely.put(onRelyObject);

        result.put("result",getCoutList(rely,total,onRely));

        return result;
    }

    /**
     * 统计
     * 根据总数,未回复数,回复数统计,合并结果集及排序
     * @param rely
     * @param total
     * @param onRely
     * @return
     */
    public List<Map<String,Object>> getCoutList(JSONArray rely,JSONArray total,JSONArray onRely){

        Map<String,Object> relyMap = new HashMap<>();
        Map<String,Object> totalMap = new HashMap<>();
        Map<String,Object> onRelyMap = new HashMap<>();

        //将List转换为Map,Key为要比较的CODE,降低循环层数
        //转换回复数
        Iterator iterator =  rely.iterator();
        while(iterator.hasNext()){
            JSONObject jsonObject = (JSONObject)iterator.next();
            relyMap.put(jsonObject.get("code").toString(),jsonObject);
        }
        //转换总咨询数
        Iterator iterator2 =  total.iterator();
        while(iterator2.hasNext()){
            JSONObject jsonObject = (JSONObject)iterator2.next();
            totalMap.put(jsonObject.get("code").toString(),jsonObject);
        }

        //转换总咨询数
        Iterator iterator3 =  onRely.iterator();
        while(iterator3.hasNext()){
            JSONObject jsonObject = (JSONObject)iterator3.next();
            onRelyMap.put(jsonObject.get("code").toString(),jsonObject);
        }

        List<Map<String,Object>> resultMaps = new ArrayList<>();
        for(String key : totalMap.keySet()){
            Map<String,Object> rs = new HashMap<>();
            JSONObject relyRs = (JSONObject)relyMap.get(key);
            JSONObject totalRs = (JSONObject)totalMap.get(key);
            JSONObject onRelyRs = (JSONObject)onRelyMap.get(key);
            //合并结果集
            Long totalNm = totalRs.getLong("num");
            Long relyNm = relyRs.getLong("num");
            Long noRelyNm = onRelyRs.getLong("num");
            rs.put("name",relyRs.get("name"));
            rs.put("noRelyCount",noRelyNm);
            rs.put("relyCount",relyNm);
            rs.put("total",totalNm);
            rs.put("code",key);
            if(totalNm !=null&&totalNm!=0){
                if(relyNm!=null&&relyNm!=0){
                    double rr = (double)relyNm/totalNm*100;
                    DecimalFormat df  = new DecimalFormat("0.00");
                    rs.put("relyRate",df.format(rr)+"%");
                    rs.put("relyDoubleRate",rr);
                }else{
                    rs.put("relyRate","0.00%");
                    rs.put("relyDoubleRate",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("relyRate","0.00%");
                rs.put("relyDoubleRate",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  (double)o1.get("noRelyDoubleRate")<(double)o2.get("noRelyDoubleRate")?1:( (double)o1.get("noRelyDoubleRate")==(double)o2.get("noRelyDoubleRate")?0:-1);
            }
        });

        return resultMaps;
    }

    /**
     * 获取及时回复的时间分布
     * @param level
     * @param area
     * @return
     */
    public JSONObject getCoutListByTime(String level,String area){
        JSONObject result = new JSONObject();

        if(StringUtils.isNotBlank(level)&&StringUtils.isNotBlank(area)){
            String timeKey = redisTemplate.opsForValue().get("quota:timeKey");
            String relyVal = redisTemplate.opsForValue().get("quota:24:"+level+":"+area+":"+timeKey);
            JSONArray array = new JSONArray(relyVal);
            result.put("resultList",array);
        }
        return result;
    }
}
