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

import com.yihu.wlyy.entity.address.Town;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
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.entity.statistics.WlyyQuotaResult;
import com.yihu.wlyy.job.Constant;
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.apache.shiro.authc.ExcessiveAttemptsException;
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.BeanPropertyRowMapper;
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.ParseException;
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(String year) throws Exception {
        List<PopulationBase> peopleNums = peopleNumDao.findByYear(Integer.valueOf(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 startDate, 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 (StringUtils.isNoneEmpty(startDate)) {
            sql += " and quota_date >= '" + startDate + "'";
        }

        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, 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, 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, String year) 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 + "'";
        }
        //如果year有值 就按照年度来查询 即2017年 就是大于2017-06-30
        if (!org.springframework.util.StringUtils.isEmpty(year)) {
            sql += " and quota_date > '" + year + "-06-30' ";
        }

        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, 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")) {
                    if (org.springframework.util.StringUtils.isEmpty(year)) {
                        year = Constant.getNowYear();
                    }
                    PopulationBase peopleNum = getPopulationBase(map.get("code").toString(), 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());
                    }
                }
            }

            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, 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 = 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(level,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(level,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(level,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(level,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(level,rely, total, onRely));

        return result;
    }

    /**
     * 统计
     * 根据总数,未回复数,回复数统计,合并结果集及排序
     *
     * @param rely
     * @param total
     * @param onRely
     * @return
     */
    public List<Map<String, Object>> getCoutList(Integer level,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);
        }
        if(level==1){
            statisticsAllService.translateTeamLeaderName(resultMaps);
        }
        //根据为回复数排序
        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, 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, 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 >0 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_team c,wlyy_evaluate_score s  " +
                " WHERE " +
                " c.consult = s.consult  " +
                " AND c.czrq >= '" + startDate + "' " +
                " AND c.czrq <= '" + endDate + "' " +
                " AND c.admin_team_code =" + 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 + " 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('" + startDate + "','%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 + " 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;
    }

    /**
     * 查询续签约
     *
     * @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_log f " +
                    " WHERE " +
                    " f.apply_date >= '" + startDate + "  00:00:00' " +
                    " AND f.apply_date <= '" + endDate + "  23:59:59' " +
                    " AND f.old_admin_team_id = f.admin_team_id" +
                    " AND f.admin_team_id = " + id +
                    " GROUP BY " +
                    " LEFT (f.apply_date, 10)";
            //按月
        } else {
            sql = "SELECT " +
                    " (DATE_FORMAT(f.apply_date,'%v')-DATE_FORMAT('" + startDate + "','%v')+1) AS weekOfMonth, " +
                    " count(1) AS signCount " +
                    " FROM " +
                    " wlyy_sign_family_renew_log f " +
                    " WHERE " +
                    " f.apply_date >= '" + startDate + "  00:00:00' " +
                    " AND f.apply_date <= '" + endDate + " 23:59:59' " +
                    " AND f.old_admin_team_id = f.admin_team_id" +
                    " AND f.admin_team_id = " + 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 getReyStatbyTeamNow(String doctor, String startDate, String endDate, String isNow) {
        AdminTeam admin = adminTeamDao.findByLeaderCode(doctor);
        if (admin == null) {
            throw new RuntimeException("未找到团队信息");
        }
        String imDataBaseName = SystemConf.getInstance().getImDataBaseName();
        startDate = startDate + " 00:00:00";
        endDate = endDate + " 23:59:59";
        Long id = admin.getId();
        String totalSql = "SELECT " +
                "  COUNT(1) total " +
                "  FROM " +
                "  " + imDataBaseName + ".Topics t, " +
                "  " + imDataBaseName + ".Participants p, " +
                "  " + imDataBaseName + ".Doctors d, " +
                "  Wlyy_Consult_Team c, " +
                "  " + imDataBaseName + ".Patients s " +
                "  WHERE " +
                "  d.id = p.participant_id " +
                " AND c.consult = t.id " +
                " AND c.patient = s.id " +
                " AND p.session_id = t.session_id " +
                " AND c.admin_team_code =" + id +
                " AND t.create_time >= '" + startDate + "' " +
                " AND t.create_time <= '" + endDate + "'";
        List<Map<String, Object>> totalList = jdbcTemplate.queryForList(totalSql);
        Long totalCount = 0L;
        if (totalList != null && totalList.size() > 0) {
            Map<String, Object> total = totalList.get(0);
            totalCount = (Long) total.get("total");
        }
        String noReySql = "SELECT " +
                "  COUNT(1) noRey " +
                "  FROM " +
                "  " + imDataBaseName + ".Topics t, " +
                "  " + imDataBaseName + ".Participants p, " +
                "  " + imDataBaseName + ".Doctors d, " +
                "  Wlyy_Consult_Team c, " +
                "  " + imDataBaseName + ".Patients s " +
                "  WHERE " +
                "  d.id = p.participant_id " +
                " AND c.consult = t.id " +
                " AND c.patient = s.id " +
                " AND t. STATUS <> 10 " +
                " AND t.`reply` = 0 " +
                " AND p.session_id = t.session_id " +
                " AND c.admin_team_code =" + id +
                " AND t.create_time >= '" + startDate + "' " +
                " AND t.create_time <= '" + endDate + "'";
        List<Map<String, Object>> noReyList = jdbcTemplate.queryForList(noReySql);
        Long noReyCount = 0L;
        if (noReyList != null && noReyList.size() > 0) {
            Map<String, Object> noRey = noReyList.get(0);
            noReyCount = (Long) noRey.get("noRey");
        }
        JSONObject rs = new JSONObject();
        rs.put("onReyCount", noReyCount);
        rs.put("totalCount", totalCount);
        return rs;
    }

    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 + "'";

        List<Map<String, Object>> noRelyList = jdbcTemplate.queryForList(noRelysql);
        Long noRelystartCount = 0L;
        Long totalstartCount = 0L;
        if (noRelyList != null && noRelyList.size() > 0) {
            Map<String, Object> noRelyMap = noRelyList.get(0);
            noRelystartCount = Long.parseLong((String) noRelyMap.get("result"));
        }
        List<Map<String, Object>> totalList = jdbcTemplate.queryForList(totalsql);
        if (totalList != null && totalList.size() > 0) {
            Map<String, Object> totalMap = totalList.get(0);
            totalstartCount = Long.parseLong((String) totalMap.get("result"));
        }

        Long noRelyEndCount = 0L;
        Long totalEndCount = 0L;
        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 + "'";
            List<Map<String, Object>> noRelyEndList = jdbcTemplate.queryForList(noRelyEndsql);
            if (noRelyEndList != null && noRelyEndList.size() > 0) {
                Map<String, Object> noRelyEndMap = noRelyEndList.get(0);
                noRelyEndCount = Long.parseLong((String) noRelyEndMap.get("result"));
            }
            List<Map<String, Object>> totalEndList = jdbcTemplate.queryForList(totalEndsql);
            if (totalEndList != null && totalEndList.size() > 0) {
                Map<String, Object> totalEndMap = totalEndList.get(0);
                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) {
        String imDataBaseName = SystemConf.getInstance().getImDataBaseName();
//        startDate = startDate + " 00:00:00";
//        endDate = endDate + " 23:59:59";
        //咨询量
        String consult_sql = "SELECT " +
                "  COUNT(1) consultCount " +
                "  FROM " +
                "  " + imDataBaseName + ".Topics t, " +
                "  " + imDataBaseName + ".Participants p, " +
                "  " + imDataBaseName + ".Doctors d, " +
                "  Wlyy_Consult_Team c, " +
                "  " + imDataBaseName + ".Patients s " +
                "  WHERE " +
                "  d.id = p.participant_id " +
                " AND c.consult = t.id " +
                " AND c.patient = s.id " +
                " AND p.session_id = t.session_id " +
                " AND c.admin_team_code =" + id +
                " AND t.create_time >= '" + startDate + "' " +
                " AND t.create_time <= '" + endDate + "'";
        //获取咨詢數
        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 + "' ";
        //随访数目
        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_evaluate_score s ,wlyy_consult_team t " +
                    " WHERE  " +
                    "  s.consult = t.consult " +
                    " AND  " +
                    " 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_evaluate_score s,wlyy_consult_team t " +
                    " WHERE  " +
                    "  s.consult = t.consult " +
                    " AND  " +
                    " 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 JSONObject checkDoctorIsTeamleader(String doctor) {
        AdminTeam team = adminTeamDao.findByLeaderCode(doctor);
        if (team != null) {
            return new JSONObject(team);
        }
        return null;
    }

    /**
     * 获取团队月或周咨询未回复和总数折线图
     *
     * @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(t.create_time,10) AS dateNo, COUNT(1) AS noRely  " +
                    " FROM " +
                    "  " + imDataBaseName + ".Topics t, " +
                    "  " + imDataBaseName + ".Participants p, " +
                    "  " + imDataBaseName + ".Doctors d, " +
                    "  Wlyy_Consult_Team c, " +
                    "  " + imDataBaseName + ".Patients s " +
                    " WHERE " +
                    "  d.id = p.participant_id " +
                    " AND c.consult = t.id " +
                    " AND c.patient = s.id " +
                    " AND t. STATUS <> 10 " +
                    " AND t.`reply` = 0 " +
                    " AND p.session_id = t.session_id " +
                    " AND c.admin_team_code = " + teamCode +
                    " AND t.create_time >= '" + startDate + "' " +
                    " AND t.create_time <= '" + endDate + "' " +
                    " GROUP BY dateNo";

            totalSql = "SELECT " +
                    "  left(t.create_time,10) AS dateNo, COUNT(1) total " +
                    " FROM " +
                    "  " + imDataBaseName + ".Topics t, " +
                    "  " + imDataBaseName + ".Participants p, " +
                    "  " + imDataBaseName + ".Doctors d, " +
                    "  Wlyy_Consult_Team c, " +
                    "  " + imDataBaseName + ".Patients s " +
                    " WHERE " +
                    "  d.id = p.participant_id " +
                    " AND c.consult = t.id " +
                    " AND c.patient = s.id " +
                    " AND p.session_id = t.session_id " +
                    " AND c.admin_team_code = " + teamCode +
                    " AND t.create_time >= '" + startDate + "' " +
                    " AND t.create_time <= '" + endDate + "' " +
                    " GROUP BY dateNo";
        } else {
            //按月统计
            sql = "SELECT " +
                    "  (DATE_FORMAT(t.create_time, '%v') - DATE_FORMAT('" + startDate + "', '%v') + 1) AS weekOfMonth, " +
                    "  COUNT(1) AS noRely " +
                    "  FROM " +
                    "  " + imDataBaseName + ".Topics t, " +
                    "  " + imDataBaseName + ".Participants p, " +
                    "  " + imDataBaseName + ".Doctors d, " +
                    "  Wlyy_Consult_Team c, " +
                    "  " + imDataBaseName + ".Patients s " +
                    "  WHERE " +
                    "  d.id = p.participant_id " +
                    "  AND c.consult = t.id " +
                    "  AND c.patient = s.id " +
                    "  AND p.session_id = t.session_id " +
                    "  AND c.admin_team_code = " + teamCode +
                    "  AND t. STATUS <> 10  " +
                    "  AND t.`reply` = 0  " +
                    "  AND t.create_time >= '" + startDate + "' " +
                    "  AND t.create_time <= '" + endDate + "' " +
                    "  GROUP BY weekOfMonth";
            totalSql = "SELECT " +
                    "  (DATE_FORMAT(t.create_time, '%v') - DATE_FORMAT('" + startDate + "', '%v') + 1) AS weekOfMonth, " +
                    "  COUNT(1) AS total " +
                    "  FROM " +
                    "  " + imDataBaseName + ".Topics t, " +
                    "  " + imDataBaseName + ".Participants p, " +
                    "  " + imDataBaseName + ".Doctors d, " +
                    "  Wlyy_Consult_Team c, " +
                    "  " + imDataBaseName + ".Patients s " +
                    "  WHERE " +
                    "  d.id = p.participant_id " +
                    "  AND c.consult = t.id " +
                    "  AND c.patient = s.id " +
                    "  AND p.session_id = t.session_id " +
                    "  AND c.admin_team_code = " + teamCode +
                    "  AND t.create_time >= '" + startDate + "' " +
                    "  AND t.create_time <= '" + endDate + "' " +
                    "  GROUP BY weekOfMonth";
        }

        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(t.create_time,10) AS dateNo, COUNT(1) AS noRely " +
                    " FROM " +
                    "  " + imDataBaseName + ".Topics t, " +
                    "  " + imDataBaseName + ".Participants p, " +
                    "  " + imDataBaseName + ".Doctors d, " +
                    "  Wlyy_Consult_Team c, " +
                    "  " + imDataBaseName + ".Patients s " +
                    " WHERE " +
                    "  d.id = p.participant_id " +
                    " AND c.consult = t.id " +
                    " AND c.patient = s.id " +
                    " AND t. STATUS <> 10 " +
                    " AND t.`reply` = 0 " +
                    " AND p.session_id = t.session_id " +
                    " AND d.id ='" + doctor + "'" +
                    " AND c.admin_team_code = " + teamCode +
                    " AND t.create_time >= '" + startDate + "' " +
                    " AND t.create_time <= '" + endDate + "' " +
                    " GROUP BY dateNo";

            totalSql = "SELECT " +
                    "  left(t.create_time,10) AS dateNo, COUNT(1) total " +
                    " FROM " +
                    "  " + imDataBaseName + ".Topics t, " +
                    "  " + imDataBaseName + ".Participants p, " +
                    "  " + imDataBaseName + ".Doctors d, " +
                    "  Wlyy_Consult_Team c, " +
                    "  " + imDataBaseName + ".Patients s " +
                    " WHERE " +
                    "  d.id = p.participant_id " +
                    " AND c.consult = t.id " +
                    " AND c.patient = s.id " +
                    " AND p.session_id = t.session_id " +
                    " AND d.id ='" + doctor + "'" +
                    " AND c.admin_team_code = " + teamCode +
                    " AND t.create_time >= '" + startDate + "' " +
                    " AND t.create_time <= '" + endDate + "' " +
                    " GROUP BY dateNo";
        } else {
            //按月统计
            sql = "SELECT " +
                    "  (DATE_FORMAT(t.create_time, '%v') - DATE_FORMAT('" + startDate + "', '%v') + 1) AS weekOfMonth, " +
                    "  COUNT(1) AS noRely " +
                    "  FROM " +
                    "  " + imDataBaseName + ".Topics t, " +
                    "  " + imDataBaseName + ".Participants p, " +
                    "  " + imDataBaseName + ".Doctors d, " +
                    "  Wlyy_Consult_Team c, " +
                    "  " + imDataBaseName + ".Patients s " +
                    "  WHERE " +
                    "  d.id = p.participant_id " +
                    "  AND c.consult = t.id " +
                    "  AND c.patient = s.id " +
                    "  AND p.session_id = t.session_id " +
                    "  AND c.admin_team_code = " + teamCode +
                    "  AND d.id ='" + doctor + "'" +
                    "  AND t. STATUS <> 10  " +
                    "  AND t.`reply` = 0  " +
                    "  AND t.create_time >= '" + startDate + "' " +
                    "  AND t.create_time <= '" + endDate + "' " +
                    "  GROUP BY weekOfMonth";
            totalSql = "SELECT " +
                    "  (DATE_FORMAT(t.create_time, '%v') - DATE_FORMAT('" + startDate + "', '%v') + 1) AS weekOfMonth, " +
                    "  COUNT(1) AS total " +
                    "  FROM " +
                    "  " + imDataBaseName + ".Topics t, " +
                    "  " + imDataBaseName + ".Participants p, " +
                    "  " + imDataBaseName + ".Doctors d, " +
                    "  Wlyy_Consult_Team c, " +
                    "  " + imDataBaseName + ".Patients s " +
                    "  WHERE " +
                    "  d.id = p.participant_id " +
                    "  AND c.consult = t.id " +
                    "  AND c.patient = s.id " +
                    "  AND p.session_id = t.session_id " +
                    "  AND d.id ='" + doctor + "'" +
                    "  AND c.admin_team_code = " + teamCode +
                    "  AND t.create_time >= '" + startDate + "' " +
                    "  AND t.create_time <= '" + endDate + "' " +
                    "  GROUP BY weekOfMonth";
        }

        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 sortType) {
        String imDataBaseName = SystemConf.getInstance().getImDataBaseName();
        startDate = startDate + " 00:00:00";
        endDate = endDate + " 23:59:59";
        // 未回复咨询总量
        String onReySQL = "SELECT " +
                " IFNULL(c.total,0) AS noRely, " +
                " d.code AS doctorCode, " +
                " d.name  " +
                " FROM " +
                " wlyy_doctor d, " +
                " wlyy_admin_team_member m " +
                "  " +
                " LEFT JOIN ( " +
                " SELECT " +
                "  COUNT(1) total, " +
                "  d.`name`, " +
                "  d.id " +
                " FROM " +
                "  " + imDataBaseName + ".Topics t, " +
                "  " + imDataBaseName + ".Participants p, " +
                "  " + imDataBaseName + ".Doctors d, " +
                "  Wlyy_Consult_Team c, " +
                "  " + imDataBaseName + ".Patients s " +
                " WHERE " +
                "  d.id = p.participant_id " +
                " AND c.consult = t.id " +
                " AND c.patient = s.id " +
                " AND p.session_id = t.session_id " +
                " AND c.admin_team_code = " + teamCode +
                " AND t. STATUS <> 10 " +
                " AND t.`reply` = 0 " +
                " AND t.create_time >= '" + startDate + "' " +
                " AND t.create_time <= '" + endDate + "' " +
                " GROUP BY " +
                "  id " +
                " ) c ON c.id = m.doctor_code " +
                " WHERE " +
                " m.doctor_code = d.`code` " +
                " AND m.team_id = " + teamCode;
        if ("0".equals(sort)) {
            onReySQL = onReySQL + " ORDER BY noRely DESC";
        } else {
            onReySQL = onReySQL + " ORDER BY noRely ASC";
        }

        //总咨询量
        String totalSql = "SELECT " +
                " IFNULL(c.total,0) AS total, " +
                " d.code AS doctorCode, " +
                " d.name  " +
                " FROM " +
                " wlyy_doctor d, " +
                " wlyy_admin_team_member m " +
                "  " +
                " LEFT JOIN ( " +
                " SELECT " +
                "  COUNT(1) total, " +
                "  d.`name`, " +
                "  d.id " +
                " FROM " +
                "  " + imDataBaseName + ".Topics t, " +
                "  " + imDataBaseName + ".Participants p, " +
                "  " + imDataBaseName + ".Doctors d, " +
                "  Wlyy_Consult_Team c, " +
                "  " + imDataBaseName + ".Patients s " +
                " WHERE " +
                "  d.id = p.participant_id " +
                " AND c.consult = t.id " +
                " AND c.patient = s.id " +
                " AND p.session_id = t.session_id " +
                " AND c.admin_team_code = " + teamCode +
                " AND t.create_time >= '" + startDate + "' " +
                " AND t.create_time <= '" + endDate + "' " +
                " GROUP BY " +
                "  id " +
                " ) c ON c.id = m.doctor_code " +
                " WHERE " +
                " m.doctor_code = d.`code` " +
                " AND m.team_id = " + teamCode;
        if ("0".equals(sort)) {
            totalSql = totalSql + " ORDER BY total DESC";
        } else {
            totalSql = totalSql + " ORDER BY total ASC";
        }

        //结束咨询
        String endConsultSql = "SELECT " +
                " IFNULL(c.total,0) AS endRey, " +
                " d.code AS doctorCode, " +
                " d.name  " +
                " FROM " +
                " wlyy_doctor d, " +
                " wlyy_admin_team_member m " +
                "  " +
                " LEFT JOIN ( " +
                " SELECT " +
                "  COUNT(1) total, " +
                "  d.`name`, " +
                "  d.id " +
                " FROM " +
                "  " + imDataBaseName + ".Topics t, " +
                "  " + imDataBaseName + ".Participants p, " +
                "  " + imDataBaseName + ".Doctors d, " +
                "  Wlyy_Consult_Team c, " +
                "  " + imDataBaseName + ".Patients s " +
                " WHERE " +
                "  d.id = p.participant_id " +
                " AND c.consult = t.id " +
                " AND c.patient = s.id " +
                " AND p.session_id = t.session_id " +
                " AND c.admin_team_code = " + teamCode +
                " AND t.create_time >= '" + startDate + "' " +
                " AND t.create_time <= '" + endDate + "' " +
                " AND t. STATUS = 10 " +
                " GROUP BY " +
                "  id " +
                " ) c ON c.id = m.doctor_code " +
                " WHERE " +
                " m.doctor_code = d.`code` " +
                " AND m.team_id = " + teamCode;
        if ("0".equals(sort)) {
            endConsultSql = endConsultSql + " ORDER BY endRey DESC";
        } else {
            endConsultSql = endConsultSql + " ORDER BY endRey ASC";
        }

        List<Map<String, Object>> onReyList = jdbcTemplate.queryForList(onReySQL);
        Map<String, Object> onReyMap = new HashMap<>();
        //将List转换为Map降低循环层级
        if (onReyList != null && onReyList.size() > 0) {
            for (Map<String, Object> list : onReyList) {
                String code = (String) list.get("doctorCode");
                onReyMap.put(code, list);
            }
        }
        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 ("0".equals(sortType)) {
            //未回复数
            //合并结果集
            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);
        } else if ("1".equals(sortType)) {
            //总数
            //合并结果集
            if (totalList != null && totalList.size() > 0) {
                for (Map<String, Object> map : totalList) {
                    String code = (String) map.get("doctorCode");

                    Map<String, Object> t = (Map<String, Object>) onReyMap.get(code);
                    Long noRely = (Long) t.get("noRely");
                    map.put("noRely", noRely);

                    Map<String, Object> e = (Map<String, Object>) endConsultMap.get(code);
                    Long endCout = (Long) e.get("endRey");
                    map.put("endRey", endCout);
                }
            }
            return new JSONArray(totalList);
        } else {
            //结束咨询数
            //合并结果集
            if (endConsultList != null && endConsultList.size() > 0) {
                for (Map<String, Object> map : endConsultList) {
                    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> r = (Map<String, Object>) onReyMap.get(code);
                    Long noRely = (Long) r.get("noRely");
                    map.put("noRely", noRely);
                }
            }
            return new JSONArray(endConsultList);
        }
    }

    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 " +
                "  COUNT(1) total " +
                " FROM " +
                "  " + imDataBaseName + ".Topics t, " +
                "  " + imDataBaseName + ".Participants p, " +
                "  " + imDataBaseName + ".Doctors d, " +
                "  Wlyy_Consult_Team c, " +
                "  " + imDataBaseName + ".Patients s " +
                " WHERE " +
                "  d.id = p.participant_id " +
                " AND c.consult = t.id " +
                " AND c.patient = s.id " +
                " AND p.session_id = t.session_id " +
                " AND c.admin_team_code =" + teamCode +
                " AND d.id='" + doctor + "'" +
                " AND t.create_time <= '" + endDate + "'";
        //及时回复数
        String reyTotalSql = "SELECT " +
                "  COUNT(1) total " +
                " FROM " +
                "  " + imDataBaseName + ".Topics t, " +
                "  " + imDataBaseName + ".Participants p, " +
                "  " + imDataBaseName + ".Doctors d, " +
                "  Wlyy_Consult_Team c, " +
                "  " + imDataBaseName + ".Patients s " +
                " WHERE " +
                "  d.id = p.participant_id " +
                " AND c.consult = t.id " +
                " AND c.patient = s.id " +
                " AND p.session_id = t.session_id " +
                " AND t.`reply`=1 " +
                " AND c.admin_team_code =" + teamCode +
                " AND d.id='" + doctor + "'" +
                " 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 + "'";
        //本周或月增量
        String addTotalSql = "SELECT " +
                " COUNT(1) total " +
                " FROM " +
                "  " + imDataBaseName + ".Topics t, " +
                "  " + imDataBaseName + ".Participants p, " +
                "  " + imDataBaseName + ".Doctors d, " +
                "  Wlyy_Consult_Team c, " +
                "  " + imDataBaseName + ".Patients s " +
                " WHERE " +
                "  d.id = p.participant_id " +
                " AND c.consult = t.id " +
                " AND c.patient = s.id " +
                " AND p.session_id = t.session_id " +
                " AND c.admin_team_code =" + teamCode +
                " AND d.id='" + doctor + "'" +
                " AND t.create_time >= '" + startDate + "' " +
                " AND t.create_time <= '" + endDate + "'";
        //当前未回复咨询数
        String noRelySql = "SELECT " +
                " COUNT(1) total " +
                " FROM " +
                "  " + imDataBaseName + ".Topics t, " +
                "  " + imDataBaseName + ".Participants p, " +
                "  " + imDataBaseName + ".Doctors d, " +
                "  Wlyy_Consult_Team c, " +
                "  " + imDataBaseName + ".Patients s " +
                " WHERE " +
                "  d.id = p.participant_id " +
                " AND c.consult = t.id " +
                " AND c.patient = s.id " +
                " AND p.session_id = t.session_id " +
                " AND t. STATUS <> 10  " +
                " AND t.`reply` = 0  " +
                " AND c.admin_team_code =" + teamCode +
                " AND d.id='" + doctor + "'" +
                " AND t.create_time >= '" + startDate + "' " +
                " AND t.create_time <= '" + endDate + "'";

        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 = 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 = 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 = 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 = 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 + "' " +
                    " GROUP BY dateNo";

            planSQL = "SELECT " +
                    " left(w.create_time,10) AS dateNo,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'" +
                    " GROUP BY dateNo";
        } else {
            //按月
            totalSQL = "SELECT " +
                    " ( " +
                    "  DATE_FORMAT(w.create_time, '%v') - DATE_FORMAT('" + DateUtil.getFristDayOfMonth() + "', '%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 + "' " +
                    " GROUP BY weekOfMonth";
            planSQL = "SELECT " +
                    " ( " +
                    "  DATE_FORMAT(w.create_time, '%v') - DATE_FORMAT('" + DateUtil.getFristDayOfMonth() + "', '%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'" +
                    " 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 + "' " +
                    " GROUP BY dateNo";

            planSQL = "SELECT " +
                    " ( " +
                    "  DATE_FORMAT(w.create_time, '%v') - DATE_FORMAT('" + DateUtil.getFristDayOfMonth() + "', '%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'" +
                    " GROUP BY weekOfMonth";
        } else {
            //按月
            totalSQL = "SELECT " +
                    " ( " +
                    "  DATE_FORMAT(w.create_time, '%v') - DATE_FORMAT('" + DateUtil.getFristDayOfMonth() + "', '%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 + "' " +
                    " GROUP BY weekOfMonth";
            planSQL = "SELECT " +
                    " ( " +
                    "  DATE_FORMAT(w.create_time, '%v') - DATE_FORMAT('" + DateUtil.getFristDayOfMonth() + "', '%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'" +
                    " 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 <= '" + endDate + "' " +
                " 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";
        }

        String addSQL = "SELECT " +
                " IFNULL(c.followupCount,0) AS addCount, " +
                " 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 + "' " +
                " 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)) {
            addSQL = addSQL + " ORDER BY addCount DESC";
        } else {
            addSQL = addSQL + " ORDER BY addCount ASC";
        }

        String planSQL = "SELECT " +
                " IFNULL(c.followupCount,0) AS planCount, " +
                " 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.status ='2'" +
                " 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)) {
            planSQL = planSQL + " ORDER BY planCount DESC";
        } else {
            planSQL = planSQL + " ORDER BY planCount ASC";
        }

        List<Map<String, Object>> totalList = jdbcTemplate.queryForList(totalSQL);
        //降低循环层级
        Map<String, Object> totalMap = new HashMap<>();
        if (totalList != null && totalList.size() > 0) {
            for (Map<String, Object> map : totalList) {
                String code = (String) map.get("doctorCode");
                totalMap.put(code, map);
            }
        }
        List<Map<String, Object>> addList = jdbcTemplate.queryForList(addSQL);
        //降低循环层级
        Map<String, Object> addMap = new HashMap<>();
        if (addList != null && addList.size() > 0) {
            for (Map<String, Object> map : addList) {
                String code = (String) map.get("doctorCode");
                addMap.put(code, map);
            }
        }

        List<Map<String, Object>> planList = jdbcTemplate.queryForList(planSQL);
        //降低循环层级
        Map<String, Object> planMap = new HashMap<>();
        if (planList != null && planList.size() > 0) {
            for (Map<String, Object> map : planList) {
                String code = (String) map.get("doctorCode");
                planMap.put(code, map);
            }
        }

        if ("0".equals(sortType)) {
            //按总数排序
            if (totalList != null && totalList.size() > 0) {
                //以总数为基准,合并结果集
                for (Map<String, Object> map : totalList) {

                    String code = (String) map.get("doctorCode");

                    Map<String, Object> m = (Map<String, Object>) addMap.get(code);
                    if (m != null) {
                        Long addCount = (Long) m.get("addCount");
                        map.put("addCount", addCount == null ? 0L : addCount);
                    } else {
                        map.put("addCount", 0L);
                    }

                    Map<String, Object> m2 = (Map<String, Object>) planMap.get(code);
                    if (m2 != null) {
                        Long planCount = (Long) m2.get("planCount");
                        map.put("planCount", planCount);
                    } else {
                        map.put("planCount", 0L);
                    }

                }
            }
            return new JSONArray(totalList);
        } else if ("1".equals(sortType)) {
            //按增量排序
            if (addList != null && addList.size() > 0) {
                //以增量为基准,合并结果集
                for (Map<String, Object> map : addList) {

                    String code = (String) map.get("doctorCode");

                    Map<String, Object> m = (Map<String, Object>) planMap.get(code);
                    if (m != null) {
                        Long planCount = (Long) m.get("planCount");
                        map.put("planCount", planCount);
                    } else {
                        map.put("planCount", 0L);
                    }

                    Map<String, Object> m2 = (Map<String, Object>) totalMap.get(code);
                    if (m2 != null) {
                        Long followupCount = (Long) m2.get("followupCount");
                        map.put("followupCount", followupCount);
                    } else {
                        map.put("followupCount", 0L);
                    }
                }
            }
            return new JSONArray(addList);
        } else {
            //按计划量排序
            if (planList != null && planList.size() > 0) {
                //以增量为基准,合并结果集
                for (Map<String, Object> map : planList) {
                    String code = (String) map.get("doctorCode");


                    Map<String, Object> m = (Map<String, Object>) totalMap.get(code);
                    if (m != null) {
                        Long followupCount = (Long) m.get("followupCount");
                        map.put("followupCount", followupCount);
                    } else {
                        map.put("followupCount", 0L);
                    }

                    Map<String, Object> m2 = (Map<String, Object>) addMap.get(code);
                    if (m2 != null) {
                        Long addCount = (Long) m2.get("addCount");
                        map.put("addCount", addCount == null ? 0L : addCount);
                    } else {
                        map.put("addCount", 0L);
                    }
                }
            }
            return new JSONArray(planList);
        }
    }

    public JSONObject getTeamDoctorFolTitle(String teamCode, String doctor, String startDate, String endDate) {
        startDate = startDate + " 00:00:00";
        endDate = endDate + " 23:59:59";
        String totalSql = "SELECT " +
                " COUNT(1) AS followupCount " +
                " FROM " +
                " wlyy_followup w " +
                " WHERE " +
                " w.admin_team_code =" + teamCode +
                " AND w.doctor_code ='" + doctor + "' " +
                " AND w.create_time <= '" + endDate + "' ";
        String addSql = "SELECT " +
                " COUNT(1) AS addCount " +
                " 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 + "' ";
        String planSql = "SELECT " +
                " 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'";

        JSONObject rs = new JSONObject();
        List<Map<String, Object>> totalList = jdbcTemplate.queryForList(totalSql);
        if (totalList != null && totalList.size() > 0) {
            Map<String, Object> map = totalList.get(0);
            Long followupCount = (Long) map.get("followupCount");
            rs.put("followupCount", followupCount != null ? followupCount : 0L);
        }
        List<Map<String, Object>> addList = jdbcTemplate.queryForList(addSql);
        if (addList != null && addList.size() > 0) {
            Map<String, Object> map = addList.get(0);
            Long addCount = (Long) map.get("addCount");
            rs.put("addCount", addCount != null ? addCount : 0L);
        }
        List<Map<String, Object>> planList = jdbcTemplate.queryForList(planSql);
        if (planList != null && planList.size() > 0) {
            Map<String, Object> map = planList.get(0);
            Long planCount = (Long) map.get("planCount");
            rs.put("planCount", planCount != null ? planCount : 0L);
        }
        return rs;
    }

    public JSONArray getTeamResLine(String teamCode, String startDate, String endDate, String type) {
        startDate = startDate + " 00:00:00";
        endDate = endDate + " 23:59:59";
        String totalSql;
        if ("0".equals(type)) {
            //查周
            totalSql = "SELECT " +
                    " left(w.czrq,10) AS dateNo,COUNT(1) AS reservationCount " +
                    " FROM " +
                    " wlyy_patient_reservation w " +
                    " WHERE " +
                    " w.admin_team_code = " + teamCode +
                    " AND w.czrq <= '" + endDate + "' " +
                    " AND w.czrq >= '" + startDate + "' " +
                    " GROUP BY dateNo";
        } else {
            //查月
            totalSql = "SELECT " +
                    " ( " +
                    "  DATE_FORMAT(w.czrq, '%v') - DATE_FORMAT('" +startDate + "', '%v') + 1 " +
                    " ) AS weekOfMonth,COUNT(1) AS reservationCount " +
                    " FROM " +
                    " wlyy_patient_reservation w " +
                    " WHERE " +
                    " w.admin_team_code = " + teamCode +
                    " AND w.czrq <= '" + endDate + "' " +
                    " AND w.czrq >= '" + startDate + "' " +
                    " GROUP BY weekOfMonth";
        }

        List<Map<String, Object>> list = jdbcTemplate.queryForList(totalSql);
        return new JSONArray(list);
    }

    public JSONArray getTeamDoctorResLine(String teamCode, String startDate, String endDate, String type, String doctor) {
        startDate = startDate + " 00:00:00";
        endDate = endDate + " 23:59:59";
        String totalSql;
        if ("0".equals(type)) {
            //查周
            totalSql = "SELECT " +
                    " left(w.czrq,10) AS dateNo,COUNT(1) AS reservationCount " +
                    " FROM " +
                    " wlyy_patient_reservation w " +
                    " WHERE " +
                    " w.admin_team_code = " + teamCode +
                    " AND w.doctor = '" + doctor + "'" +
                    " AND w.czrq <= '" + endDate + "' " +
                    " AND w.czrq >= '" + startDate + "' " +
                    " GROUP BY dateNo";
        } else {
            //查月
            totalSql = "SELECT " +
                    " ( " +
                    "  DATE_FORMAT(w.czrq, '%v') - DATE_FORMAT('" + startDate + "', '%v') + 1 " +
                    " ) AS weekOfMonth,COUNT(1) AS reservationCount " +
                    " FROM " +
                    " wlyy_patient_reservation w " +
                    " WHERE " +
                    " w.admin_team_code = " + teamCode +
                    " AND w.doctor = '" + doctor + "'" +
                    " AND w.czrq <= '" + endDate + "' " +
                    " AND w.czrq >= '" + startDate + "' " +
                    " GROUP BY weekOfMonth";
        }

        List<Map<String, Object>> list = jdbcTemplate.queryForList(totalSql);
        return new JSONArray(list);
    }

    public JSONArray getTeamDoctorResList(String teamCode, String startDate, String endDate, String sort, String sortType) {
        startDate = startDate + " 00:00:00";
        endDate = endDate + " 23:59:59";
        String totalSql = "SELECT " +
                " IFNULL(c.reservationCount,0) AS reservationCount, " +
                " d.`code` AS doctorCode, " +
                " d.`name` AS name " +
                " FROM " +
                " wlyy_admin_team_member m " +
                " LEFT JOIN ( " +
                " SELECT " +
                " COUNT(1) AS reservationCount, " +
                " w.doctor AS doctorCode, " +
                " w.dname AS name " +
                " FROM " +
                " wlyy_patient_reservation w " +
                " WHERE " +
                " w.admin_team_code = " + teamCode +
                " AND w.czrq <= '" + endDate + "' " +
                " GROUP BY doctorCode  " +
                " ) c ON c.doctorCode =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 reservationCount DESC";
        } else {
            totalSql = totalSql + " ORDER BY reservationCount ASC";
        }
        String addSql = "SELECT " +
                " IFNULL(c.reservationCount,0) AS addCount, " +
                " d.`code` AS doctorCode, " +
                " d.`name` AS name " +
                " FROM " +
                " wlyy_admin_team_member m " +
                " LEFT JOIN ( " +
                " SELECT " +
                " COUNT(1) AS reservationCount, " +
                " w.doctor AS doctorCode, " +
                " w.dname AS name " +
                " FROM " +
                " wlyy_patient_reservation w " +
                " WHERE " +
                " w.admin_team_code = " + teamCode +
                " AND w.czrq <= '" + endDate + "' " +
                " AND w.czrq >= '" + startDate + "' " +
                " GROUP BY doctorCode  " +
                " ) c ON c.doctorCode =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)) {
            addSql = addSql + " ORDER BY addCount DESC";
        } else {
            addSql = addSql + " ORDER BY addCount ASC";
        }

        List<Map<String, Object>> totalList = jdbcTemplate.queryForList(totalSql);
        Map<String, Object> totalMap = new HashMap<>();
        if (totalList != null && totalList.size() > 0) {
            for (Map<String, Object> map : totalList) {
                String code = (String) map.get("doctorCode");
                totalMap.put(code, map);
            }
        }
        List<Map<String, Object>> addList = jdbcTemplate.queryForList(addSql);
        Map<String, Object> addMap = new HashMap<>();
        if (addList != null && addList.size() > 0) {
            for (Map<String, Object> map : addList) {
                String code = (String) map.get("doctorCode");
                addMap.put(code, map);
            }
        }
        if ("0".equals(sortType)) {
            //按总数排序
            if (totalList != null && totalList.size() > 0) {
                for (Map<String, Object> map : totalList) {
                    String code = (String) map.get("doctorCode");
                    Map<String, Object> m = (Map<String, Object>) addMap.get(code);
                    if (m != null) {
                        Long addCount = (Long) m.get("addCount");
                        map.put("addCount", addCount != null ? addCount : 0L);
                    } else {
                        map.put("addCount", 0L);
                    }
                }
            }
            return new JSONArray(totalList);
        } else {
            //按增量排序
            if (addList != null && addList.size() > 0) {
                for (Map<String, Object> map : addList) {
                    String code = (String) map.get("doctorCode");
                    Map<String, Object> m = (Map<String, Object>) totalMap.get(code);
                    if (m != null) {
                        Long reservationCount = (Long) m.get("reservationCount");
                        map.put("reservationCount", reservationCount != null ? reservationCount : 0L);
                    } else {
                        map.put("reservationCount", 0L);
                    }
                }
            }
            return new JSONArray(addList);
        }
    }

    public JSONObject getTeamDoctorResTitle(String teamCode, String doctor, String startDate, String endDate) {
        startDate = startDate + " 00:00:00";
        endDate = endDate + " 23:59:59";
        String totalSQL = "SELECT " +
                " COUNT(1) AS reservationCount " +
                " FROM " +
                " wlyy_patient_reservation w " +
                " WHERE " +
                " w.admin_team_code =  " + teamCode +
                " AND w.doctor ='" + doctor + "' " +
                " AND w.czrq <= '" + endDate + "' ";

        String addSQL = "SELECT " +
                " COUNT(1) AS addCount " +
                " FROM " +
                " wlyy_patient_reservation w " +
                " WHERE " +
                " w.admin_team_code =  " + teamCode +
                " AND w.doctor ='" + doctor + "' " +
                " AND w.czrq <= '" + endDate + "' " +
                " AND w.czrq >= '" + startDate + "'";
        JSONObject rs = new JSONObject();
        Long reservationCount = 0L;
        Long addCount = 0L;
        List<Map<String, Object>> totalList = jdbcTemplate.queryForList(totalSQL);
        if (totalList != null && totalList.size() > 0) {
            Map<String, Object> map = totalList.get(0);
            reservationCount = (Long) map.get("reservationCount");
        }
        rs.put("reservationCount", reservationCount);

        List<Map<String, Object>> addList = jdbcTemplate.queryForList(addSQL);
        if (addList != null && addList.size() > 0) {
            Map<String, Object> map = addList.get(0);
            addCount = (Long) map.get("addCount");
        }
        rs.put("addCount", addCount);

        return rs;
    }

    public JSONArray getTeamGuidLine(String teamCode, String startDate, String endDate, String type) {

        startDate = startDate + " 00:00:00";
        endDate = endDate + " 23:59:59";
        String SQL;
        if ("0".equals(type)) {
            //按周统计
            SQL = "SELECT " +
                    " left(w.create_time,10) AS dateNo, " +
                    " COUNT(1) AS guidanceCount " +
                    " FROM " +
                    " wlyy_patient_health_guidance w " +
                    " WHERE " +
                    " w.admin_team_code = " + teamCode +
                    " AND w.czrq <= '" + endDate + "' " +
                    " AND w.czrq >= '" + startDate + "' " +
                    " GROUP BY dateNo";
        } else {
            //按月统计
            SQL = "SELECT " +
                    " ( " +
                    "  DATE_FORMAT(w.czrq, '%v') - DATE_FORMAT('" + startDate + "', '%v') + 1 " +
                    " ) AS weekOfMonth, " +
                    " COUNT(1) AS guidanceCount " +
                    " FROM " +
                    " wlyy_patient_health_guidance w " +
                    " WHERE " +
                    " w.admin_team_code =" + teamCode +
                    " AND w.czrq <= '" + endDate + "' " +
                    " AND w.czrq >= '" + startDate + "' " +
                    " GROUP BY weekOfMonth";
        }
        List<Map<String, Object>> totalList = jdbcTemplate.queryForList(SQL);
        return new JSONArray(totalList);
    }

    public JSONArray getTeamDoctorGuidLine(String teamCode, String startDate, String endDate, String type, String doctor) {

        startDate = startDate + " 00:00:00";
        endDate = endDate + " 23:59:59";
        String SQL;
        if ("0".equals(type)) {
            //按周统计
            SQL = "SELECT " +
                    " left(w.create_time,10) AS dateNo, " +
                    " COUNT(1) AS guidanceCount " +
                    " FROM " +
                    " wlyy_patient_health_guidance w " +
                    " WHERE " +
                    " w.admin_team_code = " + teamCode +
                    " AND w.doctor ='" + doctor + "'" +
                    " AND w.czrq <= '" + endDate + "' " +
                    " AND w.czrq >= '" + startDate + "' " +
                    " GROUP BY dateNo";
        } else {
            //按月统计
            SQL = "SELECT " +
                    " ( " +
                    "  DATE_FORMAT(w.czrq, '%v') - DATE_FORMAT('" + startDate + "', '%v') + 1 " +
                    " ) AS weekOfMonth, " +
                    " COUNT(1) AS guidanceCount " +
                    " FROM " +
                    " wlyy_patient_health_guidance w " +
                    " WHERE " +
                    " w.admin_team_code =" + teamCode +
                    " AND w.doctor ='" + doctor + "'" +
                    " AND w.czrq <= '" + endDate + "' " +
                    " AND w.czrq >= '" + startDate + "' " +
                    " GROUP BY weekOfMonth";
        }
        List<Map<String, Object>> totalList = jdbcTemplate.queryForList(SQL);
        return new JSONArray(totalList);
    }

    public JSONArray getTeamGuidList(String teamCode, String startDate, String endDate, String sort, String sortType) {
        startDate = startDate + " 00:00:00";
        endDate = endDate + " 23:59:59";
        String totalSql = "SELECT " +
                " IFNULL(c.guidanceCount,0) AS guidanceCount, " +
                " d.`code` AS doctorCode, " +
                " d.`name` AS name " +
                " FROM " +
                " wlyy_admin_team_member m " +
                " LEFT JOIN ( " +
                " SELECT " +
                " w.doctor, " +
                " COUNT(1) AS guidanceCount " +
                " FROM " +
                " wlyy_patient_health_guidance w " +
                " WHERE " +
                " w.admin_team_code =  " + teamCode +
                " AND w.czrq <= '" + endDate + "' " +
                " AND w.czrq >= '" + startDate + "' " +
                " GROUP BY w.doctor " +
                " ) c ON c.doctor = 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 guidanceCount DESC";
        } else {
            totalSql = totalSql + " ORDER BY guidanceCount ASC";
        }

        String addSql = "SELECT " +
                " IFNULL(c.guidanceCount,0) AS addCount, " +
                " d.`code` AS doctorCode, " +
                " d.`name` AS name " +
                " FROM " +
                " wlyy_admin_team_member m " +
                " LEFT JOIN ( " +
                " SELECT " +
                " w.doctor, " +
                " COUNT(1) AS guidanceCount " +
                " FROM " +
                " wlyy_patient_health_guidance w " +
                " WHERE " +
                " w.admin_team_code =  " + teamCode +
                " AND w.czrq <= '" + endDate + "' " +
                " AND w.czrq >= '" + startDate + "' " +
                " GROUP BY w.doctor " +
                " ) c ON c.doctor = 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)) {
            addSql = addSql + " ORDER BY addCount DESC";
        } else {
            addSql = addSql + " ORDER BY addCount ASC";
        }

        List<Map<String, Object>> totalList = jdbcTemplate.queryForList(totalSql);
        Map<String, Object> totalMap = new HashMap<>();
        if (totalList != null && totalList.size() > 0) {
            for (Map<String, Object> map : totalList) {
                String code = (String) map.get("doctorCode");
                totalMap.put(code, map);
            }
        }
        List<Map<String, Object>> addList = jdbcTemplate.queryForList(addSql);
        Map<String, Object> addMap = new HashMap<>();
        if (addList != null && addList.size() > 0) {
            for (Map<String, Object> map : addList) {
                String code = (String) map.get("doctorCode");
                addMap.put(code, map);
            }
        }
        if ("0".equals(sortType)) {
            //按总数排序
            if (totalList != null && totalList.size() > 0) {
                for (Map<String, Object> map : totalList) {
                    String code = (String) map.get("doctorCode");
                    Map<String, Object> m = (Map<String, Object>) addMap.get(code);
                    if (m != null) {
                        Long addCount = (Long) m.get("addCount");
                        map.put("addCount", addCount != null ? addCount : 0L);
                    } else {
                        map.put("addCount", 0L);
                    }
                }
            }
            return new JSONArray(totalList);
        } else {
            //按增量排序
            if (addList != null && addList.size() > 0) {
                for (Map<String, Object> map : addList) {
                    String code = (String) map.get("doctorCode");
                    Map<String, Object> m = (Map<String, Object>) totalMap.get(code);
                    if (m != null) {
                        Long guidanceCount = (Long) m.get("guidanceCount");
                        map.put("guidanceCount", guidanceCount != null ? guidanceCount : 0L);
                    } else {
                        map.put("guidanceCount", 0L);
                    }
                }
            }
            return new JSONArray(addList);
        }
    }

    public JSONObject getTeamDoctorGuiTitle(String teamCode, String doctor, String startDate, String endDate) {
        startDate = startDate + " 00:00:00";
        endDate = endDate + " 23:59:59";
        String totalSQL = "SELECT " +
                " COUNT(1) AS guidanceCount " +
                " FROM " +
                " wlyy_patient_health_guidance w " +
                " WHERE " +
                " w.admin_team_code =  " + teamCode +
                " AND w.doctor ='" + doctor + "'" +
                " AND w.czrq <= '" + endDate + "'";

        String addSQL = "SELECT " +
                " COUNT(1) AS addCount " +
                " FROM " +
                " wlyy_patient_health_guidance w " +
                " WHERE " +
                " w.admin_team_code =  " + teamCode +
                " AND w.doctor ='" + doctor + "'" +
                " AND w.czrq <= '" + endDate + "' " +
                " AND w.czrq >= '" + startDate + "'";
        JSONObject rs = new JSONObject();
        Long guidanceCount = 0L;
        Long addCount = 0L;
        List<Map<String, Object>> totalList = jdbcTemplate.queryForList(totalSQL);
        if (totalList != null && totalList.size() > 0) {
            Map<String, Object> map = totalList.get(0);
            guidanceCount = (Long) map.get("guidanceCount");
        }
        rs.put("guidanceCount", guidanceCount);

        List<Map<String, Object>> addList = jdbcTemplate.queryForList(addSQL);
        if (addList != null && addList.size() > 0) {
            Map<String, Object> map = addList.get(0);
            addCount = (Long) map.get("addCount");
        }
        rs.put("addCount", addCount);

        return rs;
    }

    public JSONArray getTeamEduLine(String teamCode, String startDate, String endDate, String type) {
        startDate = startDate + " 00:00:00";
        endDate = endDate + " 23:59:59";
        String sql;

        if ("0".equals(type)) {
            //按周统计
            sql = "SELECT " +
                    " left(w.czrq,10) AS dateNo,COUNT(1) AS articleCount,count(DISTINCT w.batch_no) batchCount " +
                    " FROM " +
                    " wlyy_health_edu_article_patient w " +
                    " WHERE " +
                    " w.admin_team_code =" + teamCode +
                    " AND w.czrq <= '" + endDate + "' " +
                    " AND w.czrq >= '" + startDate + "' " +
                    " GROUP BY dateNo";
        } else {
            sql = "SELECT " +
                    " ( " +
                    "  DATE_FORMAT(w.czrq, '%v') - DATE_FORMAT('" + startDate + "', '%v') + 1 " +
                    " ) AS weekOfMonth,COUNT(1) AS articleCount,count(DISTINCT w.batch_no) batchno " +
                    "FROM " +
                    " wlyy_health_edu_article_patient w " +
                    "WHERE " +
                    " w.admin_team_code =" + teamCode +
                    " AND w.czrq <= '" + endDate + "' " +
                    " AND w.czrq >= '" + startDate + "' " +
                    "GROUP BY weekOfMonth";
        }
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return new JSONArray(list);
    }

    public JSONArray getTeamDoctorEduLine(String teamCode, String startDate, String endDate, String type, String doctor) {
        startDate = startDate + " 00:00:00";
        endDate = endDate + " 23:59:59";
        String sql;

        if ("0".equals(type)) {
            //按周统计
            sql = "SELECT " +
                    " left(w.czrq,10) AS dateNo,COUNT(1) AS articleCount,count(DISTINCT w.batch_no) batchCount " +
                    " FROM " +
                    " wlyy_health_edu_article_patient w " +
                    " WHERE " +
                    " w.admin_team_code =" + teamCode +
                    " AND w.doctor ='" + doctor + "'" +
                    " AND w.czrq <= '" + endDate + "' " +
                    " AND w.czrq >= '" + startDate + "' " +
                    " GROUP BY dateNo";
        } else {
            sql = "SELECT " +
                    " ( " +
                    "  DATE_FORMAT(w.czrq, '%v') - DATE_FORMAT('" + startDate + "', '%v') + 1 " +
                    " ) AS weekOfMonth,COUNT(1) AS articleCount,count(DISTINCT w.batch_no) batchno " +
                    "FROM " +
                    " wlyy_health_edu_article_patient w " +
                    "WHERE " +
                    " w.admin_team_code =" + teamCode +
                    " AND w.doctor ='" + doctor + "'" +
                    " AND w.czrq <= '" + endDate + "' " +
                    " AND w.czrq >= '" + startDate + "' " +
                    "GROUP BY weekOfMonth";
        }
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return new JSONArray(list);
    }

    public JSONArray getTeamEduList(String teamCode, String startDate, String endDate, String sort, String sortType) {
        startDate = startDate + " 00:00:00";
        endDate = endDate + " 23:59:59";
        String totalSql = "SELECT " +
                " IFNULL(c.articleCount,0) AS articleCount, " +
                " IFNULL(c.batchno,0) AS batchno, " +
                " d.`code` AS doctorCode, " +
                " d.`name` AS name " +
                " FROM " +
                " wlyy_admin_team_member m " +
                " LEFT JOIN ( " +
                " SELECT " +
                " COUNT(1) AS articleCount, " +
                " COUNT(DISTINCT w.batch_no) batchno, " +
                " w.doctor AS doctorCode " +
                " FROM " +
                " wlyy_health_edu_article_patient w " +
                " WHERE " +
                " w.admin_team_code =" + teamCode +
                " AND w.czrq <= '" + endDate + "' " +
                " GROUP BY doctorCode " +
                " ) c ON c.doctorCode =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)) {
            //降序
            if ("0".equals(sortType)) {
                //总人次
                totalSql = totalSql + " ORDER BY articleCount DESC";
            } else if ("2".equals(sortType)) {
                //总批次
                totalSql = totalSql + " ORDER BY batchno DESC";
            }
        } else {
            if ("0".equals(sortType)) {
                totalSql = totalSql + " ORDER BY articleCount ASC";
            } else if ("2".equals(sortType)) {
                totalSql = totalSql + " ORDER BY batchno ASC";
            }
        }
        String addSql = "SELECT " +
                " IFNULL(c.articleCount,0) AS addCount, " +
                " IFNULL(c.batchno,0) AS addBatchno, " +
                " d.`code` AS doctorCode, " +
                " d.`name` AS name " +
                " FROM " +
                " wlyy_admin_team_member m " +
                " LEFT JOIN ( " +
                " SELECT " +
                " COUNT(1) AS articleCount, " +
                " COUNT(DISTINCT w.batch_no) batchno, " +
                " w.doctor AS doctorCode " +
                " FROM " +
                " wlyy_health_edu_article_patient w " +
                " WHERE " +
                " w.admin_team_code =" + teamCode +
                " AND w.czrq <= '" + endDate + "' " +
                " AND w.czrq >= '" + startDate + "' " +
                " GROUP BY doctorCode " +
                " ) c ON c.doctorCode =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)) {
            if ("1".equals(sortType)) {
                addSql = addSql + " ORDER BY addCount DESC";
            } else if ("3".equals(sortType)) {
                addSql = addSql + " ORDER BY addBatchno DESC";
            }
        } else {
            if ("1".equals(sortType)) {
                addSql = addSql + " ORDER BY addCount ASC";
            } else if ("3".equals(sortType)) {
                addSql = addSql + " ORDER BY addBatchno ASC";
            }
        }

        List<Map<String, Object>> totalList = jdbcTemplate.queryForList(totalSql);
        Map<String, Object> totalMap = new HashMap<>();
        if (totalList != null && totalList.size() > 0) {
            for (Map<String, Object> map : totalList) {
                String code = (String) map.get("doctorCode");
                totalMap.put(code, map);
            }
        }
        List<Map<String, Object>> addList = jdbcTemplate.queryForList(addSql);
        Map<String, Object> addMap = new HashMap<>();
        if (addList != null && addList.size() > 0) {
            for (Map<String, Object> map : addList) {
                String code = (String) map.get("doctorCode");
                addMap.put(code, map);
            }
        }
        if ("0".equals(sortType) || "2".equals(sortType)) {
            //按总数排序
            if (totalList != null && totalList.size() > 0) {
                for (Map<String, Object> map : totalList) {
                    String code = (String) map.get("doctorCode");
                    Map<String, Object> m = (Map<String, Object>) addMap.get(code);
                    if (m != null) {
                        Long addCount = (Long) m.get("addCount");
                        Long addBatchno = (Long) m.get("addBatchno");
                        map.put("addCount", addCount != null ? addCount : 0L);
                        map.put("addBatchno", addBatchno != null ? addBatchno : 0L);
                    } else {
                        map.put("addCount", 0L);
                        map.put("addBatchno", 0L);
                    }
                }
            }
            return new JSONArray(totalList);
        } else {
            //按增量排序
            if (addList != null && addList.size() > 0) {
                for (Map<String, Object> map : addList) {
                    String code = (String) map.get("doctorCode");
                    Map<String, Object> m = (Map<String, Object>) totalMap.get(code);
                    if (m != null) {
                        Long articleCount = (Long) m.get("articleCount");
                        map.put("articleCount", articleCount != null ? articleCount : 0L);
                        Long batchno = (Long) m.get("batchno");
                        map.put("batchno", batchno != null ? batchno : 0L);
                    } else {
                        map.put("articleCount", 0L);
                        map.put("batchno", 0L);
                    }
                }
            }
            return new JSONArray(addList);
        }
    }

    public JSONObject getTeamDoctorEduTitle(String teamCode, String startDate, String endDate, String doctor) {
        startDate = startDate + " 00:00:00";
        endDate = endDate + " 23:59:59";
        String totalSql = "SELECT " +
                " COUNT(1) AS articleCount, " +
                " COUNT(DISTINCT w.batch_no) batchno " +
                " FROM " +
                " wlyy_health_edu_article_patient w " +
                " WHERE " +
                " w.admin_team_code =" + teamCode +
                " AND w.doctor ='" + doctor + "'" +
                " AND w.czrq <= '" + endDate + "' ";
        String addSql = "SELECT " +
                " COUNT(1) AS addCount, " +
                " COUNT(DISTINCT w.batch_no) addBatchno " +
                " FROM " +
                " wlyy_health_edu_article_patient w " +
                " WHERE " +
                " w.admin_team_code =" + teamCode +
                " AND w.doctor ='" + doctor + "'" +
                " AND w.czrq <= '" + endDate + "' " +
                " AND w.czrq >= '" + startDate + "'";
        List<Map<String, Object>> totalList = jdbcTemplate.queryForList(totalSql);
        List<Map<String, Object>> addList = jdbcTemplate.queryForList(addSql);
        JSONObject rs = new JSONObject();
        rs.put("totalList", totalList);
        rs.put("addList", addList);
        return rs;
    }


    public JSONObject getDoctorInfo(String code) {
        Doctor doctor = doctorDao.findByCode(code);
        JSONObject rs = new JSONObject();
        rs.put("doctorName", doctor.getName());
        rs.put("doctor", doctor.getCode());
        rs.put("photo", doctor.getPhoto());
        return rs;
    }

    /**
     * 获取单个数据
     *
     * @param date
     * @param level
     * @param index
     * @param area
     * @return
     */
    public WlyyQuotaResult findOneQuotaResult(String date, int level, String index, String area) {
        String sql = " select * from wlyy_quota_result w where w.quota_date ='" + date + "' and w.quato_code='" + index + "' and w.level1_type= " + level;
        if (level == 4) {
            // 市级别
            sql += " and city='" + area + "' ";
        } else if (level == 3) {
            // 区、城镇级别
            sql += " and town='" + area + "' ";
        } else if (level == 2) {
            // 机构级别
            sql += " and org_code='" + area + "' ";
        } else if (level == 1) {
            // 机构级别
            sql += " and qkdoctor_code ='" + area + "'";
        }
        List<WlyyQuotaResult> results = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WlyyQuotaResult.class));
        if (results.size() > 0) {
            return results.get(0);
        }
        return null;
    }

    public List<WlyyQuotaResult> findQuotaResults(String date, int level, String index, String area) {
        String sql = " select * from wlyy_quota_result w where w.quota_date ='" + date + "' and w.quato_code='" + index + "' and w.level1_type= " + level;
        if (level == 4) {
            // 市级别
            sql += " and city='" + area + "' ";
        } else if (level == 3) {
            // 区、城镇级别
            sql += " and town='" + area + "' ";
        } else if (level == 2) {
            // 机构级别
            sql += " and org_code='" + area + "' ";
        } else if (level == 1) {
            // 机构级别
            sql += " and qkdoctor_code ='" + area + "'";
        }
        List<WlyyQuotaResult> results = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WlyyQuotaResult.class));
        return results;
    }

    public JSONObject getRenewPercentAndChangePercent(String renewIndex, String level, String code, String year) {
        String switchIndex = "";
        if ("2".equals(level)) {
            //团队的转签
            switchIndex = "35";
        } else if ("3".equals(level)) {
            //社区的转签
            switchIndex = "35";
        } else {
            //区和市的转签
            switchIndex = "35";
        }

        JSONObject jo = new JSONObject();
        //获取时间戳
        String timeKey = redisTemplate.opsForValue().get("quota:timeKey");

        int renewNum = getLevel1NumForRedis(renewIndex, level, code, timeKey);
        //根据年度获取去年的签约数 签约指标是1
        String date = year + "-06-30";
        String index = "1";
        WlyyQuotaResult wlyyQuotaResult = findOneQuotaResult(date, Integer.valueOf(level), index, code);
        int signNum = 0;
        if (wlyyQuotaResult != null) {
            signNum = Integer.valueOf(wlyyQuotaResult.getResult());
        }
        //从redis中获取最新的转签数据  指标是37
        int switchNum = getLevel1NumForRedis(switchIndex, level, code, timeKey);
        jo.put("yesterYearSign", signNum);//去年的签约量
        jo.put("thisYearRenew", renewNum);//今年的续签量
        jo.put("thisYearSwithch", switchNum);//今年的转签量
        jo.put("renewRange", getRange(renewNum, signNum, 2));//续签率  50.00%
        jo.put("switchRange", getRange(switchNum, renewNum, 2));//转签率

        return jo;
    }


    public JSONObject getRenewAnalysis(String switchIndex, String switchIndexReson, String signIn, String signOut, String level, String code) {

        JSONObject jo = new JSONObject();
        String timeKey = redisTemplate.opsForValue().get("quota:timeKey");
        //获取转签人数
        int switchNum = getLevel1NumForRedis(switchIndex, level, code, timeKey);

        //获取转签分布
        JSONArray switchJO = getLevel2JsonObjectForRedis(switchIndexReson, level, code, timeKey);
        //获取签入人数
        int inNum = getLevel1NumForRedis(signIn, level, code, timeKey);
        //获取签出人数
        int outNum = getLevel1NumForRedis(signOut, level, code, timeKey);

        int changeTeam = getLevel1NumForRedis("31", level, code, timeKey);//夸团队的数目
        int changeHospital = getLevel1NumForRedis("32", level, code, timeKey);//夸社区的数目
        int changeTown = getLevel1NumForRedis("33", level, code, timeKey);//夸社区的数目
        int allChangeCount = changeTeam + changeHospital + changeTown; //跨团队，跨社区 跨区的分母

        jo.put("inNum", inNum);//今年的签入量
        jo.put("outNum", outNum);//今年的签出量
        jo.put("thisYearSwithch", switchNum);//今年的转签量
        jo.put("switchHealth", switchJO);//今年的服务分布
        String changeTeamNum = getRangeNoLast(changeTeam, allChangeCount, 2);//跨团队转签率
        String changeHospNum = getRangeNoLast(changeHospital, allChangeCount, 2);//跨社区转签率
        String changeTownNum = "";
        //保留两位小数
        DecimalFormat df = new DecimalFormat("######0.00");
        if (changeTown == 0) {
            changeTownNum = "0";
        } else {
            changeTownNum = df.format(100 - Double.valueOf(changeTeamNum) - Double.valueOf(changeHospNum)) + "";//跨区转签率，解决算出来可能不是100%的问题 用扣的
        }

        jo.put("switchTeam", changeTeamNum + "%");//今年的转签量
        jo.put("switchHospital", changeHospNum + "%");//今年的转签量
        jo.put("switchTown", changeTownNum + "%");//今年的转签量
        return jo;
    }


    //-==============================================通用方法=============================================

    /**
     * 通用的方法 获取一级维度的数据
     *
     * @param index
     * @param level
     * @param code
     * @param timeKey
     * @return
     */
    private int getLevel1NumForRedis(String index, String level, String code, String timeKey) {
        String key37 = "quota:" + index + ":" + level + ":" + code + ":" + timeKey;
        JSONObject switchJo = new JSONObject(redisTemplate.opsForValue().get(key37));
        return switchJo.getInt("num");
    }

    /**
     * 通用的方法 获取二级维度的数据列表
     *
     * @param index
     * @param level
     * @param code
     * @param timeKey
     * @return
     */
    private JSONArray getLevel2JsonObjectForRedis(String index, String level, String code, String timeKey) {
        String key37 = "quota:" + index + ":" + level + ":" + code + ":" + timeKey;
        JSONArray switchJo = new JSONArray(redisTemplate.opsForValue().get(key37));
        return switchJo;
    }

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

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

    public JSONObject getConsultingTitleAll(Integer level, String area, String year) {

        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);
        //查找去年6月30号的及时回复数，然后累加
        relyObject.put("num", relyObject.getInt("num") + getSizeByIndexLevelArea(year, "23", level, area));

        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);
        //查找去年6月30号的咨询总数，然后累加
        totalObject.put("num", totalObject.getInt("num") + getSizeByIndexLevelArea(year, "25", level, area));

        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);
        //查找去年6月30号的未回复数，然后累加
        onRelyObject.put("num", onRelyObject.getInt("num") + getSizeByIndexLevelArea(year, "22", level, area));
        JSONArray onRely = new JSONArray();
        onRely.put(onRelyObject);

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

        return result;
    }

    public JSONObject getConsultingTitleWithYear(Integer level, String area, String year) {

        JSONObject result = new JSONObject();
        JSONObject relyObject = new JSONObject();
        //查找去年6月30号的及时回复数
        WlyyQuotaResult wlyyQuotaResult = findOneQuotaResult((Integer.valueOf(year) + 1) + "-06-30", level, "23", area);
        if (wlyyQuotaResult != null) {
            relyObject.put("name", getNameByLevel(wlyyQuotaResult, level));
            relyObject.put("code", getCodeByLevel(wlyyQuotaResult, level));
            relyObject.put("num", Integer.valueOf(wlyyQuotaResult.getResult()));
        }

        JSONArray rely = new JSONArray();
        rely.put(relyObject);
        JSONObject totalObject = new JSONObject();
        //查找去年6月30号的咨询总数
        wlyyQuotaResult = findOneQuotaResult("2017-06-30", level, "25", area);
        if (wlyyQuotaResult != null) {
            totalObject.put("name", getNameByLevel(wlyyQuotaResult, level));
            totalObject.put("code", getCodeByLevel(wlyyQuotaResult, level));
            totalObject.put("num", Integer.valueOf(wlyyQuotaResult.getResult()));
        }
        JSONArray total = new JSONArray();
        total.put(totalObject);
        //未回复数
        JSONObject onRelyObject = new JSONObject();
        //查找去年6月30号的未回复数
        wlyyQuotaResult = findOneQuotaResult("2017-06-30", level, "22", area);
        if (wlyyQuotaResult != null) {
            onRelyObject.put("name", getNameByLevel(wlyyQuotaResult, level));
            onRelyObject.put("code", getCodeByLevel(wlyyQuotaResult, level));
            onRelyObject.put("num", Integer.valueOf(wlyyQuotaResult.getResult()));
        }
        JSONArray onRely = new JSONArray();
        onRely.put(onRelyObject);

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

        return result;
    }


    public JSONObject getCoutListByTimeAll(String level, String area) {
        JSONObject result = new JSONObject();
        if (StringUtils.isNotBlank(level) && StringUtils.isNotBlank(area)) {
            String relyVal = findLevel1IndexInRedis("24", level, area);
            JSONArray array = new JSONArray(relyVal);
            result.put("resultList", array);
        }
        return result;
    }

    public JSONObject getCoutListByTimeYear(String level, String area, String year) {
        JSONObject result = new JSONObject();
        List<WlyyQuotaResult> wlyyQuotaResult = findQuotaResults((Integer.valueOf(year) + 1) + "-06-30", Integer.valueOf(level), "24", area);
        JSONArray jo = new JSONArray();
        if (wlyyQuotaResult != null && wlyyQuotaResult.size() > 0) {
            wlyyQuotaResult.stream().forEach(one -> {
                JSONObject temp1 = new JSONObject();
                temp1.put("name", one.getLevel2TypeName());
                temp1.put("code", getCodeByLevel(one, Integer.valueOf(level)));
                temp1.put("num", Integer.valueOf(one.getResult()));
                jo.put(temp1);
            });
        }
        result.put("resultList", jo);
        return result;
    }

    public JSONObject getConsultingStatisticsListAll(Integer level, String area, String lowlevel, String year) 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);
                //累加去年的数目
                getConsultingStatisticsListAllAdd(rely, "23", level, area, "3", year);
                //咨询总数
                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(level,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(level,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(level,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(level,rely, total, noRely);
            statisticsAllService.translateTeamLeaderName(rs);
            result.put("resultList", rs);
        }
        return result;
    }


    public JSONObject getConsultingStatisticsListYear(Integer level, String area, String lowlevel, String year) {
        JSONObject result = new JSONObject();
        Integer coutYear = Integer.parseInt(year) + 1;

        //及时回复数
        JSONArray rely = getQuotaList(level, lowlevel, area, coutYear, 23);
        if (rely == null) {
            return null;
        }
        //咨询总数
        JSONArray total = getQuotaList(level, lowlevel, area, coutYear, 25);
        if (total == null) {
            return null;
        }
        //未回复数
        JSONArray onRely = getQuotaList(level, lowlevel, area, coutYear, 22);
        if (total == null) {
            return null;
        }
        if(lowlevel==null){
            lowlevel=(level-1)+"";
        }
        result.put("resultList", getCoutList(Integer.valueOf(lowlevel),rely, total, onRely));
        return result;
    }

    public JSONObject getTeamRenewChangeLine(String teamCode, String startDate, String endDate, String type) {
        startDate = startDate + " 00:00:00";
        endDate = endDate + " 23:59:59";
        String inSql;
        String outSql;
        if ("0".equals(type)) {
            inSql = "SELECT left(r.apply_date,10) AS dateNo,COUNT(1) AS inCount FROM wlyy_sign_family_renew_log r  " +
                    " WHERE r.admin_team_id ='" + teamCode + "' " +
                    " AND r.apply_date >= '" + startDate + "' " +
                    " AND r.apply_date <='" + endDate + "' " +
                    " AND r.old_admin_team_id <> r.admin_team_id " +
                    " GROUP BY dateNo ";
            outSql = "SELECT left(r.apply_date,10) AS dateNo,COUNT(1) AS outCount FROM wlyy_sign_family_renew_log r  " +
                    " WHERE r.old_admin_team_id ='" + teamCode + "' " +
                    " AND r.apply_date >= '" + startDate + "' " +
                    " AND r.apply_date <='" + endDate + "' " +
                    " AND r.old_admin_team_id <> r.admin_team_id " +
                    " GROUP BY dateNo ";
        } else {
            inSql = "SELECT ( " +
                    "  DATE_FORMAT(r.apply_date, '%v') - DATE_FORMAT('" + startDate + "', '%v') + 1 " +
                    " ) AS weekOfMonth,COUNT(1) AS inCount FROM wlyy_sign_family_renew_log r  " +
                    " WHERE r.admin_team_id ='" + teamCode + "'  " +
                    " AND r.apply_date >= '" + startDate + "'  " +
                    " AND r.apply_date <='" + endDate + "'  " +
                    " AND r.old_admin_team_id <> r.admin_team_id " +
                    " GROUP BY weekOfMonth ";
            outSql = "SELECT ( " +
                    "  DATE_FORMAT(r.apply_date, '%v') - DATE_FORMAT('" + startDate + "', '%v') + 1 " +
                    " ) AS weekOfMonth,COUNT(1) AS outCount FROM wlyy_sign_family_renew_log r  " +
                    " WHERE r.old_admin_team_id ='" + teamCode + "'  " +
                    " AND r.apply_date >= '" + startDate + "'  " +
                    " AND r.apply_date <='" + endDate + "'  " +
                    " AND r.old_admin_team_id <> r.admin_team_id " +
                    " GROUP BY weekOfMonth ";
        }
        JSONObject rs = new JSONObject();
        List<Map<String, Object>> inList = jdbcTemplate.queryForList(inSql);
        rs.put("inLine", inList);
        List<Map<String, Object>> outList = jdbcTemplate.queryForList(outSql);
        rs.put("outLine", outList);

        return rs;
    }
    //-----------------------------------通用方法-------------------------------

    /**
     * @param rely     从redis查询出来的列表
     * @param index    指标code
     * @param level    父level
     * @param area     父code
     * @param children 子level
     * @param year     年份
     */
    public void getConsultingStatisticsListAllAdd(JSONArray rely, String index, Integer level, String area, String children, String year) {
        String sql = "";
    }

    /**
     * 得到某个指标的之前全部的数目
     *
     * @param year
     * @param index
     * @param level
     * @param area
     * @return
     */
    private Integer getSizeByIndexLevelArea(String year, String index, Integer level, String area) {
        //查找去年6月30号的及时回复数，然后累加
        WlyyQuotaResult wlyyQuotaResult = findOneQuotaResult("2017-06-30", level, index, area);
        if (wlyyQuotaResult != null) {
            return Integer.valueOf(wlyyQuotaResult.getResult());
        }
        return null;
    }

    private String findLevel1IndexInRedis(String index, String level, String area) {
        String timeKey = redisTemplate.opsForValue().get("quota:timeKey");
        String relyVal = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + timeKey);
        return relyVal;
    }

    private String getNameByLevel(WlyyQuotaResult wlyyQuotaResult, Integer level) {
        switch (level) {
            case 1: {
                return wlyyQuotaResult.getQkdoctorName();
            }
            case 2: {
                return wlyyQuotaResult.getOrgName();
            }
            case 3: {
                return wlyyQuotaResult.getTownName();
            }
            case 4: {
                return wlyyQuotaResult.getCityName();
            }
        }
        return null;
    }

    private String getCodeByLevel(WlyyQuotaResult wlyyQuotaResult, Integer level) {
        switch (level) {
            case 1: {
                return wlyyQuotaResult.getQkdoctorCode();
            }
            case 2: {
                return wlyyQuotaResult.getOrgCode();
            }
            case 3: {
                return wlyyQuotaResult.getTown();
            }
            case 4: {
                return wlyyQuotaResult.getCity();
            }
        }
        return null;
    }

    /**
     * 通用指标方法,格式返回与redis一致
     * 查询个指标
     * 1.市级-区
     * 2.市级-机构
     * 3.区级-机构
     * 4.机构-团队
     *
     * @param level
     * @param lovlevel
     * @param area
     * @param year
     * @param index
     * @return
     */
    public JSONArray getQuotaList(Integer level, String lovlevel, String area, Integer year, Integer index) {
        String sql;
        if (level == 4) {
            if (StringUtils.isBlank(lovlevel)) {
                //市 区
                sql = " SELECT t.result As num,t.town_name AS name,t.town AS code,t.create_time AS date" +
                        " FROM wlyy_quota_result t " +
                        " WHERE t.city ='" + area + "' AND t.quato_code ='" + index + "' AND t.level1_type ='3'AND t.quota_date='" + year + "-06-30'";
            } else {
                //市 机构
                sql = "SELECT t.result As num,t.org_name AS name,t.org_code AS code,t.create_time AS date" +
                        " FROM wlyy_quota_result t " +
                        " WHERE t.city ='" + area + "' AND t.quato_code ='" + index + "' AND t.level1_type ='2' AND t.quota_date='" + year + "-06-30'";
            }
        } else if (level == 3) {
            //区 机构
            sql = "SELECT t.result As num,t.org_name AS name,t.org_code AS code,t.create_time AS date " +
                    "FROM wlyy_quota_result t " +
                    "WHERE t.town ='" + area + "' AND t.quato_code ='" + index + "' AND t.level1_type ='2' AND t.quota_date='" + year + "-06-30'";
        } else {
            //机构 团队
            sql = "SELECT t.result As num,t.qkdoctor_name AS name,t.qkdoctor_code AS code,t.create_time AS date " +
                    " FROM wlyy_quota_result t " +
                    " WHERE t.org_code ='" + area + "' AND t.quato_code ='" + index + "' AND t.level1_type ='1' AND t.quota_date='" + year + "-06-30'";
        }
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        if (list != null && list.size() > 0) {
            return new JSONArray(list);
        } else {
            return null;
        }

    }

    public JSONObject getRenewPercent(String level, String area, String year) {
        String renewIndex = "";
        if ("1".equals(level)) {
            //团队的续签量
            renewIndex = "42";
        } else if ("2".equals(level)) {
            //社区的续签量
            renewIndex = "43";
        } else if ("3".equals(level)) {
            //区的续签量
            renewIndex = "44";
        } else {
            //市的续签量
            renewIndex = "29";
        }

        JSONObject jo = new JSONObject();
        //获取时间戳
        String timeKey = redisTemplate.opsForValue().get("quota:timeKey");

        int renewNum = getLevel1NumForRedis(renewIndex, level, area, timeKey);
        //根据年度获取去年的签约数 签约指标是1
        String date = year + "-06-30";
        String index = "1";
        WlyyQuotaResult wlyyQuotaResult = findOneQuotaResult(date, Integer.valueOf(level), index, area);
        int signNum = 0;
        if (wlyyQuotaResult != null) {
            signNum = Integer.valueOf(wlyyQuotaResult.getResult());
        }
        jo.put("yesterYearSign", signNum);//去年的签约量
        jo.put("thisYearRenew", renewNum);//今年的续签量
        jo.put("renewRange", getRange(renewNum, signNum, 2));//续签率  50.00%

        return jo;
    }

    public PopulationBase getPopulationBase(String code, String year) {

        String sql = "select * from wlyy_people_num where code=? and year=? ";
        List<PopulationBase> peopleNum = jdbcTemplate.query(sql, new BeanPropertyRowMapper(PopulationBase.class), code, year);
        if (peopleNum != null && peopleNum.size() > 0) {
            return peopleNum.get(0);
        } else {
            return null;
        }
    }
}

