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.service.app.team.AdminTeamService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.MapListUtils;
import com.yihu.wlyy.util.SystemConf;
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.jdbc.support.nativejdbc.OracleJdbc4NativeJdbcExtractor;
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;
    @Autowired
    private StatisticsAllService statisticsAllService;


    /**
     * 获取上次统计时间
     *
     * @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;更具名称group by会有问题

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

            if (level==2){
                statisticsAllService.translateTeamLeaderName(resultList);
            }

            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; 加上名称group by会影响下面流程 团队如果改名字 数据会被覆盖

        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);
            List<Map<String,Object>> rs = getCoutList(rely,total,noRely);
            statisticsAllService.translateTeamLeaderName(rs);
            result.put("resultList",rs);
        }
        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;
    }

    public JSONObject getAVGSocre(String level,String area){

        String sql = "SELECT ROUND(AVG(s.score),1) avgCount FROM wlyy_evaluate_score s ,wlyy_doctor d WHERE s.doctor = d.code ";
        //市级
        if("4".equals(level)){
            sql +=" AND d.city = ? ";
        //区级
        }else if("3".equals(level)){
            sql +=" AND d.town = ? ";
        //机构
        }else if("2".equals(level)){
            sql +=" AND d.hospital = ? ";
        }

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

        JSONObject json = new JSONObject();

        json.put("rs",rs);

        return json;
    }

    public JSONArray getAVGSocreByMonth(String level ,String area,String statDate,String endDate)throws  Exception{

        List<String> times =  getMonthBetween(statDate,endDate);
        if(times==null||times.size()==0){
            throw new Exception("时间区间错误");
        }

        String sql = "SELECT DATE_FORMAT(t.czrq,'%Y-%m') mt,ifnull(ROUND(AVG(s.score),1),0)  as avgCount " +
                " FROM  wlyy_consult_team t " +
                "  LEFT JOIN wlyy_doctor d ON d.code = t.doctor" +
                "  LEFT JOIN wlyy_evaluate_score s ON s.doctor = t.doctor" +
                " WHERE t.czrq >=? AND t.czrq <=?";
        //市级
        if("4".equals(level)){
            sql +=" AND d.city = ? ";
            //区级
        }else if("3".equals(level)){
            sql +=" AND d.town = ? ";
            //机构
        }else if("2".equals(level)){
            sql +=" AND d.hospital = ? ";
        }

        sql +=" GROUP BY mt order by mt DESC ";

        List<Map<String,Object>> rs = jdbcTemplate.queryForList(sql,new Object[]{statDate,endDate,area});
        Map<String,Object> map = new HashMap<>();
        if(rs!=null&&rs.size()>0){
            //降低循环层级
            for(Map<String,Object> m : rs){
                map.put((String)m.get("mt"),m);
            }
        }

        JSONArray jsRs = new JSONArray();
        for(String time : times){
            JSONObject json   = new JSONObject();
            json.put("month",time);
            json.put("socre",map.get(time)==null?0:((Map<String,Object>)map.get(time)).get("avgCount"));
            jsRs.put(json);
        }
        return jsRs;
    }

    private  List<String> getMonthBetween(String minDate, String maxDate) throws Exception {
        ArrayList<String> result = new ArrayList<String>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");//格式化为年月
        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();

        min.setTime(sdf2.parse(minDate));
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

        max.setTime(sdf2.parse(maxDate));
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

        Calendar curr = min;
        while (curr.before(max)) {
            result.add(sdf.format(curr.getTime()));
            curr.add(Calendar.MONTH, 1);
        }

        return result;
    }

    public String getAvgAllInfo(int level ,String area,String lowLevel){

        String timeKey = redisTemplate.opsForValue().get("quota:timeKey");
        String rs = "";
        //市级
        if(level==4){
            if(StringUtils.isBlank(lowLevel)){
                rs = redisTemplate.opsForValue().get("quota:28:"+level+":"+area+":3:"+timeKey);
            }else{
                rs = redisTemplate.opsForValue().get("quota:28:"+level+":"+area+":2:"+timeKey);
            }
        } else if(level ==3){
            rs = redisTemplate.opsForValue().get("quota:28:"+level+":"+area+":2:"+timeKey);
        }else if(level ==2){
            String rstemp = redisTemplate.opsForValue().get("quota:28:"+level+":"+area+":1:"+timeKey);
            JSONObject jsonObject = new JSONObject(rstemp);
            JSONArray json = jsonObject.getJSONArray("data");
            statisticsAllService.translateTeamLeaderName(json);
            JSONObject rsjs = new JSONObject();
            rsjs.put("data",json);
            rs = rsjs.toString();
        }
        return rs;
    }

    /**
     * 统计当前团队,签约人数,服务次数,平均满意度
     * @return
     */
    public JSONArray getStatTitleInfo(String doctor,String startDate,String endDate)throws Exception{
        JSONArray rs = new JSONArray();

        AdminTeam admin =  adminTeamDao.findByLeaderCode(doctor);
        if(admin==null){
            throw new RuntimeException("未找到团队信息");
        }
        Long id = admin.getId();

        startDate = startDate+" 00:00:00";
        endDate = endDate+" 23:59:59";

        //1.统计签约数据
        //查找团队签约
        String sign_sql = "SELECT COUNT(1) signCount FROM wlyy_sign_family t WHERE t.admin_team_code ="+id+" AND t.czrq >='"+startDate+"' AND t.czrq<='"+endDate+"' AND t.status =1 AND t.expenses_status ='1'";
        //查找续签表未转移的记录
        String renew_sql = "SELECT COUNT(1) renewCount FROM wlyy_sign_family_renew t WHERE t.admin_team_code ="+id+" AND t.czrq >='"+startDate+"' AND t.czrq<='"+endDate+"' AND t.status =1 AND t.expenses_status ='1' AND t.is_valid =0";


        //3.平均满意度
        String avg_sql="SELECT ROUND(AVG(s.score),1) avgScore FROM wlyy_consult c LEFT JOIN wlyy_evaluate_score s ON c.`code` = s.consult WHERE c.czrq>='"+startDate+"' AND c.czrq<='"+endDate+"' AND s.doctor in(select m.doctor_code from wlyy_admin_team_member m where m.team_id="+id+")";

        //计算签约表记录
        Map<String,Object> signCount = jdbcTemplate.queryForMap(sign_sql);
        //计算续签表记录
        Map<String,Object> renewCount = jdbcTemplate.queryForMap(renew_sql);

        //计算签约总数
        Long sc = (Long)signCount.get("signCount");
        Long rc = (Long)renewCount.get("renewCount");

        JSONObject signTotal =new JSONObject();
        signTotal.put("signTotal",sc+rc);
        rs.put(signTotal);
        //获取咨詢數
        Map<String,Object> consultCout= getConsultByteam(id ,startDate ,endDate);
        rs.put(consultCout);
        //获取待预约
        Map<String,Object> reservationCout = getReservationByteam(id ,startDate ,endDate);
        rs.put(reservationCout);
        //获取健康教育
        Map<String,Object> articleCout= getEduArticleByTeam(id,startDate,endDate);
        rs.put(articleCout);
        //获取健康指导
        Map<String,Object> guidanceCout= getGuidanceByTeam(id,startDate,endDate);
        rs.put(guidanceCout);
        //随访数目
        Map<String,Object> followupCout= getArticleByTeam(id,startDate,endDate);
        rs.put(followupCout);
        //平均满意度
        Map<String,Object> avgCout= jdbcTemplate.queryForMap(avg_sql);
        if(avgCout.get("avgScore")==null){
            avgCout.put("avgScore",0);
        }
        rs.put(avgCout);

        return rs;

    }

    /**
     * 查询签约
     * @param type 0 按周,1 按月
     * @param startDate
     * @param endDate
     * @return
     */
    public JSONArray getSignCountLineByType(String doctor,String type,String startDate,String endDate){

        AdminTeam admin =  adminTeamDao.findByLeaderCode(doctor);
        if(admin==null){
            throw new RuntimeException("未找到团队信息");
        }
        Long id = admin.getId();

        String sql;
        //按周
        if("0".equals(type)){
           sql = "SELECT left(f.apply_date,10) as applyDate,count(1) as signCount " +
                   " FROM wlyy_sign_family f " +
                   " where f.apply_date >='"+startDate+" 00:00:00' " +
                   " AND f.apply_date<='"+endDate+" 00:00:00' " +
                   " AND f.status >0 " +
                   " AND f.expenses_status='1' " +
                   " AND f.admin_team_code="+id+
                   " GROUP BY left(f.apply_date,10)";
        //按月
        }else{
            sql ="SELECT (DATE_FORMAT(f.apply_date,'%v')-DATE_FORMAT('2017-06-01','%v')+1) as weekOfMonth,count(1) as signCount " +
                    " FROM wlyy_sign_family f " +
                    " where f.apply_date >='"+startDate+" 00:00:00' " +
                    " AND f.apply_date<='"+endDate+" 00:00:00' " +
                    " AND f.status >0 " +
                    " AND f.expenses_status='1' " +
                    " AND f.admin_team_code="+id+
                    " GROUP BY DATE_FORMAT(f.apply_date,'%m %v')";
        }

        List<Map<String,Object>> rs = jdbcTemplate.queryForList(sql);
        JSONArray rsJs = new JSONArray(rs);
        return rsJs;
    }

    /**
     * 查询续签约
     * @param type 0 按周,1 按月
     * @param startDate
     * @param endDate
     * @return
     */
    public JSONArray getRenewCountLineByType(String doctor,String type,String startDate,String endDate){

        AdminTeam admin =  adminTeamDao.findByLeaderCode(doctor);
        if(admin==null){
            throw new RuntimeException("未找到团队信息");
        }
        Long id = admin.getId();

        String sql;
        //按周
        if("0".equals(type)){
            sql = "SELECT left(f.apply_date,10) as applyDate,count(1) as signCount " +
                    " FROM wlyy_sign_family_renew f " +
                    " where f.apply_date >='"+startDate+" 00:00:00' " +
                    " AND f.apply_date<='"+endDate+" 23:59:59' " +
                    " AND f.status >0 " +
                    " AND f.expenses_status='1' " +
                    " AND f.admin_team_code="+id+
                    " GROUP BY left(f.apply_date,10)";
            //按月
        }else{
            sql ="SELECT (DATE_FORMAT(f.apply_date,'%v')-DATE_FORMAT('"+DateUtil.getFristDayOfMonth()+"','%v')+1) as weekOfMonth,count(1) as signCount " +
                    " FROM wlyy_sign_family_renew f " +
                    " where f.apply_date >='"+startDate+" 00:00:00' " +
                    " AND f.apply_date<='"+endDate+" 23:59:59' " +
                    " AND f.status >0 " +
                    " AND f.expenses_status='1' " +
                    " AND f.admin_team_code="+id+
                    " GROUP BY DATE_FORMAT(f.apply_date,'%m %v')";
        }

        List<Map<String,Object>> rs = jdbcTemplate.queryForList(sql);
        JSONArray rsJs = new JSONArray(rs);
        return rsJs;
    }


    public JSONObject getReyStatbyTeam(String doctor,String startDate,String endDate,String isNow){
        AdminTeam admin =  adminTeamDao.findByLeaderCode(doctor);
        if(admin==null){
            throw new RuntimeException("未找到团队信息");
        }
        Long id = admin.getId();
        //查找起始时间咨询未回复总数
        String noRelysql = "SELECT q.result FROM wlyy_quota_result q " +
                " WHERE q.quato_code ='22' " +
                " AND q.level1_type ='1' " +
                " AND q.quota_date ='"+startDate+"'" +
                " AND q.qkdoctor_code ='"+id+"';";
        //查找起始时间咨询总数
        String totalsql = "SELECT q.result FROM wlyy_quota_result q " +
                " WHERE q.quato_code ='25' " +
                " AND q.level1_type ='1' " +
                " AND q.quota_date ='"+startDate+"' " +
                " AND q.qkdoctor_code ='"+id+"'";

        Map<String,Object> noRelyMap = jdbcTemplate.queryForMap(noRelysql);
        Map<String,Object> totalMap = jdbcTemplate.queryForMap(noRelysql);

        Long noRelystartCount = Long.parseLong((String)noRelyMap.get("result"));
        Long totalstartCount = Long.parseLong((String)totalMap.get("result"));

        Long noRelyEndCount ;
        Long totalEndCount ;
        if("1".equals(isNow)){
            String timeKey = redisTemplate.opsForValue().get("quota:timeKey");
            //当前时间获取未回复咨询总数
            String noReyVal = redisTemplate.opsForValue().get("quota:22:1:"+id+":"+timeKey);
            if(StringUtils.isBlank(noReyVal)){
                throw new RuntimeException("未找到截止日期数据");
            }
            JSONObject nr = new JSONObject(noReyVal);
            noRelyEndCount = nr.getLong("num");
            //获取当前时间咨询总数
            String totalVal = redisTemplate.opsForValue().get("quota:25:1:"+id+":"+timeKey);
            if(StringUtils.isBlank(totalVal)){
                throw new RuntimeException("未找到截止日期数据");
            }
            JSONObject tr = new JSONObject(totalVal);
            totalEndCount = tr.getLong("num");
        }else{
            //查找结束时间未回复总数
            String noRelyEndsql = "SELECT q.result FROM wlyy_quota_result q " +
                    " WHERE q.quato_code ='22' " +
                    " AND q.level1_type ='1' " +
                    " AND q.quota_date ='"+endDate+"'" +
                    " AND q.qkdoctor_code ='"+id+"';";
            //查找结束时间咨询总数
            String totalEndsql = "SELECT q.result FROM wlyy_quota_result q " +
                    " WHERE q.quato_code ='25' " +
                    " AND q.level1_type ='1' " +
                    " AND q.quota_date ='"+startDate+"' " +
                    " AND q.qkdoctor_code ='"+id+"'";
            Map<String,Object> noRelyEndMap = jdbcTemplate.queryForMap(noRelyEndsql);
            Map<String,Object> totalEndMap = jdbcTemplate.queryForMap(totalEndsql);

            noRelyEndCount = Long.parseLong((String)noRelyEndMap.get("result"));
            totalEndCount = Long.parseLong((String)totalEndMap.get("result"));
        }

        JSONObject rs = new JSONObject();
        rs.put("onReyCount",noRelyEndCount-noRelystartCount);
        rs.put("totalCount",totalEndCount-totalstartCount);
        return rs;
    }

    public JSONArray getServiceRankingList(String doctor ,String startDate,String endDate){

        AdminTeam admin =  adminTeamDao.findByLeaderCode(doctor);
        if(admin==null){
            throw new RuntimeException("未找到团队信息");
        }
        Long id = admin.getId();
        String orgcode = admin.getOrgCode();
        JSONArray rs = new JSONArray();

        //咨询团队排行SQL
        String crc_sql = "SELECT s.rowno AS consultRK FROM " +
                " ( " +
                "   select (@rowNum :=@rowNum + 1) AS rowno,t.count,t.admin_team_code " +
                "   FROM (" +
                "       SELECT COUNT(1) AS count,w.admin_team_code " +
                "       FROM wlyy_consult_team  w " +
                "       WHERE w.czrq>='"+startDate+" 00:00:00' AND w.czrq <='"+endDate+" 23:59:59' AND w.admin_team_code IN( " +
                "       SELECT " +
                "       m.id FROM wlyy_admin_team m " +
                "       WHERE m.org_code ='"+orgcode+"'" +
                "       ) " +
                "   GROUP BY w.admin_team_code " +
                "   ORDER BY count DESC " +
                "   )t," +
                "   (SELECT(@rowNum := 0)) b " +
                " ) s " +
                " WHERE s.admin_team_code ="+id;
        List<Map<String,Object>> crc = jdbcTemplate.queryForList(crc_sql);
        if(crc!=null&&crc.size()>0){
            rs.put(crc.get(0));
        }else{
            Map<String,Object> map = new HashMap<>();
            map.put("consultRK",0);
            rs.put(map);
        }

        //随访量排行
        String frc_sql ="SELECT s.rowno AS followupRK FROM " +
                "( " +
                " select (@rowNum :=@rowNum + 1) AS rowno,t.count,t.admin_team_code  " +
                " from ( " +
                " SELECT COUNT(1) AS count,w.admin_team_code " +
                " FROM wlyy_followup  w " +
                " WHERE w.org_code = '"+orgcode+"'  " +
                " AND w.admin_team_code IS NOT NULL " +
                " AND w.create_time >='"+startDate+" 00:00:00' AND w.create_time <='"+endDate+" 23:59:59'"+
                " GROUP BY w.admin_team_code  " +
                " ORDER BY count DESC " +
                " ) t, " +
                " (SELECT(@rowNum := 0)) b " +
                ") s  " +
                "WHERE s.admin_team_code ="+id;
        List<Map<String,Object>> frc = jdbcTemplate.queryForList(frc_sql);
        if(frc!=null&&frc.size()>0){
            rs.put(frc.get(0));
        }else{
            Map<String,Object> map = new HashMap<>();
            map.put("followupRK",0);
            rs.put(map);
        }
        //待预约量排行
        String resrc_sql = "SELECT s.rowno AS reservationRK from " +
                "( " +
                "  SELECT (@rowNum :=@rowNum + 1) AS rowno,t.reservationCount,t.admin_team_code \n" +
                "   FROM ( " +
                "   SELECT COUNT(1) AS reservationCount,w.admin_team_code " +
                "   FROM wlyy_patient_reservation  w " +
                "   WHERE w.czrq>='"+startDate+" 00:00:00' AND w.czrq <='"+endDate+" 23:59:59' AND " +
                "   w.org_code ='"+orgcode+"'" +
                "   AND w.doctor is not null " +
                "   AND w.admin_team_code IS NOT NULL " +
                "   GROUP BY w.admin_team_code " +
                "   ORDER BY reservationCount DESC " +
                "   ) t,(SELECT(@rowNum := 0)) b " +
                ") s  " +
                "WHERE s.admin_team_code ="+id;
        List<Map<String,Object>> resrc = jdbcTemplate.queryForList(resrc_sql);
        if(resrc!=null&&resrc.size()>0){
            rs.put(resrc.get(0));
        }else{
            Map<String,Object> map = new HashMap<>();
            map.put("reservationRK",0);
            rs.put(map);
        }
        //健康指导排行
        String grc_sql ="SELECT s.rowno AS guidanceRK FROM " +
                "( " +
                " SELECT (@rowNum :=@rowNum + 1) AS rowno,t.count,t.admin_team_code " +
                " FROM (" +
                " SELECT COUNT(1) AS count,w.admin_team_code " +
                " FROM wlyy_patient_health_guidance w " +
                " WHERE w.czrq>='"+startDate+" 00:00:00' AND w.czrq <='"+endDate+" 23:59:59' " +
                " AND  w.admin_team_code IN( " +
                " SELECT m.id FROM wlyy_admin_team m" +
                "   WHERE m.org_code ='"+orgcode+"'" +
                "   ) " +
                " GROUP BY w.admin_team_code " +
                " ORDER BY count DESC " +
                "   ) t," +
                "(SELECT(@rowNum := 0)) b " +
                " ) s " +
                "WHERE s.admin_team_code ="+id;
        List<Map<String,Object>> grc = jdbcTemplate.queryForList(grc_sql);
        if(grc!=null&&grc.size()>0){
            rs.put(grc.get(0));
        }else{
            Map<String,Object> map = new HashMap<>();
            map.put("guidanceRK",0);
            rs.put(map);
        }
        //健康教育排行
        String edurc_sql ="SELECT s.rowno AS articleRK FROM " +
                "( " +
                " SELECT (@rowNum :=@rowNum + 1) AS rowno,t.count,t.admin_team_code " +
                " FROM ( " +
                " SELECT COUNT(1) AS count,w.admin_team_code " +
                " FROM wlyy_health_edu_article_patient w " +
                " WHERE w.czrq>='"+startDate+" 00:00:00' AND w.czrq <='"+endDate+" 23:59:59' AND " +
                " w.admin_team_code IN(" +
                " SELECT m.id FROM wlyy_admin_team m " +
                " WHERE m.org_code ='"+orgcode+"'" +
                "   ) " +
                "   GROUP BY w.admin_team_code " +
                "   ORDER BY count DESC " +
                ") t," +
                "(SELECT(@rowNum := 0)) b" +
                ") s " +
                "WHERE s.admin_team_code ="+id;
        List<Map<String,Object>> edurc = jdbcTemplate.queryForList(edurc_sql);
        if(edurc!=null&&edurc.size()>0){
            rs.put(edurc.get(0));
        }else{
            Map<String,Object> map = new HashMap<>();
            map.put("articleRK",0);
            rs.put(map);
        }
        return rs;
    }

    /**
     * 获取咨询数
     * @param id
     * @param startDate
     * @param endDate
     * @return
     */
    public Map<String,Object> getConsultByteam(Long id ,String startDate ,String endDate){

        startDate = startDate+" 00:00:00";
        endDate = endDate+" 23:59:59";
        //咨询量
        String consult_sql = "SELECT COUNT(1) AS consultCount FROM wlyy_consult_team t WHERE t.admin_team_code = "+id+" AND t.czrq <='"+endDate+"' AND t.czrq >='"+startDate+"'";
        //获取咨詢數
        Map<String,Object> consultCout= jdbcTemplate.queryForMap(consult_sql);
        if(consultCout.get("consultCount")==null){
            consultCout.put("consultCount",0);
        }
        return consultCout;
    }

    public Map<String,Object> getReservationByteam(Long id ,String startDate ,String endDate){
        startDate = startDate+" 00:00:00";
        endDate = endDate+" 23:59:59";
        //获取待预约
        String reservation_sql = "SELECT COUNT(1) AS reservationCount FROM wlyy_patient_reservation  w WHERE w.admin_team_code ="+id+" AND w.czrq <='"+endDate+"' AND w.czrq >='"+startDate+"'";
        //获取待预约
        Map<String,Object> reservationCout= jdbcTemplate.queryForMap(reservation_sql);
        if(reservationCout.get("reservationCount")==null){
            reservationCout.put("reservationCount",0);
        }
        return reservationCout;
    }

    public Map<String,Object> getEduArticleByTeam(Long id ,String startDate ,String endDate){
        startDate = startDate+" 00:00:00";
        endDate = endDate+" 23:59:59";
        //获取健康教育
        String article_sql = "SELECT COUNT(1) AS articleCount FROM wlyy_health_edu_article_patient w WHERE  w.admin_team_code ="+id+" AND w.czrq <='"+endDate+"' AND w.czrq >='"+startDate+"'";
        //获取健康教育
        Map<String,Object> articleCout= jdbcTemplate.queryForMap(article_sql);
        if(articleCout.get("articleCount")==null){
            articleCout.put("articleCount",0);
        }
        return articleCout;
    }

    public Map<String,Object> getGuidanceByTeam(Long id ,String startDate ,String endDate){
        startDate = startDate+" 00:00:00";
        endDate = endDate+" 23:59:59";
        //获取健康指导
        String guidance_sql = "SELECT COUNT(1) AS guidanceCount  FROM wlyy_patient_health_guidance w WHERE w.admin_team_code ="+id+" AND w.czrq <='"+endDate+"' AND w.czrq >='"+startDate+"'";
        //获取健康指导
        Map<String,Object> guidanceCout= jdbcTemplate.queryForMap(guidance_sql);
        if(guidanceCout.get("guidanceCount")==null){
            guidanceCout.put("guidanceCount",0);
        }
        return guidanceCout;
    }

    public Map<String,Object> getArticleByTeam(Long id ,String startDate ,String endDate){
        startDate = startDate+" 00:00:00";
        endDate = endDate+" 23:59:59";
        //随访数目
        String followup_sql ="SELECT COUNT(1) AS followupCount from wlyy_followup w WHERE w.admin_team_code="+id+" AND  w.create_time >='"+startDate+"' AND w.create_time<='"+endDate+"' AND w.followup_class IS NOT NULL ";
        //随访数目
        Map<String,Object> followupCout= jdbcTemplate.queryForMap(followup_sql);
        if(followupCout.get("followupCount")==null){
            followupCout.put("followupCount",0);
        }
        return followupCout;
    }

    /***
     * 获取平均折线图
     * @param doctor
     * @param startDate
     * @param endDate
     * @param type 0 周,1月
     * @return
     */
    public JSONArray getAvgLine(String doctor,String startDate,String endDate,String type){

        AdminTeam admin =  adminTeamDao.findByLeaderCode(doctor);
        if(admin==null){
            throw new RuntimeException("未找到团队信息");
        }
        Long id = admin.getId();

        startDate = startDate+" 00:00:00";
        endDate = endDate+" 23:59:59";
        String sql ;
        //周计算
        if("0".equals(type)){
            sql = "SELECT DATE_FORMAT(t.czrq,'%Y-%m-%d') AS dateNo,ifnull(ROUND(AVG(s.score),1),0)  as avgCount " +
                    "    FROM  wlyy_consult_team t" +
                    "    LEFT JOIN wlyy_doctor d ON d.code = t.doctor " +
                    "    LEFT JOIN wlyy_evaluate_score s ON s.doctor = t.doctor  " +
                    " WHERE t.czrq <='"+endDate+"' AND t.czrq >='"+startDate+"'" +
                    " AND t.admin_team_code =" +id+
                    " GROUP BY dateNo ";
        }else{
            sql = "SELECT (DATE_FORMAT(t.czrq,'%v')-DATE_FORMAT('"+startDate+"','%v')+1) AS weekNo,ifnull(ROUND(AVG(s.score),1),0)  as avgCount " +
                    "    FROM  wlyy_consult_team t " +
                    "    LEFT JOIN wlyy_doctor d ON d.code = t.doctor " +
                    "    LEFT JOIN wlyy_evaluate_score s ON s.doctor = t.doctor " +
                    " WHERE t.czrq <='"+endDate+"' AND t.czrq >='"+startDate+"'" +
                    " AND t.admin_team_code =" +id+
                    " GROUP BY weekNo";
        }

        List<Map<String,Object>> rs = jdbcTemplate.queryForList(sql);
        JSONArray js = new JSONArray(rs);
        return js;
    }

    public int checkDoctorIsTeamleader(String doctor){
        AdminTeam team = adminTeamDao.findByLeaderCode(doctor);
        if(team!=null){
            return 1;
        }
        return 0;
    }

    /**
     * 获取团队月或周咨询未回复和总数折线图
     * @param teamCode
     * @param startDate
     * @param endDate
     * @param type 0周,1月
     * @return
     */
    public JSONObject getTeamConsultCount(String teamCode,String startDate,String endDate,String type){
        String imDataBaseName = SystemConf.getInstance().getImDataBaseName();
        String sql ;
        String totalSql ;
        startDate = startDate+" 00:00:00";
        endDate = endDate+" 23:59:59";
        if("0".equals(type)){
            //按周统计
            sql = "SELECT " +
                    " left(a.czrq,10) AS dateNo,count(1) AS noRely " +
                    " FROM " +
                    " wlyy_consult_team a " +
                    " WHERE" +
                    " a.czrq <= '"+endDate+"'" +
                    " AND a.czrq >= '"+startDate+"'" +
                    " AND a.admin_team_code ="+teamCode+
                    " AND a.consult IN (" +
                    " SELECT DISTINCT " +
                    " t.id consultId " +
                    " FROM " +
                    " "+imDataBaseName+".topics t, " +
                    " "+imDataBaseName+".participants p, " +
                    " "+imDataBaseName+".doctors d, " +
                    " "+imDataBaseName+".sessions s " +
                    " WHERE " +
                    " p.participant_id = d.id " +
                    " AND t.session_id = p.session_id " +
                    " AND t.session_id = s.id " +
                    " AND s.type = 1 " +
                    " AND t. STATUS <> 10 " +
                    " AND t.`reply` = 0 " +
                    " AND t.create_time <= '"+endDate+"'" +
                    " AND t.create_time >= '"+startDate+"'" +
                    " )" +
                    " GROUP BY left(a.czrq,10)";

            totalSql ="SELECT " +
                    " left(a.czrq,10) AS dateNo,count(1) AS total " +
                    " FROM " +
                    " wlyy_consult_team a " +
                    " WHERE" +
                    " a.czrq <= '"+endDate+"'" +
                    " AND a.czrq >= '"+startDate+"'" +
                    " AND a.admin_team_code ="+teamCode+
                    " AND a.consult IN (" +
                    " SELECT DISTINCT " +
                    " t.id consultId " +
                    " FROM " +
                    " "+imDataBaseName+".topics t, " +
                    " "+imDataBaseName+".participants p, " +
                    " "+imDataBaseName+".doctors d, " +
                    " "+imDataBaseName+".sessions s " +
                    " WHERE " +
                    " p.participant_id = d.id " +
                    " AND t.session_id = p.session_id " +
                    " AND t.session_id = s.id " +
                    " AND s.type = 1 " +
                    " AND t.create_time <= '"+endDate+"'" +
                    " AND t.create_time >= '"+startDate+"'" +
                    " )" +
                    " GROUP BY left(a.czrq,10)";
        }else{
            //按月统计
            sql = "SELECT " +
                    " ( " +
                    " DATE_FORMAT(a.czrq, '%v') - DATE_FORMAT('"+DateUtil.getFristDayOfMonth()+"', '%v') + 1" +
                    " ) AS weekOfMonth, " +
                    "  COUNT(1) AS noRely" +
                    " FROM " +
                    " wlyy_consult_team a " +
                    " WHERE " +
                    " a.czrq <= '"+endDate+"' " +
                    " AND a.czrq >= '"+startDate+"' " +
                    " AND a.admin_team_code =" +teamCode+
                    " AND a.consult IN (" +
                    " SELECT DISTINCT " +
                    " t.id consultId " +
                    " FROM " +
                    " "+imDataBaseName+".topics t," +
                    " "+imDataBaseName+".participants p," +
                    " "+imDataBaseName+".doctors d, " +
                    " "+imDataBaseName+".sessions s " +
                    " WHERE " +
                    " p.participant_id = d.id " +
                    " AND t.session_id = p.session_id " +
                    " AND t.session_id = s.id " +
                    " AND s.type = 1 " +
                    " AND t. STATUS <> 10 " +
                    " AND t.`reply` = 0 " +
                    " AND t.create_time <= '"+endDate+"'" +
                    " AND t.create_time >= '"+startDate+"'" +
                    " )" +
                    " GROUP BY " +
                    " DATE_FORMAT(a.czrq, '%m %v')";
            totalSql ="SELECT " +
                    " ( " +
                    " DATE_FORMAT(a.czrq, '%v') - DATE_FORMAT('"+DateUtil.getFristDayOfMonth()+"', '%v') + 1" +
                    " ) AS weekOfMonth, " +
                    "  COUNT(1) AS total" +
                    " FROM " +
                    " wlyy_consult_team a " +
                    " WHERE " +
                    " a.czrq <= '"+endDate+"' " +
                    " AND a.czrq >= '"+startDate+"' " +
                    " AND a.admin_team_code =" +teamCode+
                    " AND a.consult IN (" +
                    " SELECT DISTINCT " +
                    " t.id consultId " +
                    " FROM " +
                    " "+imDataBaseName+".topics t," +
                    " "+imDataBaseName+".participants p," +
                    " "+imDataBaseName+".doctors d, " +
                    " "+imDataBaseName+".sessions s " +
                    " WHERE " +
                    " p.participant_id = d.id " +
                    " AND t.session_id = p.session_id " +
                    " AND t.session_id = s.id " +
                    " AND s.type = 1 " +
                    " AND t.create_time <= '"+endDate+"'" +
                    " AND t.create_time >= '"+startDate+"'" +
                    " )" +
                    " GROUP BY " +
                    " DATE_FORMAT(a.czrq, '%m %v')";
        }

        List<Map<String,Object>> noReyList = jdbcTemplate.queryForList(sql);
        List<Map<String,Object>> totalList = jdbcTemplate.queryForList(totalSql);
        JSONObject result = new JSONObject();
        result.put("noReyList",noReyList);
        result.put("totalList",totalList);
        return result;
    }

    /**
     *  计算团队医生月或周咨询未回复和总数折线图
     * @param teamCode
     * @param startDate
     * @param endDate
     * @param type
     * @param doctor 医生code
     * @return
     */
    public JSONObject getTeamDoctorConsultCount(String teamCode,String startDate,String endDate,String type,String doctor){
        String imDataBaseName = SystemConf.getInstance().getImDataBaseName();
        String sql ;
        String totalSql ;
        startDate = startDate+" 00:00:00";
        endDate = endDate+" 23:59:59";
        if("0".equals(type)){
            //按周统计
            sql = "SELECT " +
                    " left(a.czrq,10) AS dateNo,count(1) AS noRely " +
                    " FROM " +
                    " wlyy_consult_team a " +
                    " WHERE" +
                    " a.czrq <= '"+endDate+"'" +
                    " AND a.czrq >= '"+startDate+"'" +
                    " AND a.admin_team_code ="+teamCode+
                    " AND a.consult IN (" +
                    " SELECT DISTINCT " +
                    " t.id consultId " +
                    " FROM " +
                    " "+imDataBaseName+".topics t, " +
                    " "+imDataBaseName+".participants p, " +
                    " "+imDataBaseName+".doctors d, " +
                    " "+imDataBaseName+".sessions s " +
                    " WHERE " +
                    " p.participant_id = d.id " +
                    " AND t.session_id = p.session_id " +
                    " AND t.session_id = s.id " +
                    " AND s.type = 1 " +
                    " AND t. STATUS <> 10 " +
                    " AND t.`reply` = 0 " +
                    " AND t.create_time <= '"+endDate+"'" +
                    " AND t.create_time >= '"+startDate+"'" +
                    " AND d.id = '"+doctor+"'"+
                    " )" +
                    " GROUP BY left(a.czrq,10)";

            totalSql ="SELECT " +
                    " left(a.czrq,10) AS dateNo,count(1) AS total " +
                    " FROM " +
                    " wlyy_consult_team a " +
                    " WHERE" +
                    " a.czrq <= '"+endDate+"'" +
                    " AND a.czrq >= '"+startDate+"'" +
                    " AND a.admin_team_code ="+teamCode+
                    " AND a.consult IN (" +
                    " SELECT DISTINCT " +
                    " t.id consultId " +
                    " FROM " +
                    " "+imDataBaseName+".topics t, " +
                    " "+imDataBaseName+".participants p, " +
                    " "+imDataBaseName+".doctors d, " +
                    " "+imDataBaseName+".sessions s " +
                    " WHERE " +
                    " p.participant_id = d.id " +
                    " AND t.session_id = p.session_id " +
                    " AND t.session_id = s.id " +
                    " AND s.type = 1 " +
                    " AND t.create_time <= '"+endDate+"'" +
                    " AND t.create_time >= '"+startDate+"'" +
                    " AND d.id = '"+doctor+"'"+
                    " )" +
                    " GROUP BY left(a.czrq,10)";
        }else{
            //按月统计
            sql = "SELECT " +
                    " ( " +
                    " DATE_FORMAT(a.czrq, '%v') - DATE_FORMAT('"+DateUtil.getFristDayOfMonth()+"', '%v') + 1" +
                    " ) AS weekOfMonth, " +
                    "  COUNT(1) AS noRely" +
                    " FROM " +
                    " wlyy_consult_team a " +
                    " WHERE " +
                    " a.czrq <= '"+endDate+"' " +
                    " AND a.czrq >= '"+startDate+"' " +
                    " AND a.admin_team_code =" +teamCode+
                    " AND a.consult IN (" +
                    " SELECT DISTINCT " +
                    " t.id consultId " +
                    " FROM " +
                    " "+imDataBaseName+".topics t," +
                    " "+imDataBaseName+".participants p," +
                    " "+imDataBaseName+".doctors d, " +
                    " "+imDataBaseName+".sessions s " +
                    " WHERE " +
                    " p.participant_id = d.id " +
                    " AND t.session_id = p.session_id " +
                    " AND t.session_id = s.id " +
                    " AND s.type = 1 " +
                    " AND t. STATUS <> 10 " +
                    " AND t.`reply` = 0 " +
                    " AND t.create_time <= '"+endDate+"'" +
                    " AND t.create_time >= '"+startDate+"'" +
                    " AND d.id = '"+doctor+"'"+
                    " )" +
                    " GROUP BY " +
                    " DATE_FORMAT(a.czrq, '%m %v')";
            totalSql ="SELECT " +
                    " ( " +
                    " DATE_FORMAT(a.czrq, '%v') - DATE_FORMAT('"+DateUtil.getFristDayOfMonth()+"', '%v') + 1" +
                    " ) AS weekOfMonth, " +
                    "  COUNT(1) AS total" +
                    " FROM " +
                    " wlyy_consult_team a " +
                    " WHERE " +
                    " a.czrq <= '"+endDate+"' " +
                    " AND a.czrq >= '"+startDate+"' " +
                    " AND a.admin_team_code =" +teamCode+
                    " AND a.consult IN (" +
                    " SELECT DISTINCT " +
                    " t.id consultId " +
                    " FROM " +
                    " "+imDataBaseName+".topics t," +
                    " "+imDataBaseName+".participants p," +
                    " "+imDataBaseName+".doctors d, " +
                    " "+imDataBaseName+".sessions s " +
                    " WHERE " +
                    " p.participant_id = d.id " +
                    " AND t.session_id = p.session_id " +
                    " AND t.session_id = s.id " +
                    " AND s.type = 1 " +
                    " AND t.create_time <= '"+endDate+"'" +
                    " AND t.create_time >= '"+startDate+"'" +
                    " AND d.id = '"+doctor+"'"+
                    " )" +
                    " GROUP BY " +
                    " DATE_FORMAT(a.czrq, '%m %v')";
        }

        List<Map<String,Object>> noReyList = jdbcTemplate.queryForList(sql);
        List<Map<String,Object>> totalList = jdbcTemplate.queryForList(totalSql);
        JSONObject result = new JSONObject();
        result.put("noReyList",noReyList);
        result.put("totalList",totalList);
        return result;
    }

    /**
     * 获取团队咨询情况列表
     * @param teamCode
     * @param startDate
     * @param endDate
     * @param sort 0降序 1升续
     * @return
     */
    public JSONArray getMemberConsultList(String teamCode,String startDate,String endDate,String sort){
        String imDataBaseName = SystemConf.getInstance().getImDataBaseName();
        startDate = startDate+" 00:00:00";
        endDate = endDate+" 23:59:59";
        // 未回复咨询总量
        String onReySQL = "SELECT " +
                " t.doctor_code AS doctorCode, " +
                " d.`name`, " +
                " IFNULL(r.noRely,0) AS noRely " +
                " FROM" +
                " wlyy_admin_team_member t " +
                " LEFT JOIN (" +
                " SELECT " +
                "  c.doctorCode, " +
                "  count(1) AS noRely " +
                " FROM " +
                " wlyy_consult_team a," +
                " ( " +
                " SELECT DISTINCT " +
                " t.id consultId, " +
                " d.id doctorCode " +
                " FROM " +
                " "+imDataBaseName+".topics t, " +
                " "+imDataBaseName+".participants p, " +
                " "+imDataBaseName+".doctors d, " +
                " "+imDataBaseName+".sessions s " +
                " WHERE " +
                " p.participant_id = d.id " +
                " AND t.session_id = p.session_id " +
                " AND t.session_id = s.id " +
                " AND s.type = 1 " +
                " AND t. STATUS <> 10 " +
                " AND t.`reply` = 0 " +
                " AND t.create_time <= '"+endDate+"' " +
                " AND t.create_time >= '"+startDate+"' " +
                " ) c" +
                " WHERE " +
                " c.consultId = a.consult " +
                " AND a.admin_team_code = " +teamCode+
                " GROUP BY " +
                " c.doctorCode " +
                " ) r ON r.doctorCode = t.doctor_code, " +
                " wlyy_doctor d " +
                " WHERE " +
                " t.doctor_code = d.`code` " +
                " AND t.available = 1 " +
                " AND t.team_id = "+teamCode ;
        if("0".equals(sort)){
            onReySQL = onReySQL+ " ORDER BY noRely DESC";
        }else{
            onReySQL = onReySQL+ " ORDER BY noRely ASC";
        }

        //总咨询量
        String totalSql ="SELECT " +
                " t.doctor_code AS doctorCode, " +
                " d.`name`, " +
                " IFNULL(r.total,0) AS total " +
                "FROM " +
                " wlyy_admin_team_member t " +
                "LEFT JOIN ( " +
                " SELECT " +
                " c.doctorCode, " +
                " count(1) AS total " +
                " FROM " +
                " wlyy_consult_team a, " +
                " ( " +
                " SELECT DISTINCT " +
                " t.id consultId, " +
                " d.id doctorCode " +
                " FROM " +
                " "+imDataBaseName+".topics t, " +
                " "+imDataBaseName+".participants p, " +
                " "+imDataBaseName+".doctors d, " +
                " "+imDataBaseName+".sessions s " +
                " WHERE " +
                " p.participant_id = d.id " +
                " AND t.session_id = p.session_id " +
                " AND t.session_id = s.id " +
                " AND s.type = 1 " +
                " AND t.create_time <= '"+endDate+"' " +
                " AND t.create_time >= '"+startDate+"' " +
                " ) c " +
                " WHERE " +
                " c.consultId = a.consult " +
                " AND a.admin_team_code = " +teamCode+
                " GROUP BY " +
                " c.doctorCode " +
                ") r ON r.doctorCode = t.doctor_code, " +
                " wlyy_doctor d " +
                "WHERE " +
                " t.doctor_code = d.`code` " +
                "AND t.available = 1 " +
                "AND t.team_id =  "+teamCode ;

        //结束咨询
        String endConsultSql ="SELECT " +
                " t.doctor_code doctorCode, " +
                " d.`name`, " +
                " IFNULL(r.endRey,0) AS endRey " +
                "FROM " +
                " wlyy_admin_team_member t " +
                "LEFT JOIN ( " +
                " SELECT " +
                "  c.doctorCode, " +
                "  count(1) AS endRey " +
                " FROM " +
                "  wlyy_consult_team a, " +
                "  ( " +
                " SELECT DISTINCT " +
                " t.id consultId, " +
                " d.id doctorCode " +
                " FROM " +
                " "+imDataBaseName+".topics t, " +
                " "+imDataBaseName+".participants p, " +
                " "+imDataBaseName+".doctors d, " +
                " "+imDataBaseName+".sessions s " +
                " WHERE " +
                " p.participant_id = d.id " +
                " AND t.session_id = p.session_id " +
                " AND t.session_id = s.id " +
                " AND s.type = 1 " +
                " AND t. STATUS = 10 " +
                " AND t.create_time <= '"+endDate+"' " +
                " AND t.create_time >= '"+startDate+"' " +
                " ) c " +
                " WHERE " +
                " c.consultId = a.consult " +
                " AND a.admin_team_code =" +teamCode+
                " GROUP BY " +
                " c.doctorCode " +
                ") r ON r.doctorCode = t.doctor_code, " +
                " wlyy_doctor d " +
                " WHERE " +
                " t.doctor_code = d.`code` " +
                " AND t.available = 1 " +
                " AND t.team_id = "+teamCode;

        List<Map<String,Object>> onReyList = jdbcTemplate.queryForList(onReySQL);

        List<Map<String,Object>> totalList = jdbcTemplate.queryForList(totalSql);

        Map<String,Object> totalMap = new HashMap<>();
        //将List转换为Map降低循环层级
        if(totalList!=null&&totalList.size()>0){
            for(Map<String,Object> list :totalList){
                String code = (String)list.get("doctorCode");
                totalMap.put(code,list);
            }
        }
        List<Map<String,Object>> endConsultList = jdbcTemplate.queryForList(endConsultSql);

        //将List转换为Map降低循环层级
        Map<String,Object> endConsultMap = new HashMap<>();
        //将List转换为Map降低循环层级
        if(endConsultList!=null&&endConsultList.size()>0){
            for(Map<String,Object> list :endConsultList){
                String code = (String)list.get("doctorCode");
                endConsultMap.put(code,list);
            }
        }

        //合并结果集
        if(onReyList!=null&&onReyList.size()>0){
            for(Map<String,Object> map :onReyList){
                String code = (String)map.get("doctorCode");

                Map<String,Object> t = ( Map<String,Object>)totalMap.get(code);
                Long totalCout = (Long)t.get("total");
                map.put("total",totalCout);

                Map<String,Object> e =( Map<String,Object>)endConsultMap.get(code);
                Long endCout = (Long)e.get("endRey");
                map.put("endRey",endCout);
            }
        }

        return new JSONArray(onReyList);
    }

    public JSONObject getDoctorConsultTitle(String doctor,String teamCode,String startDate,String endDate){
        String imDataBaseName = SystemConf.getInstance().getImDataBaseName();
        startDate = startDate+" 00:00:00";
        endDate = endDate+" 23:59:59";
        //获取咨询总数
        String couTotalSQL = "SELECT " +
                " c.doctorCode, " +
                " count(1) AS total " +
                " FROM " +
                " wlyy_consult_team a, " +
                " ( " +
                " SELECT DISTINCT " +
                " t.id consultId, " +
                " d.id doctorCode " +
                " FROM " +
                " "+imDataBaseName+".topics t, " +
                " "+imDataBaseName+".participants p, " +
                " "+imDataBaseName+".doctors d, " +
                " "+imDataBaseName+".sessions s " +
                " WHERE " +
                " p.participant_id = d.id " +
                " AND t.session_id = p.session_id " +
                " AND t.session_id = s.id " +
                " AND s.type = 1 " +
                " AND t.create_time <= '"+endDate+"' " +
                " AND d.id='"+doctor+"' " +
                " ) c " +
                " WHERE " +
                " c.consultId = a.consult " +
                " AND a.admin_team_code = " +teamCode +
                " GROUP BY " +
                " c.doctorCode ";
        //及时回复数
        String reyTotalSql ="SELECT " +
                " c.doctorCode, " +
                " count(1) AS total " +
                " FROM " +
                " wlyy_consult_team a, " +
                " ( " +
                " SELECT DISTINCT " +
                " t.id consultId, " +
                " d.id doctorCode " +
                " FROM " +
                " "+imDataBaseName+".topics t, " +
                " "+imDataBaseName+".participants p, " +
                " "+imDataBaseName+".doctors d, " +
                " "+imDataBaseName+".sessions s " +
                " WHERE " +
                " p.participant_id = d.id " +
                " AND t.session_id = p.session_id " +
                " AND t.session_id = s.id " +
                " AND s.business_type=2  " +
                " AND t.`reply`=1  " +
                " AND TIMESTAMPDIFF(SECOND ,t.create_time ,t.reply_time) <86400 AND TIMESTAMPDIFF(SECOND ,t.create_time,t.reply_time) >0 " +
                " AND t.create_time <= '"+endDate+"' " +
                " AND d.id='"+doctor+"' " +
                " ) c " +
                " WHERE " +
                " c.consultId = a.consult " +
                " AND a.admin_team_code =" +teamCode+
                " GROUP BY " +
                " c.doctorCode";
        //本周或月增量
        String addTotalSql ="SELECT " +
                "  c.doctorCode, " +
                "  count(1) AS total " +
                " FROM " +
                "  wlyy_consult_team a, " +
                "  ( " +
                "   SELECT DISTINCT " +
                " t.id consultId," +
                " d.id doctorCode " +
                " FROM " +
                "    "+imDataBaseName+".topics t, " +
                "    "+imDataBaseName+".participants p, " +
                "    "+imDataBaseName+".doctors d, " +
                "    "+imDataBaseName+".sessions s " +
                "   WHERE " +
                "    p.participant_id = d.id " +
                "   AND t.session_id = p.session_id " +
                "   AND t.session_id = s.id " +
                "   AND s.type = 1 " +
                "   AND t.create_time <= '"+endDate+"' " +
                "   AND t.create_time >= '"+startDate+"' " +
                "   AND d.id='"+doctor+"' " +
                "  ) c " +
                " WHERE " +
                "  c.consultId = a.consult " +
                " AND a.admin_team_code =" +teamCode+
                " GROUP BY " +
                "  c.doctorCode";
        //当前未回复咨询数
        String noRelySql ="SELECT " +
                "  c.doctorCode, " +
                "  count(1) AS total " +
                " FROM " +
                "  wlyy_consult_team a, " +
                "  ( " +
                "   SELECT DISTINCT " +
                "    t.id consultId, " +
                "    d.id doctorCode " +
                "   FROM " +
                "    "+imDataBaseName+".topics t, " +
                "    "+imDataBaseName+".participants p, " +
                "    "+imDataBaseName+".doctors d, " +
                "    "+imDataBaseName+".sessions s " +
                "   WHERE " +
                "    p.participant_id = d.id " +
                "   AND t.session_id = p.session_id " +
                "   AND t.session_id = s.id " +
                "   AND s.type = 1  " +
                "   AND t. STATUS <> 10  " +
                "   AND t.`reply` = 0  " +
                "   AND t.create_time <= '"+endDate+"' " +
                "   AND t.create_time >= '"+startDate+"' " +
                "   AND d.id='"+doctor+"' " +
                "  ) c " +
                " WHERE " +
                "  c.consultId = a.consult " +
                "  AND a.admin_team_code =" +teamCode+
                " GROUP BY " +
                "  c.doctorCode";

        JSONObject rs = new JSONObject();
        Long total =0L;
        Long relyOnTime =0L;
        Long addNumber = 0L;
        Long noRelyNumber =0L;
        List<Map<String,Object>> couTotal = jdbcTemplate.queryForList(couTotalSQL);
        if(couTotal!=null&&couTotal.size()>0){
            Map<String,Object> couTotalMap = couTotal.get(0);
            total = (Long) couTotalMap.get("total")==null?0L:(Long) couTotalMap.get("total");
        }
        rs.put("total",total);

        List<Map<String,Object>> reyTotal = jdbcTemplate.queryForList(reyTotalSql);
        if(reyTotal!=null&&reyTotal.size()>0){
            Map<String,Object> reyTotalMap = reyTotal.get(0);
            relyOnTime = (Long) reyTotalMap.get("total")==null?0L:(Long) reyTotalMap.get("total");
        }
        if(total!=0L&&relyOnTime!=0L){
            double rr = (double)relyOnTime/total*100;
            double nrr = (double)relyOnTime/total*100;
            DecimalFormat df  = new DecimalFormat("###.00");
            rs.put("relyOnTimeRate",df.format(nrr)+"%");
        }else{
            rs.put("relyOnTimeRate","0.00%");
        }

        List<Map<String,Object>> addTotal = jdbcTemplate.queryForList(addTotalSql);
        if(addTotal!=null&&addTotal.size()>0){
            Map<String,Object> addTotalMap = addTotal.get(0);
            addNumber = (Long) addTotalMap.get("total")==null?0L:(Long) addTotalMap.get("total");
        }
        //本周或月增量
        rs.put("addNumber",addNumber);

        List<Map<String,Object>> noRelyTotal = jdbcTemplate.queryForList(noRelySql);
        if(noRelyTotal!=null&&noRelyTotal.size()>0){
            Map<String,Object> noRelyTotalMap = noRelyTotal.get(0);
            noRelyNumber = (Long) noRelyTotalMap.get("total")==null?0L:(Long) noRelyTotalMap.get("total");
        }
        rs.put("noRelyNumber",noRelyNumber);
        return rs;
    }

    public JSONObject getTeamDoctorFollowupLine(String teamCode,String startDate,String endDate,String type,String doctor){
        startDate = startDate+" 00:00:00";
        endDate = endDate+" 23:59:59";
        String totalSQL ;
        String planSQL ;
        if("0".equals(type)){
            //按周
            totalSQL ="SELECT " +
                    " left(w.create_time,10) AS dateNo,COUNT(1) AS followupCount " +
                    " FROM " +
                    " wlyy_followup w " +
                    " WHERE " +
                    " w.admin_team_code =" +teamCode+
                    " AND w.doctor_code ='"+doctor+"'"+
                    " AND w.create_time >= '"+startDate+"' " +
                    " AND w.create_time <= '"+endDate+"' " +
                    " AND w.followup_class IS NOT NULL " +
                    " GROUP BY dateNo";

            planSQL ="SELECT " +
                    " ( " +
                    "  DATE_FORMAT(w.create_time, '%v') - DATE_FORMAT('2017-06-01', '%v') + 1 " +
                    " ) AS weekOfMonth,COUNT(1) AS planCount " +
                    "FROM " +
                    " wlyy_followup w " +
                    "WHERE " +
                    " w.admin_team_code =" +teamCode+
                    " AND w.doctor_code ='"+doctor+"'"+
                    " AND w.create_time >= '"+startDate+"' " +
                    " AND w.create_time <= '"+endDate+"' " +
                    " AND w.status ='2'"+
                    " AND w.followup_class IS NOT NULL " +
                    " GROUP BY weekOfMonth";
        }else{
            //按月
            totalSQL ="SELECT " +
                    " ( " +
                    "  DATE_FORMAT(w.create_time, '%v') - DATE_FORMAT('2017-06-01', '%v') + 1 " +
                    " ) AS weekOfMonth,COUNT(1) AS followupCount " +
                    " FROM " +
                    " wlyy_followup w " +
                    " WHERE " +
                    " w.admin_team_code =" +teamCode+
                    " AND w.doctor_code ='"+doctor+"'"+
                    " AND w.create_time >= '"+startDate+"' " +
                    " AND w.create_time <= '"+endDate+"' " +
                    " AND w.followup_class IS NOT NULL " +
                    " GROUP BY weekOfMonth";
            planSQL = "SELECT " +
                    " ( " +
                    "  DATE_FORMAT(w.create_time, '%v') - DATE_FORMAT('2017-06-01', '%v') + 1 " +
                    " ) AS weekOfMonth,COUNT(1) AS followupCount " +
                    " FROM " +
                    " wlyy_followup w " +
                    " WHERE " +
                    " w.admin_team_code =" +teamCode+
                    " AND w.doctor_code ='"+doctor+"'"+
                    " AND w.create_time >= '"+startDate+"' " +
                    " AND w.create_time <= '"+endDate+"' " +
                    " AND w.status ='2'"+
                    " AND w.followup_class IS NOT NULL " +
                    " GROUP BY weekOfMonth";
        }
        List<Map<String,Object>> totalList = jdbcTemplate.queryForList(totalSQL);
        List<Map<String,Object>> planList = jdbcTemplate.queryForList(planSQL);
        JSONObject rs = new JSONObject();
        rs.put("totalLine",totalList);
        rs.put("planLine",planList);
        return rs;
    }

    public JSONObject getTeamFollowupLine(String teamCode,String startDate,String endDate,String type){
        startDate = startDate+" 00:00:00";
        endDate = endDate+" 23:59:59";
        String totalSQL ;
        String planSQL ;
        if("0".equals(type)){
            //按周
            totalSQL ="SELECT " +
                    " left(w.create_time,10) AS dateNo,COUNT(1) AS followupCount " +
                    " FROM " +
                    " wlyy_followup w " +
                    " WHERE " +
                    " w.admin_team_code =" +teamCode+
                    " AND w.create_time >= '"+startDate+"' " +
                    " AND w.create_time <= '"+endDate+"' " +
                    " AND w.followup_class IS NOT NULL " +
                    " GROUP BY dateNo";

            planSQL ="SELECT " +
                    " ( " +
                    "  DATE_FORMAT(w.create_time, '%v') - DATE_FORMAT('2017-06-01', '%v') + 1 " +
                    " ) AS weekOfMonth,COUNT(1) AS planCount " +
                    "FROM " +
                    " wlyy_followup w " +
                    "WHERE " +
                    " w.admin_team_code =" +teamCode+
                    " AND w.create_time >= '"+startDate+"' " +
                    " AND w.create_time <= '"+endDate+"' " +
                    " AND w.status ='2'"+
                    " AND w.followup_class IS NOT NULL " +
                    " GROUP BY weekOfMonth";
        }else{
            //按月
            totalSQL ="SELECT " +
                    " ( " +
                    "  DATE_FORMAT(w.create_time, '%v') - DATE_FORMAT('2017-06-01', '%v') + 1 " +
                    " ) AS weekOfMonth,COUNT(1) AS followupCount " +
                    " FROM " +
                    " wlyy_followup w " +
                    " WHERE " +
                    " w.admin_team_code =" +teamCode+
                    " AND w.create_time >= '"+startDate+"' " +
                    " AND w.create_time <= '"+endDate+"' " +
                    " AND w.followup_class IS NOT NULL " +
                    " GROUP BY weekOfMonth";
            planSQL = "SELECT " +
                    " ( " +
                    "  DATE_FORMAT(w.create_time, '%v') - DATE_FORMAT('2017-06-01', '%v') + 1 " +
                    " ) AS weekOfMonth,COUNT(1) AS followupCount " +
                    " FROM " +
                    " wlyy_followup w " +
                    " WHERE " +
                    " w.admin_team_code =" +teamCode+
                    " AND w.create_time >= '"+startDate+"' " +
                    " AND w.create_time <= '"+endDate+"' " +
                    " AND w.status ='2'"+
                    " AND w.followup_class IS NOT NULL " +
                    " GROUP BY weekOfMonth";
        }
        List<Map<String,Object>> totalList = jdbcTemplate.queryForList(totalSQL);
        List<Map<String,Object>> planList = jdbcTemplate.queryForList(planSQL);
        JSONObject rs = new JSONObject();
        rs.put("totalLine",totalList);
        rs.put("planLine",planList);
        return rs;
    }

    public JSONArray getDoctorTeamFolList(String startDate,String endDate,String teamCode,String sort,String sortType){
        startDate = startDate+" 00:00:00";
        endDate = endDate+" 23:59:59";
        String totalSQL = "SELECT " +
                " IFNULL(c.followupCount,0) AS followupCount, " +
                " d.`code` AS doctorCode, " +
                " d.`name` AS name " +
                " FROM " +
                " wlyy_admin_team_member m " +
                " LEFT JOIN ( " +
                " SELECT " +
                "  w.doctor_code, " +
                "  w.doctor_name, " +
                "  COUNT(1) AS followupCount " +
                " FROM " +
                "  wlyy_followup w " +
                " WHERE " +
                " w.admin_team_code =" +teamCode+
                " AND w.create_time >= '"+startDate+"' " +
                " AND w.create_time <= '"+endDate+"' " +
                " AND w.followup_class IS NOT NULL " +
                " GROUP BY " +
                "  w.doctor_code " +
                " ) c ON c.doctor_code =m.doctor_code, " +
                " wlyy_doctor d " +
                " WHERE  " +
                "  d.`code` = m.doctor_code " +
                " AND m.available = 1 " +
                " AND m.team_id =" +teamCode ;
        if("0".equals(sort)){
            totalSQL =totalSQL+" ORDER BY followupCount DESC";
        }else{
            totalSQL =totalSQL+" ORDER BY followupCount ASC";
        }
        return null;
    }
}
