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.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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

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.bean.StatisticsBean;
import com.xintong.visualinspection.bean.StatisticsBo;
import com.xintong.visualinspection.bean.User;
import com.xintong.visualinspection.dao.cluster.DepartmentDao;
import com.xintong.visualinspection.dao.cluster.UserInfoDao;
import com.xintong.visualinspection.dao.master.StatisticsDao;
import com.xintong.visualinspection.service.BaseService;
import com.xintong.visualinspection.service.StatisticsService;

/**
 * 文件名：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;

	@Override
	public List<StatisticsBo> getEmployeeCheckedInfo(StatisticsBean obj) {
		// 查看是否有部门id
		Long organId = obj.getDept_id();
		// 将检索出来的数据放到如map中
		List<StatisticsBean> list = statisticsDao.selectStatistics(obj);

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

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

		User user = new User();
		user.setPositionid(1);
		if (obj.getDept_id() != null)
			user.setOrganid(obj.getDept_id().intValue());
		List<User> listUserts = userInfoDao.getUsers(user);
		for (User u : listUserts) {
			u.setPassword(null);
			if (u.getFee_station_name() != null) {
				StatisticsBo tmp = new StatisticsBo();
				tmp.setUser(u);
				statisticBoMap.put(u.getId() + 0L, tmp);
			}
		}

		for (StatisticsBean statisticsBean : list) {
			if (statisticBoMap.containsKey(statisticsBean.getUser_id())) {
				StatisticsBo tmp = statisticBoMap.get(statisticsBean.getUser_id());
				if (statisticsBean.getName() != null && statisticsBean.getScore() != 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<StatisticsBo> lists = new ArrayList<>(statisticBoMap.values());
		// 进行排序
		lists.sort(new Comparator<StatisticsBo>() {
			@Override
			public int compare(StatisticsBo o1, StatisticsBo o2) {
				if (o1.getCheck_all_score() > o2.getCheck_all_score()) {
					return 1;
				} else if (o1.getCheck_all_score() < o2.getCheck_all_score()) {
					return -1;
				} else {
					return 0;
				}
			}
		});

		return lists;
	}

	@Override
	public List<StatisticsBean> getFeeStationCheckedScore(StatisticsBean obj) {
		// 获取收费站信息收费站人数
		List<StatisticsBean> lists = departmentDao.selectFeeStationGroup(obj);
		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);
			}
			mapStationInfos.put(sta.getDept_id(), sta);
		}

		// 检查人数 和 检查次数
		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.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());
				if (sta.getScore() <= 15) {
					statis.setScore_fifteen(statis.getScore_fifteen() + 1);
				} else if (sta.getScore() <= 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.getAll_check_score() > o2.getAll_check_score()) {
						return 1;
					} else if (o1.getAll_check_score() < o2.getAll_check_score()) {
						return -1;
					} else {
						return 0;
					}
				} else {
					return -1;
				}
			}
		});

		return sortList;
	}

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

		// 获取收费站信息收费站人数
		List<StatisticsBean> lists = departmentDao.selectFeeStationGroup(obj);
		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);
			}
			mapStationInfos.put(sta.getDept_id(), sta);
		}

		// 检查人数 和 检查次数
		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())) {
				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());
			}
		}

		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.getAll_check_score() > o2.getAll_check_score()) {
						return 1;
					} else if (o1.getAll_check_score() < o2.getAll_check_score()) {
						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).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());
		// 处理数据
		int j = 1;
		for (Iterator<StatisticsBo> it = listStatistic.iterator(); it.hasNext(); ) {
			StatisticsBo st = it.next();
			double score = (st.getChecked_num() != 0) ? 1000 - (st.getCheck_all_score() / (st.getChecked_num())) : 1000;
			if (score >= start_score && score <= end_score) {
				// 得分
				st.setCheck_score((st.getChecked_num() != 0) ? String.format("%.2f", score) : "1000.00");
				// 平均值
				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, "工作纪律"));
			} else {
				it.remove();
			}
        }
		
		exportExcel("温馨服务考核情况反馈表", "employee_order", listStatistic, resp);
	}

	@Override
	public void getFeeStationCheckedScore(StatisticsBean obj, HttpServletRequest req, HttpServletResponse resp) {
		List<StatisticsBean> list = getFeeStationCheckedScore(obj);
		for (StatisticsBean st : list) {
			st.setCheck_no_score(
					st.getPeople_num() - st.getScore_fifteen() - st.getScore_fifteen() - 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()));
		}
		// 处理数据
		exportExcel("温馨服务检查千分考核扣分情况汇总表", "checked_info", list, resp);
	}

	@Override
	public void getFeeStationCheckItemScore(StatisticsBean obj, HttpServletRequest req, HttpServletResponse resp) {
		List<StatisticsBean> list = getFeeStationCheckItemScore(obj);
		// 处理数据
		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, "工作纪律"));
		}
		exportExcel("温馨服务检查情况统计表", "checked_item_info", list, resp);
	}

	private void exportExcel(String fileName, String excelTemplateName, List<?> list, 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", list);
				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());
		}
	}
}
