/** 
 * @Title: sss.java 
 * @Package com.zhiweidata.bjfzxWebapp.timerTask 
 * @Description: TODO(用一句话描述该文件做什么) 
 * @author xuyimeng 
 * @date 2018年2月6日 上午11:18:20 
 * @version V1.0 
 */ /**
 * 
 */
package com.zhiweidata.bjfzxWebapp.timerTask;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimerTask;
import java.util.TreeMap;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zhiwei.weixin.service.TemplateService;
import com.zhiweidata.bjfzxWebapp.conf.StaticConfig;
import com.zhiweidata.bjfzxWebapp.entity.Keyword;
import com.zhiweidata.bjfzxWebapp.entity.MediaAndWechatEvent;
import com.zhiweidata.bjfzxWebapp.entity.WeiboBusiness;
import com.zhiweidata.bjfzxWebapp.exception.ZhiweiException;
import com.zhiweidata.bjfzxWebapp.mongoDao.MediaAndWechatEventDAO;
import com.zhiweidata.bjfzxWebapp.mongoDao.WeiboBusinessDao;
import com.zhiweidata.bjfzxWebapp.service.KeysWordSerivce;
import com.zhiweidata.bjfzxWebapp.util.TimeUtil;

import net.sf.json.JSONObject;

/** 
 * @ClassName: SendMessageTimerTask 
 * @Description: TODO(发送推送的定时器) 
 * @author xuyimeng 
 * @date 2018年2月6日 上午11:18:20  
 */
public class SendMessageTimerTask extends TimerTask {

	private static Logger log = LoggerFactory.getLogger(SendMessageTimerTask.class);
	private Long ex_startTime = Long.valueOf(0); // 上次run的开始时间,假定第一次运行的上一次时间是8小时前

	private KeysWordSerivce keysWordSerivce;

	private MediaAndWechatEventDAO mediaDao;

	private WeiboBusinessDao weiboDao;

	/**
	 * @class SendMessageTimerTask 定时给微信发送信息
	 * @param keywordDao
	 * @param mediaDao
	 * @param weiboDao
	 * @param weixinDao
	 */
	public SendMessageTimerTask(KeysWordSerivce keysWordSerivce, MediaAndWechatEventDAO mediaDao, WeiboBusinessDao weiboDao) {
		super();
		this.keysWordSerivce = keysWordSerivce;
		this.mediaDao = mediaDao;
		this.weiboDao = weiboDao;
	}

	public SendMessageTimerTask() {
		super();
	}

	@Override
	public void run() {
		// 当前时间
		Date nowdate = new Date();

		// 截取实际到当前小时
		String now = TimeUtil.formatDateToHour(nowdate);

		// 中心组
//		if (isSendTime(now, StaticConfig.ZXtimeList)) {
//
//			String groupName = StaticConfig.ZXGroup;
//			String groupWeixin = StringUtils.isNotEmpty(StaticConfig.TEST) ? StaticConfig.TEST : StaticConfig.ZXGroup;
//			String startTime = TimeUtil.formatDateToHour(TimeUtil.getSkipTime(nowdate, 0, -1, 0, 0, 0));
//
//			sendMessageByParam(now, startTime, groupName, groupWeixin);
//		}

		// 质检中心
		if (isSendTime(now, StaticConfig.ZJtimeList)) {

			String groupName = StaticConfig.ZJGroup;
			String groupWeixin = StringUtils.isNotEmpty(StaticConfig.TEST) ? StaticConfig.TEST : StaticConfig.ZJGroup;
			String startTime = TimeUtil.formatDateToHour(TimeUtil.getSkipTime(nowdate, -1));

			sendMessageByParam(now, startTime, groupName, groupWeixin);
		}
		
		// 北京副中心
		if (isSendTime(now, StaticConfig.bjfzxTimeList)) {
			String end = now;
			if (ex_startTime == 0) {
				Date aroundZdDate = TimeUtil.parseHour(TimeUtil.formatDateToHour(nowdate));
				ex_startTime = aroundZdDate.getTime() - 4 * 60 * 60 * 1000;
			}

			String sta = TimeUtil.formatDateToHour(new Date(ex_startTime));
			String groupName = StaticConfig.BJFZXGroup;
			String groupWeixin = StringUtils.isNotEmpty(StaticConfig.TEST) ? StaticConfig.TEST
					: StaticConfig.BJFZXGroup;
			sendMessageByParam(end, sta, groupName, groupWeixin);
			ex_startTime = nowdate.getTime();
		}

		// 质检小黄车
		if (isSendTime(now, StaticConfig.OFOtimeList)) {

			String groupName = StaticConfig.OFOGroup;
			String groupWeixin = StringUtils.isNotEmpty(StaticConfig.TEST) ? StaticConfig.TEST : StaticConfig.OFOGroup;
			String startTime = TimeUtil.formatDateToHour(TimeUtil.getSkipTime(nowdate, 0, -1, 0, 0, 0));

			sendMessageByParam(now, startTime, groupName, groupWeixin);
		}

		//交易所
		if (isSendTime(now, StaticConfig.jyTimeList)) {
			
			String groupName = StaticConfig.JYGroup;
			String groupWeixin = StringUtils.isNotEmpty(StaticConfig.TEST) ? StaticConfig.TEST : StaticConfig.JYGroup;
			String startTime = TimeUtil.formatDateToHour(TimeUtil.getSkipTime(nowdate, 0, -1, 0, 0, 0));
			
			sendMessageByParam(now, startTime, groupName, groupWeixin);
		}
		
		// 神户
//		if (isSendTime(now, StaticConfig.SHENHUtimeList)) {
//			String groupName = StaticConfig.SHENHUGroup;
//			String groupWeixin = StringUtils.isNotEmpty(StaticConfig.TEST) ? StaticConfig.TEST : StaticConfig.SHENHUGroup;
//			String startTime = TimeUtil.formatDateToHour(TimeUtil.getSkipTime(nowdate, 0, -1, 0, 0, 0));
//			sendMessageByParam(now, startTime, groupName, groupWeixin);
//		}
		
		//test
//		if (isSendTime(now, StaticConfig.jyTimeList)) {
//			
//			String groupName = StaticConfig.JYGroup;
//			String groupWeixin = StringUtils.isNotEmpty(StaticConfig.TEST) ? StaticConfig.TEST : StaticConfig.JYGroup;
//			String startTime = TimeUtil.formatDateToHour(TimeUtil.getSkipTime(nowdate, 0, -1, 0, 0, 0));
//			
//			sendMessageByParam(now, startTime, groupName, groupWeixin);
//		}
		
	}

	/**
	 *
	 * @author: 落花流水 2017年4月15日 下午2:33:13
	 * @return
	 *
	 */
	private boolean isSendTime(String end, int[] timeList) {
		int zd = Integer.valueOf(end.split(" ")[1]);
		boolean flag = false;
		for (int x : timeList) {
			if (x == zd) {
				flag = true;
				break;
			}
		}
		return flag;
	}

	/**
	 * 根据参数发送微信模板数据
	 * 
	 * @author: 落花流水 2017年4月15日 下午2:27:00
	 * @param end
	 * @param sta
	 * @param groupName
	 * @param groupWeixin
	 *
	 */
	public void sendMessageByParam(String end, String sta, String groupName, String groupWeixin) {
		for (int j = 0; j < 3; j++) {
			try {
				sendWechat(sta, end, groupName, groupWeixin);
				break;
			} catch (ZhiweiException e) {
				e.printStackTrace();
			}
		}
	}

	public void sendWechat(String sta, String end, String groupName, String groupWeixin) throws ZhiweiException {
		log.info("微信模板发送开始：【{}】", TimeUtil.getCurrentTimeStr());
		TemplateService templateService = new TemplateService();
		String template_id_short = "OPENTM207188516";
		String url = "http://ef.zhiweidata.com/bjfzx/#index/t" + end + ":00:00/" + groupName;
//		 String url = "http://192.168.0.239:8080/bjfzxWebapp/#index/t" + end +
//		 ":00:00/" + groupName;// 用于测试
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		HashMap<String, String> firstMap = new HashMap<String, String>();
		firstMap.put("value", "Top10关键词");

		HashMap<String, String> keyword1Map = new HashMap<String, String>();
		keyword1Map.put("value", "自动预警");

		HashMap<String, String> keyword2Map = new HashMap<String, String>();
		String content = "";
		Map<String, Integer> contentTreeMap = new TreeMap<String, Integer>();
		List<Keyword> keywords = keysWordSerivce.findNoShieldListByGroup(groupName);
		for (Keyword keyword : keywords) {
			String kString = keyword.getKeyword();
			int count_media = (int)countlastMedia(kString, sta, end);
			int conut_weibo = (int)countLastWeibo(kString, sta, end);
			int count = count_media + conut_weibo;
			if (count > 0) {
				contentTreeMap.put(kString, count);
			}
		}
		int i = 0;
		// 进行排序
		Map<String, Integer> contentResultMap = sortMapByValue(contentTreeMap);
		try {
			for (Entry<String, Integer> entry : contentResultMap.entrySet()) {
				if (i >= 10) {
					break;
				}
				i++;
				content = content + "\r\n" + entry.getKey() + ":" + entry.getValue();
			}
		} catch (NullPointerException e) {
			// content = content + "无数据";
			log.error("无数据：{}", e);
		}
		// keyword2Map.put("value",
		// "\r\n核安全:54\r\n核试验:37\r\n核动力:14
		// \r\n中广核集团:13\r\n核事故:10\r\n法国核电:7\r\n浙江+核电:6\r\n中央研究院:6\r\n中国电力投资集团:6\r\n山东院:5");
		keyword2Map.put("value", content);

		dataMap.put("first", firstMap);
		dataMap.put("keyword1", keyword1Map);
		dataMap.put("keyword2", keyword2Map);
		JSONObject resultjson = new JSONObject();

		resultjson.put("groupName", groupWeixin);
		resultjson.put("template_id_short", template_id_short);
		resultjson.put("url", url);
		resultjson.put("dataMap", dataMap);
		
		if (!"".equals(content)) {
			int k = templateService.sendTemplate(resultjson);
			log.info("微信模板发送结束：【sendTemplate result={}， {}】", k, TimeUtil.getCurrentTimeStr());
		} else {
			log.info("微信模板发送结束：【sendTemplate result={}， {}】", "无数据", TimeUtil.getCurrentTimeStr());
		}

	}

	/**
	 * 获取最近一小时内的百度新闻 和 微信
	 * 
	 * @return
	 * @throws ParseException
	 */
	public List<MediaAndWechatEvent> getlastHourMedia(String keyword) throws ZhiweiException {
		return mediaDao.findLastHour(keyword);
	}

	/**
	 * 获取最近一小时内的微博
	 * 
	 * @return
	 * @throws ParseException
	 */
	public List<WeiboBusiness> getLastHourWeibo(String keyword) throws ZhiweiException {
		return weiboDao.findLastHour(keyword);
	}

	/**
	 * 获取从上一段时间到现在的 百度新闻 和 微信
	 * 
	 * @return
	 * @throws ParseException
	 */
	public List<MediaAndWechatEvent> getlastMedia(String keyword, String sta, String end) throws ZhiweiException {
		sta = sta + ":00:00";
		end = end + ":00:00";
		return mediaDao.findLast(keyword, sta, end);
	}

	public long countlastMedia(String keyword, String sta, String end) throws ZhiweiException {
		sta = sta + ":00:00";
		end = end + ":00:00";
		return mediaDao.countLast(keyword, sta, end);
	}
	
	/**
	 * 获取从上一段时间到现在的 微博
	 * 
	 * @return
	 * @throws ParseException
	 */
	public List<WeiboBusiness> getLastWeibo(String keyword, String sta, String end) throws ZhiweiException {
		sta = sta + ":00:00";
		end = end + ":00:00";
		return weiboDao.findLast(keyword, sta, end);
	}
	
	/**
	 * 获取从上一段时间到现在的 微博
	 * 
	 * @return
	 * @throws ParseException
	 */
	public long countLastWeibo(String keyword, String sta, String end) throws ZhiweiException {
		sta = sta + ":00:00";
		end = end + ":00:00";
		return weiboDao.countLast(keyword, sta, end);
	}

	/**
	 * 使用 Map按value进行排序
	 * 
	 * @param map
	 * @return
	 */
	public static Map<String, Integer> sortMapByValue(Map<String, Integer> oriMap) {
		if (oriMap == null || oriMap.isEmpty()) {
			return null;
		}
		Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
		List<Map.Entry<String, Integer>> entryList = new ArrayList<Map.Entry<String, Integer>>(oriMap.entrySet());
		Collections.sort(entryList, new MapValueComparator());

		Iterator<Map.Entry<String, Integer>> iter = entryList.iterator();
		Map.Entry<String, Integer> tmpEntry = null;
		while (iter.hasNext()) {
			tmpEntry = iter.next();
			sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
		}
		return sortedMap;
	}

}

class MapValueComparator implements Comparator<Map.Entry<String, Integer>> {

	@Override
	public int compare(Entry<String, Integer> me1, Entry<String, Integer> me2) {

		return me2.getValue().compareTo(me1.getValue());
	}
}