package com.xintong.visualinspection.service.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xintong.visualinspection.bean.*;
import com.xintong.visualinspection.dao.master.*;
import com.xintong.visualinspection.pojo.StatisiticPojo;
import com.xintong.visualinspection.pojo.StatisticExUser;
import com.xintong.visualinspection.pojo.UserRankingData;
import com.xintong.visualinspection.service.ThreadTaskService;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xintong.visualinspection.dao.cluster.DepartmentDao;
import com.xintong.visualinspection.dao.cluster.UserInfoDao;
import com.xintong.visualinspection.service.BaseService;
import com.xintong.visualinspection.service.StatisticsService;
import com.xintong.visualinspection.util.CacheUtil;
import com.xintong.visualinspection.util.CodeUtil;
import com.xintong.visualinspection.util.DateUtil;

/**
 * 文件名：StatisticsServiceImpl 版本信息：日期：2017/3/30 Copyright 江苏省交通规划设计院 Corporation
 * 2017 版权所有.
 */
@Service
public class StatisticsServiceImpl extends BaseService implements StatisticsService {

	private static final org.slf4j.Logger logger = LoggerFactory.getLogger(StatisticsServiceImpl.class);

	@Autowired
	private StatisticsDao statisticsDao;

	@Autowired
	private DepartmentDao departmentDao;

	@Autowired
	private UserInfoDao userInfoDao;

	@Autowired
	private CheckTaskPeriodDao checkTaskPeriodDao;

	@Autowired
	private CheckOtherDao checkOtherDao;

    @Autowired
    private CheckUserStatisticsDao checkUserStatisticsDao;

	@Autowired
	private CheckDeptStatisticsDao checkDeptStatisticsDao;

    @Autowired
    private ThreadTaskService threadTaskService;






    @Override
    public List<UserChangeStation> getUserChangeStation(StatisticsBean obj) {
        return statisticsDao.selectuserchangestation(obj);
    }

    @Override
	public UserRankingData getEmployeeRankingData(StatisticsBean obj) {
		UserRankingData data = new UserRankingData();

		List<CheckTaskPeriod> checkTaskPeriods = checkTaskPeriodDao.select(new CheckTaskPeriod());

		CheckTaskPeriod lastTaskPeriod = null;
		// 计算上个周期时间 周期时间：00:00:00 ----- 00:00:00 参数：23:00:00
		for (CheckTaskPeriod p : checkTaskPeriods) {
			if (obj.getStart_date().getTime() + 1 * 1000 * 60 * 60 == p.getEndtime().getTime()) {
				lastTaskPeriod = p;
				break;
			}
		}
		if (lastTaskPeriod != null) {
			StatisticsBean temp = new StatisticsBean();
			temp.setStart_date(new Date(lastTaskPeriod.getStarttime().getTime() - 1 * 1000 * 60 * 60));
			temp.setEnd_date(new Date(lastTaskPeriod.getEndtime().getTime() - 1 * 1000 * 60 * 60));
			List<StatisticsBo> list = getEmployeeCheckedInfo(temp);
			if (list == null || list.size() < 1)
				return data;
			for (StatisticsBo b : list) {
				if (b.getUser().getId().intValue() == obj.getUser_id().intValue()) {
					data.setLastP(b);
					break;
				}
			}
		}
		List<StatisticsBo> list = getEmployeeCheckedInfo(obj);
		if (list == null || list.size() < 1)
			return data;
		for (StatisticsBo b : list) {
			if (b.getUser().getId().intValue() == obj.getUser_id().intValue()) {
				data.setCurrentP(b);
				break;
			}
		}

		data.setUser(CacheUtil.getUserFromMap(obj.getUser_id()));
		return data;
	}

	@Override
	public List<StatisticsBo> getEmployeeCheckedInfo(StatisticsBean obj) {

		// 查看是否有部门id
		Long organId = obj.getDept_id();
		// 道管中心 id
		Long parent_dept_id = obj.getParent_dept_id();
		obj.setParent_dept_id(null);
		obj.setDept_id(null);
		// 将检索出来的数据放到如map中
		List<StatisticsBean> list = statisticsDao.selectStatistics(obj);

		List<StatisticsBean> timesList = statisticsDao.selectCheckedTimes(obj);

		Map<Long, StatisticsBo> statisticBoMap = new HashMap<Long, StatisticsBo>();

		// 检索收费站的人员
		Constant t = CodeUtil.getCodeByFlagAndValue("feestation_check_jobs", "1");
		String[] postions = t.getCode_name().split(",");
		User user = new User();
		List<Integer> positionList = new ArrayList<Integer>();
		for (int i = 0; i < postions.length; i++) {
			positionList.add(Integer.parseInt(postions[i]));
		}
		user.setPosition_ids(positionList);

		if (obj.getDept_id() != null) {
			user.setOrganid(obj.getDept_id().intValue());
		}
		if (obj.getParent_dept_id() != null) {
			user.setParent_organid(obj.getParent_dept_id().intValue());
		}
		List<User> listUserts = userInfoDao.getAllUsers(user);
		for (User u : listUserts) {
			u.setPassword(null);
			if (u.getInvalidtime() != null && u.getInvalidtime().getTime() < obj.getEnd_date().getTime())
				continue;
			if (u.getFee_station_name() != null) {
				StatisticsBo tmp = new StatisticsBo();
				tmp.setUser(u);
				statisticBoMap.put(u.getId() + 0L, tmp);
			}
			u.setPosition_name(CacheUtil.getJobnameFromMap(new Long(u.getPositionid())));
		}

		for (StatisticsBean statisticsBean : list) {
			if (statisticBoMap.containsKey(statisticsBean.getUser_id())) {
				StatisticsBo tmp = statisticBoMap.get(statisticsBean.getUser_id());
				if (statisticsBean.getName() != null) {
					tmp.getChecked_socre_name().add(statisticsBean.getName());
					tmp.getChecked_score().add(statisticsBean.getScore());
					tmp.setCheck_all_score(tmp.getCheck_all_score() + statisticsBean.getScore());
				}

			}

		}

		for (StatisticsBean statisticsBean : timesList) {
			if (statisticBoMap.containsKey(statisticsBean.getUser_id())) {
				StatisticsBo tmp = statisticBoMap.get(statisticsBean.getUser_id());
				tmp.setChecked_num(statisticsBean.getChecked_num());
			}

		}

//		List<TaskAndScore> taskAndScores = GET_M_SCORE(obj.getStart_date(), obj.getEnd_date());
//		for (StatisticsBo b : statisticBoMap.values()) {
//			// 班长扣分加上成员的扣分
//			for (TaskAndScore s : taskAndScores) {
//				if (s.getMonitor_user_id().intValue() == b.getUser().getId().intValue()
//						&& s.getCheck_item_score() != null
//						&& ((s.getChecked_person1() == null
//								&& s.getChecked_person().intValue() != s.getMonitor_user_id().intValue())
//								|| (s.getChecked_person1() != null
//										&& s.getChecked_person1().intValue() != s.getMonitor_user_id().intValue()))) {
//					b.setCheck_all_m_score(b.getCheck_all_m_score() + s.getCheck_item_score());
//				}
//
//				if (s.getMonitor_user_id().intValue() == b.getUser().getId().intValue()
//						&& ((s.getChecked_person1() == null
//								&& s.getChecked_person().intValue() != s.getMonitor_user_id().intValue())
//								|| (s.getChecked_person1() != null
//										&& s.getChecked_person1().intValue() != s.getMonitor_user_id().intValue()))) {
//					b.setChecked_m_num(b.getChecked_m_num() + 1);
//				}
//			}
//		}

		List<StatisticsBo> lists = new ArrayList<>(statisticBoMap.values());
		// 进行排序
		lists.sort(new Comparator<StatisticsBo>() {
			@Override
			public int compare(StatisticsBo o1, StatisticsBo o2) {
				return o1.compareTo(o2);
			}
		});
		// 道管Map
		// 排名
		Map<String, Integer> center_ranking = new HashMap<>();
		// 留last
		Map<String, StatisticsBo> center_ranking2 = new HashMap<>();
		center_ranking.put("30", 1);
		center_ranking.put("31", 1);
		center_ranking.put("32", 1);

		center_ranking2.put("30", null);
		center_ranking2.put("31", null);
		center_ranking2.put("32", null);

		Map<String, Integer> fee_ranking = new HashMap<>();
		Map<String, StatisticsBo> fee_ranking2 = new HashMap<>();
		// 这边需要对道管和收费站内的员工进行排名
		List<FeeStation> list_feeStation = departmentDao.getAllFS();
		for (FeeStation fee : list_feeStation) {
			fee_ranking.put(fee.getDeptid(), 1);
			fee_ranking2.put(fee.getDeptid(), null);
		}

		for (int i = 0; i < lists.size(); i++) {

			StatisticsBo statisticsBo = lists.get(i);
			if (statisticsBo.getChecked_num() + statisticsBo.getChecked_m_num() == 0) {
				continue;
			}
			// 计算平均扣分
			DecimalFormat df = new DecimalFormat(".##");
			double count = statisticsBo.getChecked_num() + statisticsBo.getChecked_m_num();
			Double sc = (statisticsBo.getCheck_all_score() + statisticsBo.getCheck_all_m_score()) * 1.00
					/ (count == 0 ? 1 : count);
			statisticsBo.setCheck_score_avg(sc == 0 ? "0" : df.format(sc));

			// 累计道管排名
			// 获取道管id
			String centerId = statisticsBo.getUser().getParent_organid().toString();

			if (center_ranking2.get(centerId) == null) {
				statisticsBo.setCenter_ranking(center_ranking.get(centerId));
			} else {
				center_ranking.put(centerId, center_ranking.get(centerId) + 1);
				if (statisticsBo.compareTo(center_ranking2.get(centerId)) == 0) {
					statisticsBo.setCenter_ranking(center_ranking2.get(centerId).getCenter_ranking());
				} else {
					statisticsBo.setCenter_ranking(center_ranking.get(centerId));
				}
			}
			center_ranking2.put(centerId, statisticsBo);

			// 累计收费站的排名
			String feeStationId = statisticsBo.getUser().getOrganid().toString();

			if (fee_ranking2.get(feeStationId) == null) {
				statisticsBo.setFee_station_ranking(fee_ranking.get(feeStationId));
			} else {
				fee_ranking.put(feeStationId, fee_ranking.get(feeStationId) + 1);
				if (statisticsBo.compareTo(fee_ranking2.get(feeStationId)) == 0) {
					statisticsBo.setFee_station_ranking(fee_ranking2.get(feeStationId).getFee_station_ranking());
				} else {
					statisticsBo.setFee_station_ranking(fee_ranking.get(feeStationId));
				}
			}
			fee_ranking2.put(feeStationId, statisticsBo);

			// 公司排名

			if (i == 0) {
				statisticsBo.setCompany_ranking(1);
			} else {
				StatisticsBo lastbo = lists.get(i - 1);
				if (statisticsBo.compareTo(lastbo) == 0) {
					statisticsBo.setCompany_ranking(lastbo.getCompany_ranking());
				} else {
					statisticsBo.setCompany_ranking(i + 1);
				}

			}

		}


		CheckTaskPeriod period = getperiod(obj.getStart_date().getTime(),obj.getEnd_date().getTime());

		Map<Integer,StatisticExUser> statisticExUserMap = new HashMap<>();
		if(period!=null) {
			StatisticExUser u = new StatisticExUser();
			u.setPeriod_id(period.getId());
			List<StatisticExUser> statisticExUsers = statisticsDao.getcheckSExUser(u);
			if(statisticExUsers!=null && statisticExUsers.size()>0){
				for (StatisticExUser d:statisticExUsers
						) {
					statisticExUserMap.put(d.getUser_id(),d);
				}
			}
		}

		// 这边进行赛选一下；
		List<StatisticsBo> reList = new ArrayList<>();
		for (int i = 0; i < lists.size(); i++) {
			if (parent_dept_id == null || lists.get(i).getUser().getParent_organid() == parent_dept_id + 0) {
				if (organId == null || lists.get(i).getUser().getOrganid() == organId + 0) {
					if(statisticExUserMap.get(lists.get(i).getUser().getId())!=null){
						lists.get(i).setIsEx(true);
					}else{
						lists.get(i).setIsEx(false);
					}
					lists.get(i).setPeriod_id(period==null?0:period.getId());
					reList.add(lists.get(i));
				}
			}
		}
		//更新数据库统计
      // threadTaskService.saveUserStatic(reList,obj.getStart_date().getTime(),obj.getEnd_date().getTime());

		return reList;
	}


  private CheckTaskPeriod getperiod(long st,long et){
    	CheckTaskPeriod period = null;
	  List<CheckTaskPeriod> checkTaskPeriods = checkTaskPeriodDao.select(new CheckTaskPeriod());
	  // 计算上个周期时间 周期时间：00:00:00 ----- 00:00:00 参数：23:00:00
	  for (CheckTaskPeriod p : checkTaskPeriods) {
		  if (st + 1 * 1000 * 60 * 60 == p.getStarttime().getTime() && et + 1 * 1000 * 60 * 60 == p.getEndtime().getTime()) {
			  period = p;
			  break;
		  }
	  }
	  return period;
  }

	@Override
	public List<StatisticsBean> getFeeStationCheckedScore(StatisticsBean obj) {
		// 获取收费站信息收费站人数
		Constant t = CodeUtil.getCodeByFlagAndValue("feestation_check_jobs", "1");
		String[] postions = t.getCode_name().split(",");
		User user = new User();
		List<Integer> positionList = new ArrayList<Integer>();
		for (int i = 0; i < postions.length; i++) {
			positionList.add(Integer.parseInt(postions[i]));
		}
		user.setPosition_ids(positionList);

		user.setInvalidtime(obj.getStart_date());
		List<StatisticsBean> lists = departmentDao.selectFeeStationGroup(user);
		Map<Long, StatisticsBean> mapStationInfos = new HashMap<>();
		int i = 0;
		for (StatisticsBean sta : lists) {
			if (i < 7) {
				sta.setId(1);
			} else if (i < 13) {
				sta.setId(2);
			} else {
				sta.setId(3);
			}
			i++;
			mapStationInfos.put(sta.getDept_id(), sta);
		}

		if(obj.getStart_date()!=null && obj.getEnd_date()!=null){
			CheckTaskPeriod p = getperiod(obj.getStart_date().getTime(),obj.getEnd_date().getTime());
			if(p!=null){
				obj.setPeriod_id(p.getId());
			}
		}


		// 检查人数 和 检查次数
		obj.setPosition_ids(positionList);
		List<StatisticsBean> listCheckNum = statisticsDao.selectFeeStationCheckNum(obj);
		for (StatisticsBean sta : listCheckNum) {
			if (mapStationInfos.containsKey(sta.getDept_id())) {
				mapStationInfos.get(sta.getDept_id()).setChecked_num(sta.getChecked_num());
				mapStationInfos.get(sta.getDept_id()).setChecked_people_num(sta.getChecked_people_num());
			}
		}

		List<StatisticsBo> list = getEmployeeCheckedInfo(obj);
		Map<Integer, StatisticsBo> listmap = new HashMap<>();
		for (StatisticsBo b : list) {
			listmap.put(b.getUser().getId(), b);
		}

		List<StatisticsBean> listCheckedScore = statisticsDao.selectFeeStationCheckedScore(obj);
		for (StatisticsBean sta : listCheckedScore) {
			if (mapStationInfos.containsKey(sta.getDept_id())) {

				StatisticsBean statis = mapStationInfos.get(sta.getDept_id());
				statis.setAll_check_score(statis.getAll_check_score() + sta.getScore());

				StatisticsBo b = listmap.get(sta.getUser_id().intValue());

				if (b == null || b.getCheck_score_avg() == null || statis == null)
					continue;
				double sc = Double.parseDouble(b.getCheck_score_avg());
				if (sc == 0) {
					statis.setScore(statis.getScore() + 1);
				} else if (sc <= 15) {
					statis.setScore_fifteen(statis.getScore_fifteen() + 1);
				} else if (sc <= 50) {
					statis.setScore_fifty(statis.getScore_fifty() + 1);
				} else {
					statis.setScore_over_fifty(statis.getScore_over_fifty() + 1);
				}

			}
		}

		List<StatisticsBean> sortList = new ArrayList<>(mapStationInfos.values());

		sortList.sort(new Comparator<StatisticsBean>() {
			@Override
			public int compare(StatisticsBean o1, StatisticsBean o2) {
				if (o1.getId() > o2.getId()) {
					return 1;
				} else if (o1.getId() == o2.getId()) {
					if (o1.getChecked_num() != 0 && o2.getChecked_num() != 0) {
						if (o1.getAll_check_score() / (o1.getChecked_num() + 0.0) > o2.getAll_check_score()
								/ (o2.getChecked_num() + 0.0)) {
							return 1;
						} else if (o1.getAll_check_score() / (o1.getChecked_num() + 0.0) < o2.getAll_check_score()
								/ (o2.getChecked_num() + 0.0)) {
							return -1;
						} else {
							return 0;
						}
					} else {
						if (o1.getChecked_num() == 0) {
							return -1;
						} else if (o2.getChecked_num() == 0) {
							return 1;
						} else {
							return 0;
						}
					}
				} else {
					return -1;
				}
			}
		});

		return sortList;
	}

	@Override
	public List<StatisticsBean> getFeeStationCheckItemScore(StatisticsBean obj) {

		// 获取收费站信息收费站人数
		Constant t = CodeUtil.getCodeByFlagAndValue("feestation_check_jobs", "1");
		String[] postions = t.getCode_name().split(",");
		User user = new User();
		List<Integer> positionList = new ArrayList<Integer>();
		for (int i = 0; i < postions.length; i++) {
			positionList.add(Integer.parseInt(postions[i]));
		}
		user.setPosition_ids(positionList);
		user.setInvalidtime(obj.getStart_date());
		List<StatisticsBean> lists = departmentDao.selectFeeStationGroup(user);
		Map<Long, StatisticsBean> mapStationInfos = new HashMap<>();
		int i = 0;
		for (StatisticsBean sta : lists) {
			if (i < 7) {
				sta.setId(1);
			} else if (i < 13) {
				sta.setId(2);
			} else {
				sta.setId(3);
			}
			i++;
			mapStationInfos.put(sta.getDept_id(), sta);
		}

		if(obj.getStart_date()!=null && obj.getEnd_date()!=null){
			CheckTaskPeriod p = getperiod(obj.getStart_date().getTime(),obj.getEnd_date().getTime());
			if(p!=null){
				obj.setPeriod_id(p.getId());
			}
		}



		// 检查人数 和 检查次数
		obj.setPosition_ids(positionList);
		List<StatisticsBean> listCheckNum = statisticsDao.selectFeeStationCheckNum(obj);
		for (StatisticsBean sta : listCheckNum) {
			if (mapStationInfos.containsKey(sta.getDept_id())) {
				mapStationInfos.get(sta.getDept_id()).setChecked_num(sta.getChecked_num());
				mapStationInfos.get(sta.getDept_id()).setChecked_people_num(sta.getChecked_people_num());
			}
		}

		List<StatisticsBean> listCheckedScore = statisticsDao.selectFeeStationCheckedPersonScoreDetail(obj);
		for (StatisticsBean sta : listCheckedScore) {
			if (mapStationInfos.containsKey(sta.getDept_id()) && sta != null) {
				StatisticsBean statis = mapStationInfos.get(sta.getDept_id());
				statis.setAll_check_score(statis.getAll_check_score() + sta.getScore());
				statis.getChecked_socre_name().add(sta.getName());
				statis.getChecked_score().add(sta.getScore());
				statis.getChecked_score_ids().add(sta.getId());
			}
		}

		List<StatisticsBean> sortList = new ArrayList<>(mapStationInfos.values());

		sortList.sort(new Comparator<StatisticsBean>() {
			@Override
			public int compare(StatisticsBean o1, StatisticsBean o2) {
				if (o1.getId() > o2.getId()) {
					return 1;
				} else if (o1.getId() == o2.getId()) {
					if (o1.getChecked_num() != 0 && o2.getChecked_num() != 0) {
						if (o1.getAll_check_score() / (o1.getChecked_num() + 0.0) > o2.getAll_check_score()
								/ (o2.getChecked_num() + 0.0)) {
							return 1;
						} else if (o1.getAll_check_score() / (o1.getChecked_num() + 0.0) < o2.getAll_check_score()
								/ (o2.getChecked_num() + 0.0)) {
							return -1;
						} else {
							return 0;
						}
					} else {
						if (o1.getChecked_num() == 0) {
							return -1;
						} else if (o2.getChecked_num() == 0) {
							return 1;
						} else {
							return 0;
						}
					}
				} else {
					return -1;
				}
			}
		});

		return sortList;

	}

	private Integer getItemScore(StatisticsBo obj, String name) {
		List<String> names = obj.getChecked_socre_name();
		List<Integer> scores = obj.getChecked_score();
		for (int i = 0; i < names.size(); i++) {
			if (names.get(i).indexOf(name) > -1) {
				return scores.get(i);
			}
		}
		return 0;
	}

	private Integer getItemScore2(StatisticsBean obj, String name) {

            List<String> names = obj.getChecked_socre_name();
            List<Integer> scores = obj.getChecked_score();
            for (int i = 0; i < names.size(); i++) {
                if(names.get(i)==null) continue;
                if (names.get(i).indexOf(name) > -1) {
                    return scores.get(i);
                }
            }
            return 0;


	}

	@Override
	public void getEmployeeCheckedInfo(StatisticsBean obj, HttpServletRequest req, HttpServletResponse resp) {
		// 检索数据
		List<StatisticsBo> listStatistic = getEmployeeCheckedInfo(obj);
		double start_score = Double.parseDouble(obj.getStart_score());
		double end_score = Double.parseDouble(obj.getEnd_score());

		StatisticsBeanBO objs = (StatisticsBeanBO) obj;

		for (Iterator<StatisticsBo> it = listStatistic.iterator(); it.hasNext();) {
			StatisticsBo st = it.next();
			boolean flag = false;
			if (objs.getMax_check_num() != null && st.getChecked_num() > objs.getMax_check_num()) {
				flag = true;
			}
			if (objs.getMin_check_num() != null && st.getChecked_num() < objs.getMin_check_num()) {
				flag = true;
			}
//			double score = (st.getChecked_num() != 0) ? 1000 - (st.getCheck_all_score() / (st.getChecked_num())) : 1000;
            double score = 0;
            if(st.getCheck_score_avg()!=null){
                score = 1000 -  Double.parseDouble(st.getCheck_score_avg());
            }

			if (objs.getMin_score() != null && score < objs.getMin_score()) {
				flag = true;
			}
			if (objs.getMax_score() != null && score > objs.getMax_score()) {
				flag = true;
			}
			if (objs.getPosition_id() != null && st.getUser().getPositionid() != objs.getPosition_id() + 0) {
				flag = true;
			}
			if (flag) {
				it.remove();
			}
		}

		// 处理数据
		int j = 1;
		for (Iterator<StatisticsBo> it = listStatistic.iterator(); it.hasNext();) {
			StatisticsBo st = it.next();
			String scoredata = "";
            double score = 0;
            if(st.getCheck_score_avg()!=null){
                score = 1000 -  Double.parseDouble(st.getCheck_score_avg());
                scoredata = String.format("%.2f", score);
            }else{
                scoredata = "-";
            }
			if (score >= start_score && score <= end_score) {
//				// 得分

				st.setCheck_score(scoredata);
//				// 平均值
//				st.setCheck_score_avg((st.getChecked_num() != 0)
//						? String.format("%.2f", st.getCheck_all_score() / (st.getChecked_num() + 0.0)) : "0.00");
//				// id值设置
				st.setId(j++);
				st.getEmp_item_score().add(getItemScore(st, "环境卫生"));
				st.getEmp_item_score().add(getItemScore(st, "仪容仪表"));
				st.getEmp_item_score().add(getItemScore(st, "表情"));
				st.getEmp_item_score().add(getItemScore(st, "动作"));
				st.getEmp_item_score().add(getItemScore(st, "文明用语"));
				st.getEmp_item_score().add(getItemScore(st, "工作纪律"));
				st.getEmp_item_score().add(getItemScore(st, "便民服务"));
				st.getEmp_item_score().add(getItemScore(st, "安全管理"));
			} else {
				it.remove();
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", listStatistic);
		exportExcel("温馨服务考核情况反馈表", "employee_order", map, resp);
	}

	@Override
	public void getFeeStationCheckedScore(StatisticsBean obj, HttpServletRequest req, HttpServletResponse resp) {
		List<StatisticsBean> list = getFeeStationCheckedScore(obj);
		int totalMan = 0, totalcheckedMan = 0, totalcheckedCount = 0, total0 = 0, total15 = 0, total50 = 0,
				totalOver50 = 0, totalAll = 0;
		for (StatisticsBean st : list) {
			st.setCheck_no_score(st.getChecked_people_num() - st.getScore_fifteen() - st.getScore_fifty()
					- st.getScore_over_fifty());
			st.setCheck_score_avg(
					(st.getChecked_num() != 0) ? st.getAll_check_score() / (st.getChecked_num() + 0.0f) : 0.00f);
			st.setScore_avg(String.format("%.2f", 1000.0 - st.getCheck_score_avg()));
			totalMan += st.getPeople_num();
			totalcheckedMan += st.getChecked_people_num();
			totalcheckedCount += st.getChecked_num();
			total0 += (st.getChecked_people_num() - st.getScore_fifteen() - st.getScore_fifty()
					- st.getScore_over_fifty());
			total15 += st.getScore_fifteen();
			total50 += st.getScore_fifty();
			totalOver50 += st.getScore_over_fifty();
			totalAll += st.getAll_check_score();
		}
		// 处理数据
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", list);
		map.put("totalMan", totalMan);
		map.put("totalcheckedMan", totalcheckedMan);
		map.put("totalcheckedCount", totalcheckedCount);
		map.put("total0", total0);
		map.put("total15", total15);
		map.put("total50", total50);
		map.put("totalOver50", totalOver50);
		map.put("totalAll", totalAll);
		exportExcel("温馨服务检查千分考核扣分情况汇总表", "checked_info", map, resp);
	}

	@Override
	public void getFeeStationCheckItemScore(StatisticsBean obj, HttpServletRequest req, HttpServletResponse resp) {
		List<StatisticsBean> list = getFeeStationCheckItemScore(obj);
		int totalMan = 0, totalcheckedMan = 0, totalcheckedCount = 0, totalAll = 0;
		Map<String, Integer> scoreTypeMap = new HashMap<String, Integer>();
		// 处理数据
		for (int i = 0; i < list.size(); i++) {
			StatisticsBean st = list.get(i);
			// id值设置 seq_checked_score
			// 平均值
			st.setCheck_score_avg(
					(st.getChecked_num() != 0) ? st.getAll_check_score() / (st.getChecked_num() + 0.0f) : 0.00f);
			st.getSeq_checked_score().add(getItemScore2(st, "环境卫生"));
			st.getSeq_checked_score().add(getItemScore2(st, "仪容仪表"));
			st.getSeq_checked_score().add(getItemScore2(st, "表情"));
			st.getSeq_checked_score().add(getItemScore2(st, "动作"));
			st.getSeq_checked_score().add(getItemScore2(st, "文明用语"));
			st.getSeq_checked_score().add(getItemScore2(st, "工作纪律"));
			st.getSeq_checked_score().add(getItemScore2(st, "便民服务"));
			st.getSeq_checked_score().add(getItemScore2(st, "安全管理"));
			totalMan += st.getPeople_num();
			totalcheckedMan += st.getChecked_people_num();
			totalcheckedCount += st.getChecked_num();
			totalAll += st.getAll_check_score();
			List<String> names = st.getChecked_socre_name();
			List<Integer> scores = st.getChecked_score();
			for (int j = 0; j < names.size(); j++) {
				Integer score = scoreTypeMap.get(names.get(j));
				if (score == null)
					score = 0;
				score += scores.get(j);
				scoreTypeMap.put(names.get(j), score);
			}
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("totalMan", totalMan);
		map.put("totalcheckedMan", totalcheckedMan);
		map.put("totalcheckedCount", totalcheckedCount);
		List<Constant> typeList = CodeUtil.getCodeByFlag("statistic_check_item_type");
		for (Constant c : typeList) {
			if (scoreTypeMap.containsKey(c.getCode_name())) {
				scoreTypeMap.put(c.getRemark(), scoreTypeMap.get(c.getCode_name()));
			} else {
				scoreTypeMap.put(c.getRemark(), 0);
			}
		}
		map.putAll(scoreTypeMap);
		map.put("totalAll", totalAll);
		map.put("list", list);
		exportExcel("温馨服务检查情况统计表", "checked_item_info", map, resp);
	}

	@Override
	public void getExcelAppealInfo(CheckAppealStatistic obj, String monthName, HttpServletRequest req,
			HttpServletResponse resp) {
		List<CheckAppealStatistic> list = getCheckAppealStatistic(obj);
		for (Integer i = 0; i < list.size(); i++) {
			if (i == 0) {
				list.get(0).setMonth_name(monthName);
			}
			list.get(i).setId(i + 1);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", list);
		exportExcel(monthName + "月份收费站申诉情况统计", "appeal_info", map, resp);
	}

	private void exportExcel(String fileName, String excelTemplateName, Map<String, Object> map,
			HttpServletResponse resp) {
		String path = "./" + fileName + ".xls";
		try (InputStream is = this.getClass().getResourceAsStream("/" + excelTemplateName + ".xls")) {
			try (OutputStream os = new FileOutputStream(path)) {
				Context context = new Context();
				// context.putVar("list", map.get("list"));
				// context.putVar("totalMan", map.get("totalMan"));
				for (String key : map.keySet()) {
					context.putVar(key, map.get(key));
				}
				JxlsHelper.getInstance().processTemplate(is, os, context);
			}
			Thread.sleep(1000);
			// path是指欲下载的文件的路径。
			File file = new File(path);
			// 取得文件名。
			String filename = file.getName();
			// 以流的形式下载文件。
			InputStream bis = new BufferedInputStream(new FileInputStream(file));
			byte[] buffer = new byte[bis.available()];
			bis.read(buffer);
			bis.close();
			// 清空response
			resp.reset();
			// 设置response的Header
			resp.addHeader("Content-Disposition",
					"attachment;filename=" + new String(filename.getBytes("gb2312"), "ISO8859-1"));
			resp.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(resp.getOutputStream());
			resp.setContentType("application/vnd.ms-excel;charset=gb2312");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
			// 删除生成的临时文件
			if (file.exists()) {
				file.delete();
			}

		} catch (Exception e) {
			logger.error(e.toString());
		}
	}

	@Override
	public List<StatisticsBean> getYearScoreChange(StatisticsBean obj) {
		// 导管中心
		if (obj.getQueryType() != null && obj.getQueryType() == 1) {
			// 检索当前导管中心下的deptid
			Organ organ = new Organ();
			if (obj.getDept_id() == null) {
				return null;
			}
			organ.setParentid(obj.getDept_id().intValue());

			List<Organ> list = departmentDao.getOrgan(organ);
			// 将导管中心下的收费站部门id 列表放入到list中
			obj.setDept_list(list);
		}

		// 这边把总人数计算出来
		List<StatisticsBean> feeStationList;
		int people_num = 0;
		if (obj.getQueryType() != null && obj.getQueryType() == 1) {
			// 道管中心
			people_num = userInfoDao.getUsersCenterManageCount(obj);

		} else if (obj.getQueryType() != null && obj.getQueryType() == 2) {
			// 收费站
			feeStationList = userInfoDao.getUsersCountList();
			if (feeStationList != null && feeStationList.size() > 0) {
				for (StatisticsBean sta : feeStationList) {
					if (obj.getDept_id() + 0L == sta.getDept_id()) {
						people_num = sta.getPeople_num();
					}
				}
			}
		} else {
			// 总公司
			feeStationList = userInfoDao.getUsersCountList();
			if (feeStationList != null && feeStationList.size() > 0) {
				for (StatisticsBean sta : feeStationList) {
					people_num += sta.getPeople_num();
				}
			}
		}

		// Constant t = CodeUtil.getCodeByFlagAndValue("feestation_check_jobs",
		// "1");
		// String[] postions = t.getCode_name().split(",");
		// List<Integer> positionList = new ArrayList<Integer>();
		// for (int i = 0; i < postions.length; i++) {
		// positionList.add(Integer.parseInt(postions[i]));
		// }
		// //未计算未扣分的稽查次数
		// obj.setPosition_ids(positionList);
		// List<StatisticsBean> listCheckNum =
		// statisticsDao.selectFeeStationCheckNum(obj);

		List<StatisticsBean> lists = statisticsDao.selectYearScoreInfo(obj);
		for (StatisticsBean sta : lists) {
			sta.setPeople_num(people_num);
		}

		return lists;
	}

	private List<StatisticsBean> reFeeStationScoreInfo(StatisticsBean obj) {
		List<StatisticsBean> scoreList = statisticsDao.selectFeeStationScoreInfo(obj);
		Map<Long, StatisticsBean> feeStationMap = new HashMap<>();
		// 获取所有的收费站
		List<StatisticsBean> feeStationList = userInfoDao.getUsersCountList();
		for (StatisticsBean feeObj : scoreList) {
			if (!feeStationMap.containsKey(feeObj.getDept_id())) {
				feeStationMap.put(feeObj.getDept_id(), feeObj);
			}
		}
		// 需要补充的
		List<StatisticsBean> reList = new ArrayList<>();

		for (StatisticsBean sta : feeStationList) {
			if (feeStationMap.containsKey(sta.getDept_id())) {
				feeStationMap.get(sta.getDept_id()).setFeeStationName(sta.getName());
				feeStationMap.get(sta.getDept_id()).setPeople_num(sta.getPeople_num());
			} else {
				sta.setAll_check_score(0);
				sta.setChecked_num(0);
				sta.setFeeStationName(sta.getName());
				reList.add(sta);
			}
		}
		scoreList.addAll(reList);
		return scoreList;
	}

	/**
	 * 检索公司收费站的排名
	 */
	@Override
	public List<StatisticsBean> getFeeStationScoreInfo(StatisticsBean obj) {
		List<StatisticsBean> scoreList = reFeeStationScoreInfo(obj);

		scoreList.sort(new Comparator<StatisticsBean>() {
			@Override
			public int compare(StatisticsBean o1, StatisticsBean o2) {
				return o1.compareTo(o2);
			}
		});

		return scoreList;
	}

	/**
	 * 检索某个导管中心下的收费站排名
	 */
	@Override
	public List<StatisticsBean> getSingleFeeStationScoreInfo(StatisticsBean obj) {
		List<StatisticsBean> resultList = new ArrayList<>();

		List<StatisticsBean> scoreList = reFeeStationScoreInfo(obj);
		Map<Long, StatisticsBean> centerManageMap = new HashMap<>();
		for (StatisticsBean sta : scoreList) {
			if (!centerManageMap.containsKey(sta.getDept_id())) {
				centerManageMap.put(sta.getDept_id(), sta);
			}
		}
		Organ organ = new Organ();
		if (obj.getDept_id() == null) {
			return null;
		}
		organ.setParentid(obj.getDept_id().intValue());
		List<Organ> list = departmentDao.getOrgan(organ);

		for (Organ org : list) {
			if (centerManageMap.containsKey(org.getId() + 0L)) {
				resultList.add(centerManageMap.get(org.getId() + 0L));
			}
		}

		resultList.sort(new Comparator<StatisticsBean>() {
			@Override
			public int compare(StatisticsBean o1, StatisticsBean o2) {
				return o1.compareTo(o2);
			}
		});

		return resultList;
	}

	/**
	 * 检索导管中心排名和数据
	 */
	@Override
	public List<StatisticsBean> getCenterManageScoreInfo(StatisticsBean obj) {

		// 导管中心
		List<StatisticsBean> centerManageList = new ArrayList<>();
		for (int i = 0; i < 3; i++) {
			StatisticsBean e = new StatisticsBean();
			centerManageList.add(e);
		}

		List<StatisticsBean> scoreList = reFeeStationScoreInfo(obj);
		Map<Long, StatisticsBean> centerManageMap = new HashMap<>();
		for (StatisticsBean sta : scoreList) {
			if (!centerManageMap.containsKey(sta.getDept_id())) {
				centerManageMap.put(sta.getDept_id(), sta);
			}
		}

		Constant t = CodeUtil.getCodeByFlagAndValue("feestation_check_jobs", "1");
		String[] postions = t.getCode_name().split(",");
		User user = new User();
		List<Integer> positionList = new ArrayList<Integer>();
		for (int i = 0; i < postions.length; i++) {
			positionList.add(Integer.parseInt(postions[i]));
		}
		user.setPosition_ids(positionList);

		List<StatisticsBean> lists = departmentDao.selectFeeStationGroup(user);
		int i = 0;
		for (StatisticsBean sta : lists) {
			if (i < 7) {
				centerManageList.get(0).setAll_check_score(centerManageList.get(0).getAll_check_score()
						+ centerManageMap.get(sta.getDept_id()).getAll_check_score());
				centerManageList.get(0).setChecked_num(centerManageList.get(0).getChecked_num()
						+ centerManageMap.get(sta.getDept_id()).getChecked_num());
				centerManageList.get(0).setPeople_num(centerManageList.get(0).getPeople_num()
						+ centerManageMap.get(sta.getDept_id()).getPeople_num());

				centerManageList.get(0).setFeeStationName("连云港");
			} else if (i < 13) {
				centerManageList.get(1).setAll_check_score(centerManageList.get(1).getAll_check_score()
						+ centerManageMap.get(sta.getDept_id()).getAll_check_score());
				centerManageList.get(1).setChecked_num(centerManageList.get(1).getChecked_num()
						+ centerManageMap.get(sta.getDept_id()).getChecked_num());
				centerManageList.get(1).setPeople_num(centerManageList.get(1).getPeople_num()
						+ centerManageMap.get(sta.getDept_id()).getPeople_num());
				centerManageList.get(1).setFeeStationName("盐城");
			} else {
				centerManageList.get(2).setAll_check_score(centerManageList.get(2).getAll_check_score()
						+ centerManageMap.get(sta.getDept_id()).getAll_check_score());
				centerManageList.get(2).setChecked_num(centerManageList.get(2).getChecked_num()
						+ centerManageMap.get(sta.getDept_id()).getChecked_num());
				centerManageList.get(2).setPeople_num(centerManageList.get(2).getPeople_num()
						+ centerManageMap.get(sta.getDept_id()).getPeople_num());
				centerManageList.get(2).setFeeStationName("南通");
			}
			i++;
		}

		// 进行排序
		centerManageList.sort(new Comparator<StatisticsBean>() {
			@Override
			public int compare(StatisticsBean o1, StatisticsBean o2) {
				return o1.compareTo(o2);
			}
		});

		return centerManageList;
	}

	/**
	 * 考核情况占比
	 */
	@Override
	public StatisticsBean getCheckedScoreInfo(StatisticsBean obj) {
		int people_num = 0;
		StatisticsBean returnObj = new StatisticsBean();

		if (obj.getQueryType() == 0) {
			// 公司
			// 公司总人数
			// List<StatisticsBean> feeStationList =
			// userInfoDao.getUsersCountList();
			// if (feeStationList != null && feeStationList.size() > 0) {
			// for (StatisticsBean sta : feeStationList) {
			// people_num += sta.getPeople_num();
			// }
			// }
			people_num = statisticsDao.selectCheckedNum(obj);
		} else if (obj.getQueryType() == 1) {
			// 道管中心
			Organ organ = new Organ();
			if (obj.getDept_id() == null) {
				return null;
			}
			organ.setParentid(obj.getDept_id().intValue());
			List<Organ> list = departmentDao.getOrgan(organ);
			// 将导管中心下的收费站部门id 列表放入到list中
			obj.setDept_list(list);
			obj.setDept_id(null);
			people_num = statisticsDao.selectCheckedNum(obj);
			// people_num = userInfoDao.getUsersCenterManageCount(obj);
		} else if (obj.getQueryType() == 2) {
			// 收费站
			// List<StatisticsBean> feeStationList =
			// userInfoDao.getUsersCountList();
			// if (feeStationList != null && feeStationList.size() > 0) {
			// for (StatisticsBean sta : feeStationList) {
			// if (obj.getDept_id() + 0L == sta.getDept_id()) {
			// people_num = sta.getPeople_num();
			// }
			// }
			// }
			people_num = statisticsDao.selectCheckedNum(obj);
		}
		if (obj.getStart_date() == null && obj.getMth() != null) {
			Calendar cal = Calendar.getInstance();
			Date d = DateUtil.strParseDate(obj.getMth(), "yyyy/MM");
			cal.setTime(d);
			cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), 25, 23, 0, 0);
			obj.setEnd_date(cal.getTime());
			cal.add(Calendar.MONTH, -1);
			obj.setStart_date(cal.getTime());
		}

		// List<StatisticsBean> userLostScoreInfoList =
		// statisticsDao.selectCheckedScoreList(obj);

		Long deptid = obj.getDept_id();
		List<StatisticsBo> list = getEmployeeCheckedInfo(obj);
		Map<Integer, StatisticsBo> listmap = new HashMap<>();
		for (StatisticsBo b : list) {
			listmap.put(b.getUser().getId(), b);
		}

		List<StatisticsBean> listCheckedScore = statisticsDao.selectFeeStationCheckedScore(obj);
		for (StatisticsBean sta : listCheckedScore) {
			if (deptid != null && sta.getDept_id().intValue() == deptid.intValue()) {

				StatisticsBo b = listmap.get(sta.getUser_id().intValue());

				if (b == null || b.getCheck_score_avg() == null)
					continue;
				double sc = Double.parseDouble(b.getCheck_score_avg());
				if (sc == 0) {
					returnObj.setScore(returnObj.getScore() + 1);
				} else if (sc <= 15) {
					returnObj.setScore_fifteen(returnObj.getScore_fifteen() + 1);
				} else if (sc <= 50) {
					returnObj.setScore_fifty(returnObj.getScore_fifty() + 1);
				} else {
					returnObj.setScore_over_fifty(returnObj.getScore_over_fifty() + 1);
				}

			}
		}

		// for (StatisticsBean sta : userLostScoreInfoList) {
		// if (listmap.containsKey(sta.getUser_id().intValue())) {
		// StatisticsBo bo = listmap.get(sta.getUser_id().intValue());
		// double score = Double.parseDouble(bo.getCheck_score_avg());
		// if(score==0){
		// continue;
		// }else
		// if (score <= 15) {
		// returnObj.setScore_fifteen(returnObj.getScore_fifteen() + 1);
		// } else if (score <= 50 ) {
		// returnObj.setScore_fifty(returnObj.getScore_fifty() + 1);
		// } else {
		// returnObj.setScore_over_fifty(returnObj.getScore_over_fifty() + 1);
		// }
		// }
		// }
		returnObj.setPeople_num(people_num);

		return returnObj;
	}

	@Override
	public List<StatisticsBean> getCheckedItemScoreInfo(StatisticsBean obj) {
		if (obj.getQueryType() == 1) {
			// 道管中心
			Organ organ = new Organ();
			if (obj.getDept_id() == null) {
				return null;
			}
			organ.setParentid(obj.getDept_id().intValue());
			List<Organ> list = departmentDao.getOrgan(organ);
			// 将导管中心下的收费站部门id 列表放入到list中
			obj.setDept_list(list);
		} else if (obj.getQueryType() == 2) {
			// 收费站
		}
		return statisticsDao.selectCheckedItemScoreInfo(obj);
	}

	@Override
	public Map<String, List<StatisticsBean>> get2CheckedItemScoreInfo(StatisticsBean obj) {

		Map<String, List<StatisticsBean>> map = new HashMap<>();

		int people_num = 0;

		if (obj.getQueryType() == 0) {
			// 公司
			// 公司总人数
			List<StatisticsBean> feeStationList = userInfoDao.getUsersCountList();
			if (feeStationList != null && feeStationList.size() > 0) {
				for (StatisticsBean sta : feeStationList) {
					people_num += sta.getPeople_num();
				}
			}
		} else if (obj.getQueryType() == 1) {
			// 道管中心
			Organ organ = new Organ();
			if (obj.getDept_id() == null) {
				return null;
			}
			organ.setParentid(obj.getDept_id().intValue());
			List<Organ> list = departmentDao.getOrgan(organ);
			// 将导管中心下的收费站部门id 列表放入到list中
			obj.setDept_list(list);

			people_num = userInfoDao.getUsersCenterManageCount(obj);
		} else if (obj.getQueryType() == 2) {
			// 收费站
			List<StatisticsBean> feeStationList = userInfoDao.getUsersCountList();
			if (feeStationList != null && feeStationList.size() > 0) {
				for (StatisticsBean sta : feeStationList) {
					if (obj.getDept_id() + 0L == sta.getDept_id()) {
						people_num = sta.getPeople_num();
					}
				}
			}
		}

		List<StatisticsBean> objList = statisticsDao.selectCheckedItemScoreInfo(obj);

		for (int i = 0; i < objList.size(); i++) {
			objList.get(i).setPeople_num(people_num);
			objList.get(i).setFeeStationName(CacheUtil.getOrgannameFromMap(objList.get(i).getDept_id()));
			objList.get(i).setPfeeStationName(CacheUtil.getOrgannameFromMap(objList.get(i).getParent_dept_id()));
		}

		map.put("Tmth", objList);

		obj.setMth(obj.getPrev_mth());

		objList = statisticsDao.selectCheckedItemScoreInfo(obj);

		for (int i = 0; i < objList.size(); i++) {
			objList.get(i).setPeople_num(people_num);
			objList.get(i).setFeeStationName(CacheUtil.getOrgannameFromMap(objList.get(i).getDept_id()));
			objList.get(i).setPfeeStationName(CacheUtil.getOrgannameFromMap(objList.get(i).getParent_dept_id()));
		}

		map.put("Pmth", objList);

		return map;
	}

	/**
	 * 道管中心或者收费站考核排名
	 */
	@Override
	public List<StatisticsBean> getPersonalScoreInfo(StatisticsBean obj) {

		if (obj.getQueryType() == 1) {
			// 道管中心
			Organ organ = new Organ();
			if (obj.getDept_id() == null) {
				return null;
			}
			organ.setParentid(obj.getDept_id().intValue());
			List<Organ> list = departmentDao.getOrgan(organ);
			// 将导管中心下的收费站部门id 列表放入到list中
			obj.setDept_list(list);
		}

		List<StatisticsBean> userLostScoreInfoList = statisticsDao.selectCheckedScoreList(obj);

		Map<Long, StatisticsBean> statisticBoMap = new HashMap<Long, StatisticsBean>();

		Constant t = CodeUtil.getCodeByFlagAndValue("feestation_check_jobs", "1");

		String[] postions = t.getCode_name().split(",");

		User user = new User();
		List<Integer> positionList = new ArrayList<Integer>();
		for (int i = 0; i < postions.length; i++) {
			positionList.add(Integer.parseInt(postions[i]));
		}
		user.setPosition_ids(positionList);
		if (obj.getQueryType() == 2 && obj.getDept_id() != null) {
			user.setOrganid(obj.getDept_id().intValue());
		} else if (obj.getQueryType() == 1) {
			// 当前为道管的时候，部门id
			user.setParent_organid(obj.getDept_id().intValue());
		}
		List<User> listUserts = userInfoDao.getUsers(user);
		for (User u : listUserts) {
			u.setPassword(null);
			if (u.getInvalidtime() != null && u.getInvalidtime().getTime() < obj.getEnd_date().getTime())
				continue;
			if (u.getFee_station_name() != null) {
				StatisticsBean tmp = new StatisticsBean();
				tmp.setUser(u);
				statisticBoMap.put(u.getId() + 0L, tmp);
			}
			u.setPosition_name(CacheUtil.getJobnameFromMap(new Long(u.getPositionid())));
		}

//		Map<Long, StatisticsBo> masterMap = getMasterNumAndScore(obj.getMth());
		for (StatisticsBean statisticsBean : userLostScoreInfoList) {
			if (statisticBoMap.containsKey(statisticsBean.getUser_id())) {
				StatisticsBean tmp = statisticBoMap.get(statisticsBean.getUser_id());
				tmp.setAll_check_score(statisticsBean.getAll_check_score());
				tmp.setChecked_num(statisticsBean.getChecked_num());
			}
//			// 计算班长总扣分和总稽查次数
//			if (masterMap.get(statisticsBean.getUser_id()) != null) {
//				StatisticsBean tmp = statisticBoMap.get(statisticsBean.getUser_id());
//				StatisticsBo msb = masterMap.get(statisticsBean.getUser_id());
//                if(tmp==null) continue;
//				tmp.setAll_check_score(statisticsBean.getAll_check_score() + (msb!=null?msb.getCheck_all_m_score():0));
//				tmp.setChecked_num(statisticsBean.getChecked_num() + (msb!=null?msb.getChecked_m_num():0));
//			}
		}

		List<StatisticsBean> lists = new ArrayList<>();
		for (StatisticsBean bean : statisticBoMap.values()) {
			if (bean.getChecked_num() != 0) {
				lists.add(bean);
			}
//			else if (masterMap.get(bean.getUser_id()) != null) {
//
//			}
		}
		// 进行排序
		lists.sort(new Comparator<StatisticsBean>() {
			@Override
			public int compare(StatisticsBean o1, StatisticsBean o2) {
				return o1.compare2To(o2);
			}
		});

		if (obj.getQueryType() == 1 && obj.getOrder_type() == 0) {
			// 道管 正序 前10
			return lists.subList(0, 10);
		} else if (obj.getQueryType() == 1 && obj.getOrder_type() == 1) {
			return lists.subList(lists.size() - 20, lists.size());
		}




		return lists;
	}




	@Override
	public List<StatisticsBean> getFSUp5Person(StatisticsBean obj) {
		obj.setQueryType(2);
		List<StatisticsBean> t_mthList = getPersonalScoreInfo(obj);
		Map<Integer, StatisticsBean> t_map = new HashMap<>();

		int seq = 0;

		for (int i = 0; i < t_mthList.size(); i++) {
			if (i == 0) {
				seq = 0;
			} else {
				if (t_mthList.get(i).compare2To(t_mthList.get(i - 1)) == 0) {
					;
				} else {
					seq = i + 1;
				}
			}
			seq = seq == 0 ? 1 : seq;
			t_mthList.get(i).setRanking(seq);
			t_mthList.get(i).setRanking_change(seq);
			t_map.put(t_mthList.get(i).getUser().getId(), t_mthList.get(i));
		}

		seq = 0;
		// 查询上一个月
		obj.setMth(obj.getPrev_mth());
		List<StatisticsBean> prev_mthList = getPersonalScoreInfo(obj);
		for (int i = 0; i < prev_mthList.size(); i++) {
			Integer uid = prev_mthList.get(i).getUser().getId();
			if (i == 0) {
				;
			} else {
				if (prev_mthList.get(i).compare2To(prev_mthList.get(i - 1)) == 0) {
					;
				} else {
					seq = i + 1;
				}
			}

			if (t_map.containsKey(uid)) {
				seq = seq == 0 ? 1 : seq;
				t_map.get(uid).setRanking_change(seq - t_map.get(uid).getRanking());
			}

		}

		// 这边按照名词变化进行排名
		t_mthList.sort(new Comparator<StatisticsBean>() {
			@Override
			public int compare(StatisticsBean o1, StatisticsBean o2) {
				if (o1.getRanking_change() > o2.getRanking_change()) {
					return -1;
				} else if (o1.getRanking_change() < o2.getRanking_change()) {
					return 1;
				} else {
					return 0;
				}
			}
		});

		if (obj.getOrder_type() == 0) {
			// 正序
			return t_mthList.subList(0, 5);
		} else if (obj.getOrder_type() == 1) {
			// 反序
			List<StatisticsBean> reList = new ArrayList<>();
			for (int j = t_mthList.size() - 1; j > t_mthList.size() - 6; j--) {
				reList.add(t_mthList.get(j));
			}
			return reList;
		}
		return t_mthList;
	}

	@Override
	public List<StatisticsBean> getOneFSCheckedInfo(StatisticsBean obj) {

		List<StatisticsBean> datas = statisticsDao.selectOneCheckedInfoData(obj);
//		for (StatisticsBean d : datas) {
//			Map<Long, StatisticsBo> p = getMasterNumAndScore(d.getMth());
//			if (p != null && p.get(obj.getUser_id()) != null) {
//				StatisticsBo b = p.get(obj.getUser_id());
//				d.setChecked_num(b.getChecked_m_num() + d.getChecked_num());
//				d.setAll_check_score(d.getAll_check_score() + b.getCheck_all_m_score());
//			}
//		}

		return datas;
	}

	@Override
	public List<StatisticsBean> getOneCheckedItemInfo(StatisticsBean obj) {

		return statisticsDao.selectOneCheckedItemInfo(obj);
	}

	@Override
	public List<StatisticsBean> getOneCheckedDetailInfo(StatisticsBean obj) {
		List<StatisticsBean> list = statisticsDao.selectOneCheckedDetailInfo(obj);

		if (obj.getQueryType() == 1) {
			for (StatisticsBean sta : list) {
				sta.setCheckman_name(CacheUtil.getUserFromMap(sta.getCheckman_id() + 0L).getTruename());
				sta.setChecked_name(CacheUtil.getUserFromMap(sta.getUser_id() + 0L).getTruename());
				sta.setFeeStationName(CacheUtil.getOrganFromMap(sta.getDept_id()).getOrganname());
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				SimpleDateFormat formatter2 = new SimpleDateFormat("- HH:mm");
				sta.setCheck_task_time_name(
						formatter.format(sta.getStart_date()) + formatter2.format(sta.getEnd_date()));

				if (sta.getUser_id() != null && obj.getUser_id() != null && obj.getQueryType() != null
						&& obj.getQueryType().intValue() == 0) {
					sta.setChecked_name(CacheUtil.getUserFromMap(sta.getUser_id()).getTruename()
							+ (obj.getUser_id().intValue() == sta.getUser_id().intValue() ? "" : "(组员)"));

				}
			}
		} else {
			for (StatisticsBean sta : list) {
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				SimpleDateFormat formatter2 = new SimpleDateFormat("- HH:mm");
				sta.setCheck_task_time_name(
						formatter.format(sta.getStart_date()) + formatter2.format(sta.getEnd_date()));

				if (sta.getUser_id() != null && obj.getUser_id() != null && obj.getQueryType() != null
						&& obj.getQueryType().intValue() == 0) {
					sta.setChecked_name(CacheUtil.getUserFromMap(sta.getUser_id()).getTruename()
							+ (obj.getUser_id().intValue() == sta.getUser_id().intValue() ? "" : "(组员)"));

				}
			}
		}
		return list;
	}

	@Override
	public CheckmanStatisticsBean getCheckmanStatisticInfo(CheckmanStatisticsBean obj) {

		CheckmanStatisticsBean obj1 = statisticsDao.selectCheckManInfo1(obj);
		CheckmanStatisticsBean obj2 = statisticsDao.selectCheckManInfo2(obj);
		CheckmanStatisticsBean obj3 = statisticsDao.selectCheckManInfo3(obj);
		obj1.setAll_checked_score(obj2.getAll_checked_score());
		obj1.setChecked_people_num(obj2.getChecked_people_num());
		obj1.setChecked_task_num(obj2.getChecked_task_num());
		obj1.setAll_checkman(obj2.getAll_checkman());

		obj1.setUnable_task_num(obj3.getUnable_task_num());

		return obj1;
	}

	// 根据调剂获取用户列表
	private List<User> getUsers(User user) {
		// 检索收费站的人员
		Constant t = CodeUtil.getCodeByFlagAndValue("feestation_check_jobs", "1");
		String[] postions = t.getCode_name().split(",");
		List<Integer> positionList = new ArrayList<Integer>();
		for (int i = 0; i < postions.length; i++) {
			positionList.add(Integer.parseInt(postions[i]));
		}
		user.setPosition_ids(positionList);
		return userInfoDao.getUsers(user);
	}

	/**
	 * 根据parant_organ_id 查询该下面的收费站列表
	 * 
	 * @param id
	 *            organ_id
	 * @return
	 */
	private List<Organ> getFsStationList(Integer id) {
		// 道管中心
		Organ organ = new Organ();
		organ.setParentid(id);
		return departmentDao.getOrgan(organ);
	}

	@Override
	public List<StatisticsFsWork> getFsWorkStatisticInfo(StatisticsFsWork obj) {

		List<User> userList = new ArrayList<>();
		if (obj.getUser_id() != null) {
			userList.add(userInfoDao.getOneDetail(obj.getUser_id().intValue()));
		} else {
			User user = new User();
			if (obj.getDept_id() != null) {
				user.setOrganid(obj.getDept_id().intValue());
			}
			if (obj.getParent_dept_id() != null) {
				user.setParent_organid(obj.getParent_dept_id().intValue());
				obj.setDept_list(getFsStationList(obj.getParent_dept_id().intValue()));
			}
			userList = getUsers(user);
		}

		//
		Map<Integer, StatisticsFsWork> map = new HashMap<>();
		List<StatisticsFsWork> sFsList = statisticsDao.selectFsWork(obj);
		for (int i = 0; i < sFsList.size(); i++) {
			map.put(sFsList.get(i).getUser_id().intValue(), sFsList.get(i));
		}
		//
		Map<Integer, StatisticsFsWork> mapSta = new HashMap<>();
		List<StatisticsFsWork> sfswList = statisticsDao.selectFsWorkGather(obj);
		for (int i = 0; i < sfswList.size(); i++) {
			mapSta.put(sfswList.get(i).getUser_id().intValue(), sfswList.get(i));
		}

		for (User userObj : userList) {
			if (mapSta.containsKey(userObj.getId())) {
				StatisticsFsWork staobj = map.get(userObj.getId());
				staobj.setFeeStationName(userObj.getFee_station_name());
				staobj.setWorkno(userObj.getWorkno());
				staobj.setPositionName(CacheUtil.getJobnameFromMap(new Long(userObj.getPositionid())));
				staobj.setUserName(userObj.getTruename());
				staobj.setWork_days(mapSta.get(userObj.getId()).getWork_days());
				staobj.setWork_minutes(mapSta.get(userObj.getId()).getWork_minutes());
			}
		}

		try {
			List<Task> tasklist = statisticsDao.getAllTasklist(obj);
			for (Task t : tasklist) {
				if (mapSta.containsKey(t.getChecked_person().intValue())) {
					if (t.getUser_class_unregular_id() != null)
						continue;
					StatisticsFsWork staobj = map.get(t.getChecked_person().intValue());
					List<StatisticsFsWork> list = staobj.getSubStatisticsFsWork();
					// 当前任务工作时间
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
					Calendar cal = Calendar.getInstance();
					cal.setTime(t.getStart_time());
					int hour = cal.get(Calendar.HOUR);// 小时
					Date workdate = t.getStart_time();
					if (hour >= 23) {
						cal.add(1, Calendar.DAY_OF_MONTH);
						workdate = df.parse(df.format(cal.getTime()));
					} else {
						workdate = df.parse(df.format(cal.getTime()));
					}
					boolean isin = false;

					List<StatisticsFsWork> temp = new ArrayList<>();
					for (StatisticsFsWork w : list) {
						if (w.getWork_date().getTime() == workdate.getTime()) {
							isin = true;
							break;
						}
					}
					if (!isin) {
						StatisticsFsWork ww = new StatisticsFsWork();
						ww.setId(Integer.parseInt(t.getUser_class_id()));
						ww.setDept_id(t.getChecked_dept());
						ww.setStart_time(t.getStart_time());
						ww.setEnd_time(t.getEnd_time());
						ww.setWork_date(workdate);
						ww.setClass_type(t.getClass_type());
						ww.setCheck_id(t.getId().intValue());
						ww.setStatus(1);
						temp.add(ww);
						list.addAll(temp);
						staobj.setSubStatisticsFsWork(list);
					}

				}

			}
		} catch (Exception e) {

		}

		return sFsList;
	}

	@Override
	public List<StatisticsFsWork> getUnregularFsWorkStatisticInfo(StatisticsFsWork obj) {
		List<User> userList = new ArrayList<>();
		if (obj.getUser_id() != null) {
			userList.add(userInfoDao.getOneDetail(obj.getUser_id().intValue()));
		} else {
			User user = new User();
			if (obj.getDept_id() != null) {
				user.setOrganid(obj.getDept_id().intValue());
			}
			if (obj.getParent_dept_id() != null) {
				user.setParent_organid(obj.getParent_dept_id().intValue());
				obj.setDept_list(getFsStationList(obj.getParent_dept_id().intValue()));
			}
			userList = getUsers(user);
		}

		//
		Map<Integer, StatisticsFsWork> map = new HashMap<>();
		List<StatisticsFsWork> sFsList = statisticsDao.selectFsUnregularWork(obj);
		for (int i = 0; i < sFsList.size(); i++) {
			map.put(sFsList.get(i).getUser_id().intValue(), sFsList.get(i));
		}
		//
		Map<Integer, StatisticsFsWork> mapSta = new HashMap<>();
		List<StatisticsFsWork> sfswList = statisticsDao.selectFsUnregularWorkGather(obj);
		for (int i = 0; i < sfswList.size(); i++) {
			mapSta.put(sfswList.get(i).getUser_id().intValue(), sfswList.get(i));
		}
		for (User userObj : userList) {
			if (mapSta.containsKey(userObj.getId())) {
				StatisticsFsWork staobj = map.get(userObj.getId());
				staobj.setFeeStationName(userObj.getFee_station_name());
				staobj.setWorkno(userObj.getWorkno());
				staobj.setPositionName(CacheUtil.getJobnameFromMap(new Long(userObj.getPositionid())));
				staobj.setUserName(userObj.getTruename());
				staobj.setWork_days(mapSta.get(userObj.getId()).getWork_days());
				staobj.setWork_minutes(mapSta.get(userObj.getId()).getWork_minutes());
			}
		}

		try {
			List<Task> tasklist = statisticsDao.getAllTasklist(obj);
			for (Task t : tasklist) {
				if (mapSta.containsKey(t.getChecked_person().intValue())) {
					if (t.getUser_class_unregular_id() == null)
						continue;
					StatisticsFsWork staobj = map.get(t.getChecked_person().intValue());
					List<StatisticsFsWork> list = staobj.getSubStatisticsFsWork();
					// 当前任务工作时间
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
					Calendar cal = Calendar.getInstance();
					cal.setTime(t.getStart_time());
					int hour = cal.get(Calendar.HOUR);// 小时
					Date workdate = t.getStart_time();
					if (hour >= 23) {
						cal.add(1, Calendar.DAY_OF_MONTH);
						workdate = df.parse(df.format(cal.getTime()));
					} else {
						workdate = df.parse(df.format(cal.getTime()));
					}
					boolean isin = false;

					List<StatisticsFsWork> temp = new ArrayList<>();
					for (StatisticsFsWork w : list) {
						if (w.getWork_date().getTime() == workdate.getTime()) {
							isin = true;
							break;
						}
					}
					if (!isin) {
						StatisticsFsWork ww = new StatisticsFsWork();
						ww.setId(Integer.parseInt(t.getUser_class_id()));
						ww.setDept_id(t.getChecked_dept());
						ww.setStart_time(t.getStart_time());
						ww.setEnd_time(t.getEnd_time());
						ww.setWork_date(workdate);
						ww.setClass_type(t.getClass_type());
						ww.setCheck_id(t.getId().intValue());
						ww.setStatus(1);
						temp.add(ww);
						list.addAll(temp);
						staobj.setSubStatisticsFsWork(list);
					}

				}

			}
		} catch (Exception e) {

		}

		return sFsList;
	}

	@Override
	public List<StatisticsFsWork> getFsWorkPerson(StatisticsFsWork obj) {

		List<User> userList = new ArrayList<>();
		if (obj.getUser_id() != null) {
			userList.add(userInfoDao.getOneDetail(obj.getUser_id().intValue()));
		} else {
			User user = new User();
			if (obj.getDept_id() != null) {
				user.setOrganid(obj.getDept_id().intValue());
			}
			if (obj.getParent_dept_id() != null) {
				user.setParent_organid(obj.getParent_dept_id().intValue());
				obj.setDept_list(getFsStationList(obj.getParent_dept_id().intValue()));
			}
			userList = getUsers(user);
		}
		Map<Integer, StatisticsFsWork> map = new HashMap<>();
		List<StatisticsFsWork> sFsList = statisticsDao.selectFsWorkGatherGroupByWorkType(obj);
		for (int i = 0; i < sFsList.size(); i++) {
			map.put(sFsList.get(i).getUser_id().intValue(), sFsList.get(i));
		}

		for (User userObj : userList) {
			if (map.containsKey(userObj.getId())) {
				StatisticsFsWork staobj = map.get(userObj.getId());
				staobj.setFeeStationName(userObj.getFee_station_name());
				staobj.setPositionName(CacheUtil.getJobnameFromMap(new Long(userObj.getPositionid())));
				staobj.setUserName(userObj.getTruename());
			}
		}
		return sFsList;
	}

	@Override
	public List<StatisticsFsWork> getFsWorkUnregularWorkPerson(StatisticsFsWork obj) {
		List<User> userList = new ArrayList<>();
		if (obj.getUser_id() != null) {
			userList.add(userInfoDao.getOneDetail(obj.getUser_id().intValue()));
		} else {
			User user = new User();
			if (obj.getDept_id() != null) {
				user.setOrganid(obj.getDept_id().intValue());
			}
			if (obj.getParent_dept_id() != null) {
				user.setParent_organid(obj.getParent_dept_id().intValue());
				obj.setDept_list(getFsStationList(obj.getParent_dept_id().intValue()));
			}
			userList = getUsers(user);
		}
		Map<Integer, StatisticsFsWork> map = new HashMap<>();
		List<StatisticsFsWork> sFsList = statisticsDao.selectFsUnregularWorkGatherGroupByWorkType(obj);
		for (int i = 0; i < sFsList.size(); i++) {
			map.put(sFsList.get(i).getUser_id().intValue(), sFsList.get(i));
		}

		for (User userObj : userList) {
			if (map.containsKey(userObj.getId())) {
				StatisticsFsWork staobj = map.get(userObj.getId());
				staobj.setFeeStationName(userObj.getFee_station_name());
				staobj.setPositionName(CacheUtil.getJobnameFromMap(new Long(userObj.getPositionid())));
				staobj.setUserName(userObj.getTruename());
			}
		}
		return sFsList;
	}

	// 将list 转化为 HashMap
	private <T> Map<Integer, T> getMapFromList(List<T> list, String fieldName) {
		if (list != null && list.size() > 0) {
			try {
				Map<Integer, T> map = new HashMap<>();
				for (T obj : list) {
					Method m = obj.getClass()
							.getMethod("get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1));
					Integer value = (Integer) m.invoke(obj);
					map.put(value, obj);
				}
				return map;
			} catch (Exception e) {

				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public List<CheckAppealStatistic> getCheckAppealStatistic(CheckAppealStatistic obj) {
		// 根据不同检索条件，分别检索去 公司、道管或者收费站 下的收费站列表
		List<Organ> list;
		if (obj.getDept_id() != null) {
			Organ organ = new Organ();
			organ.setId(obj.getDept_id());
			list = departmentDao.getOrgan(organ);
		} else if (obj.getParent_dept_id() != null) {
			list = getFsStationList(obj.getParent_dept_id());
			obj.setDept_list(list);
		} else {
			list = new ArrayList<>();
			List<FeeStation> lists = departmentDao.getAllFS();
			for (FeeStation e : lists) {
				Organ organ = new Organ();
				organ.setId(Integer.parseInt(e.getDeptid()));
				organ.setOrganname(e.getName());
				list.add(organ);
			}
		}

		// 将检索的数据填充list中
		List<CheckAppealStatistic> ObjList = statisticsDao.selectCheckAppealNum(obj);
		Map<Integer, CheckAppealStatistic> map = getMapFromList(ObjList, "dept_id");

		for (Organ organObj : list) {
			if (map != null && map.containsKey(organObj.getId())) {
				CheckAppealStatistic reObj = map.get(organObj.getId());
				reObj.setFee_station_name(organObj.getOrganname());
				Integer appeal_num = 0;
				for (CheckAppealStatistic subObj : reObj.getSubCheckApealStatistic()) {
					appeal_num += subObj.getAppeal_num();
					if (subObj.getAppeal_result() == null) {
						reObj.setAppeal_other_num(subObj.getAppeal_num());
					} else if (subObj.getAppeal_result() == 1) {
						reObj.setAppeal_success_num(subObj.getAppeal_num());
					} else {
						reObj.setAppeal_fail_num(subObj.getAppeal_num());
					}
				}
				reObj.setAppeal_num(appeal_num);
				reObj.setSubCheckApealStatistic(null);
			} else {
				CheckAppealStatistic reobj = new CheckAppealStatistic();
				reobj.setFee_station_name(organObj.getOrganname());
				reobj.setDept_id(organObj.getId());
				reobj.setAppeal_num(0);
				reobj.setAppeal_fail_num(0);
				reobj.setAppeal_other_num(0);
				reobj.setAppeal_result(0);
				ObjList.add(reobj);
			}
		}

		return ObjList;
	}

	@Override
	public void getCheckInfo(StatisticsBean obj, HttpServletRequest req, HttpServletResponse resp) {
		List<StatisticsBean> list = statisticsDao.selectOneCheckedDetailInfo(obj);
		if (obj.getQueryType() == 1) {
			int seq = 1;
			for (StatisticsBean sta : list) {
				sta.setId(seq++);
				User user = CacheUtil.getUserFromMap(sta.getCheckman_id() + 0L);
				if (user != null) {
					sta.setCheckman_name(user.getTruename());
				}
				user = CacheUtil.getUserFromMap(sta.getUser_id() + 0L);
				if (user != null) {
					sta.setChecked_name(user.getTruename());
				}
				Organ organ = CacheUtil.getOrganFromMap(sta.getDept_id());
				if (organ != null) {
					sta.setFeeStationName(organ.getOrganname());
				}
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				SimpleDateFormat formatter2 = new SimpleDateFormat("- HH:mm");
				sta.setCheck_task_time_name(
						formatter.format(sta.getStart_date()) + formatter2.format(sta.getEnd_date()));
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", list);
		exportExcel("稽查人员工作量统计", "check_info", map, resp);
	}

//	/*
//	 * 获取班长班组内总得分和扣分
//	 */
//	private Map<Long, StatisticsBo> getMasterNumAndScore(String month) {
//		TaskAndScore temp = new TaskAndScore();
//		Calendar cal = Calendar.getInstance();
//		Date d = DateUtil.strParseDate(month, "yyyy/MM");
//		cal.setTime(d);
//		cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), 25, 23, 0, 0);
//		temp.setEnd_time(cal.getTime());
//		cal.add(Calendar.MONTH, -1);
//		temp.setStart_time(cal.getTime());
//
//		List<TaskAndScore> taskAndScores = statisticsDao.selectMList(temp);
//		Map<Long, StatisticsBo> masterMap = new HashMap<Long, StatisticsBo>();
//		for (TaskAndScore score : taskAndScores) {
//			if (!masterMap.containsKey(score.getMonitor_user_id())) {
//				masterMap.put(score.getMonitor_user_id(), new StatisticsBo());
//			}
//			StatisticsBo sb = masterMap.get(score.getMonitor_user_id());
//
//			if (score.getCheck_item_score() != null && ((score.getChecked_person1() == null
//					&& score.getChecked_person().intValue() != score.getMonitor_user_id().intValue())
//					|| (score.getChecked_person1() != null
//							&& score.getChecked_person1().intValue() != score.getMonitor_user_id().intValue()))) {
//				sb.setCheck_all_m_score(sb.getCheck_all_m_score() + score.getCheck_item_score());
//			}
//
//			if (((score.getChecked_person1() == null
//					&& score.getChecked_person().intValue() != score.getMonitor_user_id().intValue())
//					|| (score.getChecked_person1() != null
//							&& score.getChecked_person1().intValue() != score.getMonitor_user_id().intValue()))) {
//				sb.setChecked_m_num(sb.getChecked_m_num() + 1);
//			}
//			//
//			//
//			// sb.setCheck_all_m_score(sb.getCheck_all_m_score()+(score.getCheck_item_score()==null?0:score.getCheck_item_score()));
//			// sb.setChecked_m_num(sb.getChecked_m_num()+1);
//		}
//		return masterMap;
//	}

//	private List<TaskAndScore> GET_M_SCORE(Date start_time, Date end_time) {
//		TaskAndScore temp = new TaskAndScore();
//		temp.setStart_time(start_time);
//		temp.setEnd_time(end_time);
//
//		List<TaskAndScore> taskAndScores = statisticsDao.selectMList(temp);
//		return taskAndScores;
//	}

	@Override
	public List<StatisticsBean> getOperationInfo(StatisticsBean obj) {
		// 获取收费站信息收费站人数
		Constant t = CodeUtil.getCodeByFlagAndValue("feestation_check_jobs", "1");
		String[] postions = t.getCode_name().split(",");
		User user = new User();
		List<Integer> positionList = new ArrayList<Integer>();
		for (int i = 0; i < postions.length; i++) {
			positionList.add(Integer.parseInt(postions[i]));
		}
		user.setPosition_ids(positionList);
		user.setInvalidtime(obj.getStart_date());
		List<StatisticsBean> lists = departmentDao.selectFeeStationGroup(user);
		Map<Long, StatisticsBean> mapStationInfos = new HashMap<>();
		int i = 0;
		for (StatisticsBean sta : lists) {
			if (i < 7) {
				sta.setId(1);
			} else if (i < 13) {
				sta.setId(2);
			} else {
				sta.setId(3);
			}
			i++;
			mapStationInfos.put(sta.getDept_id(), sta);
		}
		// 获取公司检查的某个收费站的受检次数和扣分合计
		List<StatisticsBean> company_beans =  getFeeStationCheckItemScore(obj);
		// 获取第三方暗访稽查的某个收费站的受检次数和扣分合计
		obj.setCheck_type(1);
		List<StatisticsBean> third_beans = statisticsDao.getselectFeeStationOperationScoreDetail(obj);
		// 获特情稽查的某个收费站的受检次数和扣分合计
		obj.setCheck_type(2);
		List<StatisticsBean> special_beans = statisticsDao.getselectFeeStationOperationScoreDetail(obj);
		// 获取现场稽查的某个收费站的受检次数和扣分合计
		obj.setCheck_type(3);
		List<StatisticsBean> onsite_beans = statisticsDao.getselectFeeStationOperationScoreDetail(obj);
		// 获取应用数据平台稽查的某个收费站的受检次数和扣分合计
		obj.setCheck_type(4);
		List<StatisticsBean> data_beans = statisticsDao.getselectFeeStationOperationScoreDetail(obj);
		
		for (StatisticsBean company_bean : company_beans) {
            mapStationInfos.get(company_bean.getDept_id()).setCompany_check_num(company_bean.getChecked_num());
//			mapStationInfos.get(company_bean.getDept_id()).setCompany_check_num(company_bean.getChecked_num()>1?1:company_bean.getChecked_num());
			mapStationInfos.get(company_bean.getDept_id()).setCompany_total_score(company_bean.getAll_check_score());
		}
		for (StatisticsBean third_bean : third_beans) {
			mapStationInfos.get(third_bean.getDept_id()).setThird_check_num(third_bean.getChecked_num()>1?1:third_bean.getChecked_num());
			mapStationInfos.get(third_bean.getDept_id()).setThird_total_score(third_bean.getCheck_total_score());
		}
		for (StatisticsBean special_bean : special_beans) {
			mapStationInfos.get(special_bean.getDept_id()).setSpecial_check_num(special_bean.getChecked_num());
			mapStationInfos.get(special_bean.getDept_id()).setSpecial_total_score(special_bean.getCheck_total_score());
		}
		for (StatisticsBean onsite_bean : onsite_beans) {
			mapStationInfos.get(onsite_bean.getDept_id()).setOnsite_check_num(onsite_bean.getChecked_num()>1?1:onsite_bean.getChecked_num());
			mapStationInfos.get(onsite_bean.getDept_id()).setOnsite_total_score(onsite_bean.getCheck_total_score());
		}
		for (StatisticsBean data_bean : data_beans) {
			mapStationInfos.get(data_bean.getDept_id()).setData_check_num(data_bean.getChecked_num()>1?1:data_bean.getChecked_num());
			mapStationInfos.get(data_bean.getDept_id()).setData_total_score(data_bean.getCheck_total_score());
		}
		// 计算出每个收费站的总平均扣分和平均得分
		Set<Entry<Long, StatisticsBean>> stationInfos = mapStationInfos.entrySet();
		// 保留二位小数
		DecimalFormat df = new DecimalFormat("0.00");
		for (Entry<Long, StatisticsBean> station : stationInfos) {
			float avg = 0;
			StatisticsBean value = station.getValue();
			value.setThird_check_num(1);
            value.setSpecial_check_num(1);
            value.setOnsite_check_num(1);
            value.setData_check_num(1);
			// 设置总平均扣分
			if (value.getCompany_check_num() > 0 || value.getThird_check_num() > 0) {
				avg += (value.getCompany_total_score() +value.getThird_total_score())  /4.0/ (value.getCompany_check_num()+value.getThird_check_num());
			}
//			if (value.getThird_check_num() > 0) {
//				avg += value.getThird_total_score() /4.0/ value.getThird_check_num();
//			}
			if (value.getSpecial_check_num() > 0) {
				avg += value.getSpecial_total_score() /4.0/ value.getSpecial_check_num();
			}
			if (value.getOnsite_check_num() > 0) {
				avg += value.getOnsite_total_score() /4.0/ value.getOnsite_check_num();
			}
			if (value.getData_check_num() > 0) {
				avg += value.getData_total_score() / 4.0 / value.getData_check_num();
			}
//			value.setCheck_total_avg(df.format(avg / value.getPeople_num()));
			value.setCheck_total_avg(df.format(avg ));
			// 设置平均得分
			Float score_avg = (1000 - Float.valueOf(df.format(avg )));
			value.setScore_avg(score_avg.toString());
		}
		List<StatisticsBean> sortList = new ArrayList<>(mapStationInfos.values());
		sortList.sort(new Comparator<StatisticsBean>() {
			@Override
			public int compare(StatisticsBean o1, StatisticsBean o2) {
				return o1.compare3To(o2);
			}
		});

		List<StatisticsBean> temp = new ArrayList<>();
		temp.addAll(sortList);
		for (int j=0;j<sortList.size();j++) {
			if(CacheUtil.getOrganFromMap(sortList.get(j).getDept_id())!=null){
				if(CacheUtil.getOrganFromMap(sortList.get(j).getDept_id()).getCreattime().getTime()>obj.getEnd_date().getTime()){
					temp.remove(sortList.get(j));
				}
			}

		}
		sortList = temp;

		for(int j=0;j<sortList.size();j++){
			StatisticsBean statisticsBean = sortList.get(j);
			// 公司排名
			if (j == 0) {
				statisticsBean.setCompany_ranking2(1);
			} else {
				StatisticsBean bean = sortList.get(j - 1);
				if (statisticsBean.compare3To(bean) == 0) {
					statisticsBean.setCompany_ranking2(bean.getCompany_ranking2());
				} else {
					statisticsBean.setCompany_ranking2(j + 1);
				}
			}
		}
//		sortList.sort(new Comparator<StatisticsBean>() {
//			@Override
//			public int compare(StatisticsBean o1, StatisticsBean o2) {
//				if (o1.getId() > o2.getId()) {
//					return 1;
//				} else if (o1.getId() == o2.getId()) {
//					if (Float.valueOf(o1.getCheck_total_avg()) != 0 && Float.valueOf(o2.getCheck_total_avg()) != 0) {
//						if (Float.valueOf(o1.getCheck_total_avg()) < Float.valueOf(o2.getCheck_total_avg())) {
//							return -1;
//						} else if (Float.valueOf(o1.getCheck_total_avg()) > Float.valueOf(o2.getCheck_total_avg())) {
//							return 1;
//						} else {
//							return 0;
//						}
//					} else {
//						if (Float.valueOf(o1.getCheck_total_avg()) == 0) {
//							return -1;
//						} else if (Float.valueOf(o2.getCheck_total_avg()) == 0) {
//							return 1;
//						} else {
//							return 0;
//						}
//					}
//				} else {
//					return -1;
//				}
//			}
//		});
//		Map<Integer, List<StatisticsBean>> fee_ranking = new HashMap<>();
//		for (StatisticsBean statisticsBean : sortList) {
//			List<StatisticsBean> list = fee_ranking.get(statisticsBean.getId());
//			if(list !=null && list.size() >0){
//				list.add(statisticsBean);
//				fee_ranking.put(statisticsBean.getId(), list);
//			}else{
//				List<StatisticsBean> beans = new ArrayList<StatisticsBean>();
//				beans.add(statisticsBean);
//				fee_ranking.put(statisticsBean.getId(), beans);
//			}
//		}
		// 道管排序
//		Set<Entry<Integer, List<StatisticsBean>>> set = fee_ranking.entrySet();
//		for (Entry<Integer, List<StatisticsBean>> beans : set) {
//			List<StatisticsBean> values = beans.getValue();
//			for(int j=0;j<values.size();j++){
//				StatisticsBean statisticsBean = values.get(j);
//				// 公司排名
//				if (j == 0) {
//					statisticsBean.setFee_station_ranking2(1);
//				} else {
//					StatisticsBean bean = values.get(j - 1);
//					if (statisticsBean.compare3To(bean) == 0) {
//						statisticsBean.setFee_station_ranking2(bean.getFee_station_ranking2());
//					} else {
//						statisticsBean.setFee_station_ranking2(j + 1);
//					}
//				}
//			}
//		}

		threadTaskService.saveDeptStatic(sortList,obj.getStart_date().getTime(),obj.getEnd_date().getTime());

		return sortList;
	}


    private void updateDeptStatistic(StatisticsBean obj){
        this.getOperationInfo(obj);
    }



	@Override
	public void getOperationInfo(StatisticsBean obj, HttpServletRequest req, HttpServletResponse resp) {
		List<StatisticsBean> lists= getOperationInfo(obj);
    	int totalMan=0,totalCompanyNum=0,totalCompanyScore=0,totalThirdNum=0,
    			totalThirdScore=0,totalSpecialNum=0,totalSpecialScore=0,totalOnsiteNum=0,
    			totalOnsiteScore=0,totalDataNum=0,totalDataScore=0;
    	for(StatisticsBean bean:lists){
    		totalMan+=bean.getPeople_num();
    		totalCompanyNum += bean.getCompany_check_num();
    		totalCompanyScore += bean.getCompany_total_score();
    		totalThirdNum += bean.getThird_check_num();
    		totalThirdScore += bean.getThird_total_score();
    		totalSpecialNum += bean.getSpecial_check_num();
    		totalSpecialScore += bean.getSpecial_total_score();
    		totalOnsiteNum += bean.getOnsite_check_num();
    		totalOnsiteScore += bean.getOnsite_total_score();
    		totalDataNum += bean.getData_check_num();
    		totalDataScore += bean.getData_total_score();
    	}
    	Map<String,Object> map = new HashMap<String,Object>();
    	map.put("list", lists);
    	map.put("totalMan", totalMan);
    	map.put("totalCompanyNum", totalCompanyNum);
    	map.put("totalCompanyScore", totalCompanyScore);
    	map.put("totalThirdNum", totalThirdNum);
    	map.put("totalThirdScore", totalThirdScore);
    	map.put("totalSpecialNum", totalSpecialNum);
    	map.put("totalSpecialScore", totalSpecialScore);
    	map.put("totalOnsiteNum", totalOnsiteNum);
    	map.put("totalOnsiteScore", totalOnsiteScore);
    	map.put("totalDataNum", totalDataNum);
    	map.put("totalDataScore", totalDataScore);
    	exportExcel("运营管理综合检查情况统计表", "operation_info", map, resp);
	}

	@Override
	public List<StatisticsBo> getBusinessFeedbackInfo(StatisticsBean obj) {
		
		Constant t = CodeUtil.getCodeByFlagAndValue("feestation_check_jobs", "1");
		String[] postions = t.getCode_name().split(",");
		User user = new User();
		List<Integer> positionList = new ArrayList<Integer>();
		for (int i = 0; i < postions.length; i++) {
			positionList.add(Integer.parseInt(postions[i]));
		}
		user.setPosition_ids(positionList);
		
		// 查看是否有部门id
		Long organId = obj.getDept_id();
		// 道管中心 id
		Long parent_dept_id = obj.getParent_dept_id();
//		obj.setParent_dept_id(null);
//		obj.setDept_id(null);
		// 将检索出来的数据放到如map中
		obj.setPosition_ids(positionList);
		List<StatisticsBean> list = statisticsDao.selectBFStatistics(obj);

//		List<StatisticsBean> timesList = statisticsDao.selectCheckedTimes(obj);

		Map<Long, StatisticsBo> statisticBoMap = new HashMap<Long, StatisticsBo>();

		// 检索收费站的人员
		if (obj.getDept_id() != null) {
			user.setOrganid(obj.getDept_id().intValue());
		}
		if (obj.getParent_dept_id() != null) {
			user.setParent_organid(obj.getParent_dept_id().intValue());
		}
		List<User> listUserts = userInfoDao.getAllUsers(user);
		for (User u : listUserts) {
			u.setPassword(null);
			if (u.getInvalidtime() != null && u.getInvalidtime().getTime() < obj.getEnd_date().getTime())
				continue;
			if (u.getFee_station_name() != null) {
				StatisticsBo tmp = new StatisticsBo();
				tmp.setUser(u);
				statisticBoMap.put(u.getId() + 0L, tmp);
			}
			u.setPosition_name(CacheUtil.getJobnameFromMap(new Long(u.getPositionid())));
		}

		for (StatisticsBean statisticsBean : list) {
			if (statisticBoMap.containsKey(statisticsBean.getUser_id())) {
				StatisticsBo tmp = statisticBoMap.get(statisticsBean.getUser_id());
				tmp.setChecked_num(statisticsBean.getChecked_num());
				tmp.setScore(statisticsBean.getScore());
				tmp.setCheck_t_num(statisticsBean.getCheck_t_num());
				tmp.setCheck_t_score(statisticsBean.getCheck_t_score());
				tmp.setCheck_x_num(statisticsBean.getCheck_x_num());
				tmp.setCheck_x_score(statisticsBean.getCheck_x_score());
				tmp.setCheck_s_num(statisticsBean.getCheck_s_num());
				tmp.setCheck_s_score(statisticsBean.getCheck_s_score());
				tmp.setCheck_all_num(statisticsBean.getCheck_all_num());
				tmp.setCheck_all_score(statisticsBean.getCheck_all_score());
			}

		}
		
		List<StatisticsBo> lists = new ArrayList<>(statisticBoMap.values());
		for (int i = 0; i < lists.size(); i++) {
			
			StatisticsBo statisticsBo = lists.get(i);
			if (statisticsBo.getCheck_all_num()== 0) {
				continue;
			}
			// 计算平均扣分
			DecimalFormat df = new DecimalFormat(".##");
			Integer count = statisticsBo.getChecked_num() ;
//			double count = statisticsBo.getCheck_all_num();
//			Double sc = (statisticsBo.getCheck_all_score()) * 1.00
//					/ (count == 0 ? 1 : count);
			Double sc =  statisticsBo.getScore()/1.0 /  (count == 0 ? 1 : count)  + 
					statisticsBo.getCheck_t_score()/1.0/ ( 1 ) +
					statisticsBo.getCheck_x_score()/1.0/ ( 1 ) +
					statisticsBo.getCheck_s_score()/1.0/ ( 1 );
			statisticsBo.setCheck_score_avg(sc == 0 ? "0" : df.format(sc));
		}
		// 进行排序
		lists.sort(new Comparator<StatisticsBo>() {
			@Override
			public int compare(StatisticsBo o1, StatisticsBo o2) {
				return o1.compareTo3(o2);
			}
		});

		// 这边进行赛选一下；
		List<StatisticsBo> reList = new ArrayList<>();
		for (int i = 0; i < lists.size(); i++) {
			if (parent_dept_id == null || lists.get(i).getUser().getParent_organid() == parent_dept_id + 0) {
				if (organId == null || lists.get(i).getUser().getOrganid() == organId + 0) {
					reList.add(lists.get(i));
				}
			}
		}

		return reList;
	}

	@Override
	public void getBusinessFeedbackInfo(StatisticsBeanBO obj, HttpServletRequest req, HttpServletResponse resp) {
		// 检索数据
		List<StatisticsBo> listStatistic = getBusinessFeedbackInfo(obj);
		double start_score = Double.parseDouble(obj.getStart_score());
		double end_score = Double.parseDouble(obj.getEnd_score());

		StatisticsBeanBO objs = (StatisticsBeanBO) obj;

		for (Iterator<StatisticsBo> it = listStatistic.iterator(); it.hasNext();) {
			StatisticsBo st = it.next();
			boolean flag = false;
			if (objs.getMax_check_num() != null && st.getChecked_num() > objs.getMax_check_num()) {
				flag = true;
			}
			if (objs.getMin_check_num() != null && st.getChecked_num() < objs.getMin_check_num()) {
				flag = true;
			}
            double score = 0;
            if(st.getCheck_score_avg()!=null){
                score = 1000 -  Double.parseDouble(st.getCheck_score_avg());
            }

			if (objs.getMin_score() != null && score < objs.getMin_score()) {
				flag = true;
			}
			if (objs.getMax_score() != null && score > objs.getMax_score()) {
				flag = true;
			}
			if (objs.getPosition_id() != null && st.getUser().getPositionid() != objs.getPosition_id() + 0) {
				flag = true;
			}
			if (flag) {
				it.remove();
			}
		}

		// 处理数据
		int j = 1;
		for (Iterator<StatisticsBo> it = listStatistic.iterator(); it.hasNext();) {
			StatisticsBo st = it.next();
			String scoredata = "";
            double score = 0;
            if(st.getCheck_score_avg()!=null){
                score = 1000 -  Double.parseDouble(st.getCheck_score_avg());
                scoredata = String.format("%.2f", score);
            }else{
                scoredata = "-";
            }
			if (score >= start_score && score <= end_score) {
				// 得分
				st.setCheck_score(scoredata);
				st.setId(j++);
			} else {
				it.remove();
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", listStatistic);
		exportExcel("收费生产人员业务提升考核情况反馈表", "business_feedback", map, resp);
	}

	@Override
	public List<StatisticsBean> getWreckerCheckInfo(StatisticsBean obj) {
		List<StatisticsBean> wreckerInfo = statisticsDao.selectWreckerInfo(obj);
		List<WreckerGroup> wreckers = statisticsDao.selectWreckerOrgan();
		
		Map<Long,StatisticsBean> wreckerStatistic = new HashMap<>();
		for(int i=0 ; i<wreckers.size(); i++ ){
			StatisticsBean tmp = new StatisticsBean();
			tmp.setPeople_num(wreckers.get(i).getPeople_num());
			tmp.setName(wreckers.get(i).getName());
			wreckerStatistic.put(Long.parseLong(wreckers.get(i).getDeptid()) , tmp) ;
		}
		
		for(int i=0;i<wreckerInfo.size();i++ ){
			StatisticsBean tmp =  wreckerStatistic.get(wreckerInfo.get(i).getDept_id()) ;
			// 受检人数
			tmp.setChecked_people_num( tmp.getChecked_people_num() + wreckerInfo.get(i).getChecked_people_num() );
			tmp.setCheck_all_score(tmp.getCheck_all_score() + wreckerInfo.get(i).getAll_check_score());
			tmp.setChecked_num(tmp.getChecked_num() + wreckerInfo.get(i).getChecked_num() );
			
			if(wreckerInfo.get(i).getName().indexOf("中心实时")>-1){
				tmp.setData_check_num(wreckerInfo.get(i).getChecked_num());
				tmp.setData_total_score(wreckerInfo.get(i).getAll_check_score());
				
			}else if(wreckerInfo.get(i).getName().indexOf("视频")>-1){
				tmp.setSpecial_check_num(wreckerInfo.get(i).getChecked_num());
				tmp.setSpecial_total_score(wreckerInfo.get(i).getAll_check_score());
				
			}else if(wreckerInfo.get(i).getName().indexOf("第三方")>-1){
				tmp.setThird_check_num(wreckerInfo.get(i).getChecked_num());
				tmp.setThird_total_score(wreckerInfo.get(i).getAll_check_score());
				
			}else if(wreckerInfo.get(i).getName().indexOf("现场")>-1){
				tmp.setOnsite_check_num(wreckerInfo.get(i).getChecked_num());
				tmp.setOnsite_total_score(wreckerInfo.get(i).getAll_check_score());
				
			}else if(wreckerInfo.get(i).getName().indexOf("其他")>-1){
				tmp.setOther_check_num(wreckerInfo.get(i).getChecked_num());
				tmp.setOther_total_score(wreckerInfo.get(i).getAll_check_score());
			}
		}

		return new ArrayList<>(wreckerStatistic.values());
	}

	@Override
	public List<WreckerStatisticsBO> getWreckerStaffInfo(WreckerStatisticsBO obj) {
		// 检索所有人员
		List<WreckerStatisticsBO> list = statisticsDao.selectWreckerStaff(obj);
		Map<Long,WreckerStatisticsBO> wreckerMap = new HashMap<>();
		for(int i=0;i< list.size(); i++){
			wreckerMap.put(list.get(i).getUser_id() , list.get(i));
		}
		// 检查详细扣分
		List<WreckerStatisticsBO> detail_list = statisticsDao.selectWreckerStatisticDetail(obj);
		for(int i=0; i< detail_list.size(); i++){
			if(wreckerMap.containsKey(detail_list.get(i).getUser_id())){
				WreckerStatisticsBO org_tmp = detail_list.get(i);
				WreckerStatisticsBO tmp = wreckerMap.get(org_tmp.getUser_id());
				// 中心稽查
				if(org_tmp.getWrecker_check_type() == 1){
					if(org_tmp.getItem_name().indexOf("出警及时性") >-1 ){
						tmp.setChu_jing(tmp.getChu_jing()+ org_tmp.getScore() );
						tmp.setCheck_num(tmp.getCheck_num()+ org_tmp.getCheck_num() );
						tmp.setAll_check_score(tmp.getAll_check_score() + org_tmp.getScore());
					}else if(org_tmp.getItem_name().indexOf("现场到达率") >-1 ){
						tmp.setXian_chang(tmp.getXian_chang() + org_tmp.getScore() );
						tmp.setCheck_num(tmp.getCheck_num()+ org_tmp.getCheck_num() );
						tmp.setAll_check_score(tmp.getAll_check_score() + org_tmp.getScore());
					}else if(org_tmp.getItem_name().indexOf("畅通率") >-1 ){
						tmp.setChang_tong(tmp.getChang_tong() + org_tmp.getScore() );
						tmp.setCheck_num(tmp.getCheck_num()+ org_tmp.getCheck_num() );
						tmp.setAll_check_score(tmp.getAll_check_score() + org_tmp.getScore());
					}else if(org_tmp.getItem_name().indexOf("作业现场") >-1 ){
						tmp.setZuo_ye(tmp.getZuo_ye() + org_tmp.getScore());
						tmp.setCheck_num(tmp.getCheck_num()+ org_tmp.getCheck_num() );
						tmp.setAll_check_score(tmp.getAll_check_score() + org_tmp.getScore());
					}else if(org_tmp.getItem_name().indexOf("信息上报") >-1 ){
						tmp.setXin_xi(tmp.getXin_xi() + org_tmp.getScore());
						tmp.setCheck_num(tmp.getCheck_num()+ org_tmp.getCheck_num() );
						tmp.setAll_check_score(tmp.getAll_check_score() + org_tmp.getScore());
					}
				}else if(org_tmp.getWrecker_check_type() == 2){
					if(org_tmp.getItem_name().indexOf("着装规范") >-1 ){
						tmp.setZhuo_zhuang(tmp.getZhuo_zhuang() + org_tmp.getScore());
						tmp.setCheck_num(tmp.getCheck_num()+ org_tmp.getCheck_num() );
						tmp.setAll_check_score(tmp.getAll_check_score() + org_tmp.getScore());
					}else if(org_tmp.getItem_name().indexOf("作业现场") >-1 ){
						tmp.setZuo_ye_xian_chang(tmp.getZuo_ye_xian_chang()+org_tmp.getScore());
						tmp.setCheck_num(tmp.getCheck_num()+ org_tmp.getCheck_num() );
						tmp.setAll_check_score(tmp.getAll_check_score() + org_tmp.getScore());
					}else if(org_tmp.getItem_name().indexOf("文明服务") >-1 ){
						tmp.setWen_ming(tmp.getWen_ming()+org_tmp.getScore());
						tmp.setCheck_num(tmp.getCheck_num()+ org_tmp.getCheck_num() );
						tmp.setAll_check_score(tmp.getAll_check_score() + org_tmp.getScore());
					}else if(org_tmp.getItem_name().indexOf("操作规范") >-1 ){
						tmp.setCao_zuo(tmp.getCao_zuo()+ org_tmp.getScore());
						tmp.setCheck_num(tmp.getCheck_num()+ org_tmp.getCheck_num() );
						tmp.setAll_check_score(tmp.getAll_check_score() + org_tmp.getScore());
					}else if(org_tmp.getItem_name().indexOf("工作纪律") >-1 ){
						tmp.setGong_zuo(tmp.getGong_zuo() + org_tmp.getScore());
						tmp.setCheck_num(tmp.getCheck_num()+ org_tmp.getCheck_num() );
						tmp.setAll_check_score(tmp.getAll_check_score() + org_tmp.getScore());
					}
				}
			}
		}
		
		// 设置其他3项扣分
		List<WreckerStatisticsBO> other_list = statisticsDao.selectWreckerStatistic(obj);
		for(int i=0; i< other_list.size() ; i++){
			if(wreckerMap.containsKey(other_list.get(i).getUser_id())){
				WreckerStatisticsBO org_tmp = other_list.get(i);
				WreckerStatisticsBO tmp = wreckerMap.get(org_tmp.getUser_id());
				if(org_tmp.getWrecker_check_type() == 3){
					tmp.setPrivate_check(org_tmp.getScore());
					tmp.setCheck_num(tmp.getCheck_num()+ org_tmp.getCheck_num() );
					tmp.setAll_check_score(tmp.getAll_check_score() + org_tmp.getScore());
				}else if(org_tmp.getWrecker_check_type() == 4){
					tmp.setIn_check(org_tmp.getScore());
					tmp.setCheck_num(tmp.getCheck_num()+ org_tmp.getCheck_num() );
					tmp.setAll_check_score(tmp.getAll_check_score() + org_tmp.getScore());
				}else if(org_tmp.getWrecker_check_type() == 5){
					tmp.setOther_check(org_tmp.getScore());
					tmp.setCheck_num(tmp.getCheck_num()+ org_tmp.getCheck_num() );
					tmp.setAll_check_score(tmp.getAll_check_score() + org_tmp.getScore());
				}
			}
		}
		
		//排序
		List<WreckerStatisticsBO> tmpList = new ArrayList<>(wreckerMap.values()); 
		tmpList.sort(new Comparator<WreckerStatisticsBO>() {
			@Override
			public int compare(WreckerStatisticsBO o1, WreckerStatisticsBO o2) {
				return o1.compareTo(o2);
			}
		});
		return tmpList;
	}

    @Override
    public List<StatisiticPojo> getuserStatistic(UserStatistic obj) {
	    //
        List<CheckTaskPeriod> checkTaskPeriods = checkTaskPeriodDao.select(new CheckTaskPeriod());

        for (CheckTaskPeriod p : checkTaskPeriods) {
            if (obj.getStart_date() + 1 * 1000 * 60 * 60 == p.getEndtime().getTime()) {
                obj.setStartperiod_id(p.getId());
            }
            if (obj.getEnd_date() + 1 * 1000 * 60 * 60 == p.getEndtime().getTime()) {
                obj.setEndperiod_id(p.getId());
            }
        }
        if(obj.getStart_date()>(checkTaskPeriods.get(checkTaskPeriods.size()-1).getEndtime().getTime()- 1 * 1000 * 60 * 60)){
            return  new ArrayList<>();
        }
        if(obj.getEnd_date()<(checkTaskPeriods.get(0).getEndtime().getTime()- 1 * 1000 * 60 * 60)){
            return  new ArrayList<>();
        }
        if(obj.getStart_date()<(checkTaskPeriods.get(0).getEndtime().getTime()- 1 * 1000 * 60 * 60)){
            obj.setStartperiod_id(checkTaskPeriods.get(0).getId());
        }
        if(obj.getEnd_date()>(checkTaskPeriods.get(checkTaskPeriods.size()-1).getEndtime().getTime()- 1 * 1000 * 60 * 60)){
            obj.setEndperiod_id(checkTaskPeriods.get(checkTaskPeriods.size()-1).getId());
        }

        List<CheckTaskPeriod> temp_p = new ArrayList<>();
        for (CheckTaskPeriod p : checkTaskPeriods) {
            if(p.getId()>=obj.getStartperiod_id() && p.getId()<=obj.getEndperiod_id()){
                temp_p.add(p);
            }
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM");
        //获取满足条件的人员
        List<UserStatistic>  userStatistics = checkUserStatisticsDao.selectlimituser(obj);
        
        HashMap<Integer,List<UserStatistic>> usm = new HashMap<>();

        for (UserStatistic c:userStatistics
             ) {
            List<UserStatistic> s = usm.get(c.getUser_id());
            if(s==null){s = new ArrayList<>();}
            s.add(c);
            usm.put(c.getUser_id(),s);
            for (CheckTaskPeriod p : checkTaskPeriods) {
                if(c.getPeriod_id().equals(p.getId())){
                    c.setP_str(simpleDateFormat.format(p.getEndtime()));
                }
            }

        }




        List<StatisiticPojo> user_ids = new ArrayList<>();


        //判断是否连续
        for(Integer k : usm.keySet()){
            List<UserStatistic> user_temp = new ArrayList<>();
            boolean isM = false;

            List<UserStatistic> pp = new ArrayList<>();
            //获取得分
            List<UserStatistic> ll = usm.get(k);
            int count=0;
            for (CheckTaskPeriod p : temp_p
                 ) {
                boolean isfond = false;
                for (UserStatistic s:ll
                     ) {
                    if(s.getPeriod_id().equals(p.getId())){
                        isfond = true;
                        pp.add(s);
                        break;
                    }
                }
                if(isfond){
                    count++;
                    if(count>=obj.getLimitnumber()){isM = true;user_temp.addAll(pp);pp.clear();}
                }else{
                    if(count>=obj.getLimitnumber()){isM = true;user_temp.addAll(pp);}
                    count=0;
                    pp.clear();
                }
            }



            if(isM) {
                StatisiticPojo p = new StatisiticPojo();
                p.setUser(CacheUtil.getUserFromMap(k.longValue()));
                p.setDept(CacheUtil.getOrgannameFromMap(p.getUser().getOrganid().longValue()));
                p.setUserStatistics(user_temp);
                user_ids.add(p);
            }
        }

        user_ids.sort(new Comparator<StatisiticPojo>() {
            @Override
            public int compare(StatisiticPojo o1, StatisiticPojo o2) {
                if(o1.getUser().getOrganid()>o2.getUser().getOrganid()){
                    return 1;
                }
                if(o1.getUser().getOrganid()<o2.getUser().getOrganid()){
                    return -1;
                }
                return 0;
            }
        });

        return user_ids;
    }

	@Override
	public Object addcheckSExUser(StatisticExUser statisticExUser) {
		try {
			statisticsDao.addcheckSExUser(statisticExUser);

            StatisticsBean obj = new StatisticsBean();
            obj.setStart_date(statisticExUser.getStart_date());
            obj.setEnd_date(statisticExUser.getEnd_date());
			updateDeptStatistic(obj);
		}catch (Exception e){
            return null;
		}
		return "";

	}

	@Override
	public Object deletecheckSExUser(StatisticExUser statisticExUser) {
		try {
			statisticsDao.deletecheckSExUser(statisticExUser);
            StatisticsBean obj = new StatisticsBean();
            obj.setStart_date(statisticExUser.getStart_date());
            obj.setEnd_date(statisticExUser.getEnd_date());
            updateDeptStatistic(obj);
		}catch (Exception e){
			return null;
		}
		return "";
	}



	@Override
	public Map<String, List<DeptStatistic>> getDeptStatistic(DeptStatistic obj) {
		List<CheckTaskPeriod> checkTaskPeriods = checkTaskPeriodDao.select(new CheckTaskPeriod());
        SimpleDateFormat ff = new SimpleDateFormat("yyyy-MM");
        SimpleDateFormat ff1 = new SimpleDateFormat("MM月");

		for (CheckTaskPeriod p : checkTaskPeriods) {
			if (obj.getStart_date() + 1 * 1000 * 60 * 60 == p.getEndtime().getTime()) {
				obj.setStartperiod_id(p.getId());
			}
			if (obj.getEnd_date() + 1 * 1000 * 60 * 60 == p.getEndtime().getTime()) {
				obj.setEndperiod_id(p.getId());
			}
		}
		if(obj.getStart_date()>(checkTaskPeriods.get(checkTaskPeriods.size()-1).getEndtime().getTime()- 1 * 1000 * 60 * 60)){
			return  null;
		}
		if(obj.getEnd_date()<(checkTaskPeriods.get(0).getEndtime().getTime()- 1 * 1000 * 60 * 60)){
			return  null;
		}
		if(obj.getStart_date()<(checkTaskPeriods.get(0).getEndtime().getTime()- 1 * 1000 * 60 * 60)){
			obj.setStartperiod_id(checkTaskPeriods.get(0).getId());
		}
		if(obj.getEnd_date()>(checkTaskPeriods.get(checkTaskPeriods.size()-1).getEndtime().getTime()- 1 * 1000 * 60 * 60)){
			obj.setEndperiod_id(checkTaskPeriods.get(checkTaskPeriods.size()-1).getId());
		}

		List<DeptStatistic> deptStatistics = checkDeptStatisticsDao.selectdepts(obj);
		if(deptStatistics.size()<1){return null;}
		Map<String,List<DeptStatistic>> listMap = new HashMap<>();
		Map<Long,List<DeptStatistic>> listMap1 = new HashMap<>();
		for (DeptStatistic s :deptStatistics
			 ) {

			//按月统计
			if(listMap.get(s.getPeriod_id()+"")==null){
				List<DeptStatistic> t = new ArrayList<>();
				t.add(s);
				listMap.put(s.getPeriod_id()+"",t);
			}else{
				List<DeptStatistic> t = listMap.get(s.getPeriod_id()+"");
				t.add(s);
				listMap.put(s.getPeriod_id()+"",t);
			}


            //按部门统计
			if(listMap1.get(s.getDept_id())==null){
				List<DeptStatistic> t = new ArrayList<>();
				t.add(s);
				listMap1.put(s.getDept_id(),t);
			}else{
				List<DeptStatistic> t = listMap1.get(s.getDept_id());
				t.add(s);
				listMap1.put(s.getDept_id(),t);
			}
		}



//		按月划分
		for (CheckTaskPeriod p :checkTaskPeriods) {
			if(p.getId()>=obj.getStartperiod_id()  && p.getId()<=obj.getEndperiod_id() ){
				//符合要求的周期 计算得分
				for (Long tp:listMap1.keySet()
					 ) {
					List<DeptStatistic> deptStatistics1 = listMap1.get(tp);
					//该周期每一个部门
					//计算累计
					Integer s = 0;
					for (DeptStatistic ss:deptStatistics1
						 ) {
						if(ss.getPeriod_id()<=p.getId()){
                           s+=ss.getIntegral();
						}
					}

					//赋值
					for (DeptStatistic ss:deptStatistics1
							) {
						if(ss.getPeriod_id().equals(p.getId())){
							ss.setTotal_integral(s);
							ss.setDept_name(CacheUtil.getOrgannameFromMap(ss.getDept_id()));
							ss.setTime(ff.format(p.getEndtime()));
						}
					}
				}

				//计算排名
				List<DeptStatistic> deptStatistics1 = listMap.get(p.getId()+"");
				if(deptStatistics1!=null) {
					deptStatistics1.sort(new Comparator<DeptStatistic>() {
						@Override
						public int compare(DeptStatistic o1, DeptStatistic o2) {
							return o1.getTotal_integral() > o2.getTotal_integral() ? -1 : 1;
						}
					});
					for (int i = 0; i < deptStatistics1.size(); i++) {
						deptStatistics1.get(i).setTotal_ranking(i + 1);
					}
				}

			}
		}

		//排序
		for (String i :listMap.keySet()
			 ) {
			listMap.get(i).sort(new Comparator<DeptStatistic>() {
				@Override
				public int compare(DeptStatistic o1, DeptStatistic o2) {
					return o1.getDept_id()>o2.getDept_id()?1:-1;
				}
			});
		}
		listMap.clear();
		for (Long s:listMap1.keySet()
			 ) {
			List<DeptStatistic> l = listMap1.get(s);
			l.sort(new Comparator<DeptStatistic>() {
				@Override
				public int compare(DeptStatistic o1, DeptStatistic o2) {
					return o1.getPeriod_id()> o2.getPeriod_id()?1:-1;
				}
			});
			listMap.put(l.get(0).getDept_id()+"",l);
		}

        if(obj.getType()!=null && obj.getType().equals(1)){
            //excel数据
            for (CheckTaskPeriod p :checkTaskPeriods) {
                if (p.getId() >= obj.getStartperiod_id() && p.getId() <= obj.getEndperiod_id()) {
                    //符合要求的周期 计算得分
                    for (String i :listMap.keySet()
                            ) {
                        //单个部门的
                        List<DeptStatistic> l = listMap.get(i);
                        DeptStatistic temp = null;
                        if(l.size()<1){continue;}
                        boolean isin = false;
                        for (DeptStatistic s:l
                                ) {
                            if(s.getPeriod_id().equals(p.getId())){
                                isin = true;
                                temp = s;break;
                            }
                        }
                        //不在里面
                        if(!isin){
                            DeptStatistic s = l.get(0).clone();
                            s.setScore((double)-1);
                            s.setPeriod_id(p.getId());
                            s.setIntegral(-1);
                            s.setTotal_integral(-1);
                            s.setTotal_ranking(-1);
                            temp = s;
                            l.add(s);
                        }

                        temp.setMString(ff1.format(p.getEndtime()));
                        listMap.put(i,l);

                    }
                }
            }
            //再次排序
            for (String s:listMap.keySet()
                    ) {
                List<DeptStatistic> l = listMap.get(s);
                l.sort(new Comparator<DeptStatistic>() {
                    @Override
                    public int compare(DeptStatistic o1, DeptStatistic o2) {
                        return o1.getPeriod_id()> o2.getPeriod_id()?1:-1;
                    }
                });
                listMap.put(l.get(0).getDept_id()+"",l);
            }
        }


        return  listMap;
	}

    @Override
    public void getDeptStatisticExcel(DeptStatistic obj,HttpServletRequest req,HttpServletResponse resp) {
	    obj.setType(1);
        Map<String, List<DeptStatistic>> listMap = this.getDeptStatistic(obj);
        SimpleDateFormat d = new SimpleDateFormat("yyyy/MM");
        List<Integer> temp = new ArrayList<>();
        for(int i=1;i<=listMap.keySet().size();i++){
            temp.add(i);
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("datas", listMap);
        map.put("list", temp);
        map.put("title","营运管理提升综合成绩汇总表"+"("+d.format(obj.getStart_date())+"---"+d.format(obj.getEnd_date())+")");
        exportExcel("营运管理提升综合成绩汇总表", "dept_statistic", map, resp);

    }


}
