/** 
 * @Title: WeiboAndMediaSerivceImpl.java 
 * @Package com.zhiweidata.bjfzxWebapp.service.Impl 
 * @Description: TODO(用一句话描述该文件做什么) 
 * @author xuyimeng 
 * @date 2018年2月6日 下午4:48:17 
 * @version V1.0 
 */ /**
 * 
 */
package com.zhiweidata.bjfzxWebapp.service.Impl;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.mongodb.DBObject;
import com.zhiweidata.bjfzxWebapp.conf.StaticConfig;
import com.zhiweidata.bjfzxWebapp.entity.MediaAndWechatEvent;
import com.zhiweidata.bjfzxWebapp.entity.WeiboBusiness;
import com.zhiweidata.bjfzxWebapp.mongoDao.MediaAndWechatEventDAO;
import com.zhiweidata.bjfzxWebapp.mongoDao.WeiboBusinessDao;
import com.zhiweidata.bjfzxWebapp.service.KeysWordSerivce;
import com.zhiweidata.bjfzxWebapp.service.WeiboAndMediaSerivce;
import com.zhiweidata.bjfzxWebapp.util.TimeUtil;
import com.zhiweidata.bjfzxWebapp.util.Tools;
import com.zhiweidata.bjfzxWebapp.util.TreatOrder;

/** 
 * @ClassName: WeiboAndMediaSerivceImpl 
 * @Description: TODO(这里用一句话描述这个类的作用) 
 * @author xuyimeng 
 * @date 2018年2月6日 下午4:48:17  
 */
@Service
public class WeiboAndMediaSerivceImpl implements WeiboAndMediaSerivce{
	@Resource
	WeiboBusinessDao weiboBusinessDAO;
	
	@Resource
	MediaAndWechatEventDAO mediaAndWechatEventDAO;
	
	@Resource
	KeysWordSerivce keysWordSerivce;
	
	private static final String special = "08";
    
    private static SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    private static SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH");
	
	@Override
	public List<Map<String, Object>> getInfoByThemeAndTime_1H(String keyword, Date date, String groupName) {
		List<DBObject> dbolist = findAllFollowTime_1H(date, groupName);
        ArrayList<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
        for (DBObject dbObject : dbolist)
        {
            Map<String, Object> assay = new HashMap<String, Object>();
            String type = (String)dbObject.get("type");
            if (type == null)// 微博
            {
                assay.put("account", dbObject.get("username").toString());
                assay.put("keyword", dbObject.get("keyword").toString());
                assay.put("content", dbObject.get("text").toString());
                assay.put("url", dbObject.get("url").toString());
                assay.put("source", "来自" + "微博");
                assay.put("time", sdf1.format((Date)dbObject.get("createdAt")));
                assay.put("theme", dbObject.get("keyword").toString());
                assay.put("keywords", dbObject.get("keyword").toString());
                lists.add(assay);
                continue;
            }
            if ("百度新闻".equals(type.toString()) || type.toString().indexOf("微信") > -1)
            {
                assay.put("account", dbObject.get("source").toString());
                assay.put("title", dbObject.get("title").toString());
                assay.put("keyword", dbObject.get("keyword").toString());
                assay.put("content", dbObject.get("content").toString());
                assay.put("url", dbObject.get("url").toString());
                assay.put("source", "来自微信");
                if ("百度新闻".equals(type))
                {
                    assay.put("source", "来自" + "网媒");
                }
                assay.put("time", sdf1.format((Date)dbObject.get("time")));
                assay.put("theme", dbObject.get("keyword").toString());
                assay.put("keywords", dbObject.get("keyword").toString());
                lists.add(assay);
                continue;
            }
        }
        // 筛选主题
        ArrayList<Map<String, Object>> listsByTheme = new ArrayList<Map<String, Object>>();
        if ("全部".equals(keyword))
        {
            return (ArrayList<Map<String, Object>>)TreatOrder.treatOrderByDateDesc(lists);
        }
        else
        {
            for (Map<String, Object> map : lists)
            {
                if (keyword.equals(map.get("keyword").toString()))
                {
                    listsByTheme.add(map);
                }
            }
            return (ArrayList<Map<String, Object>>)TreatOrder.treatOrderByDateDesc(listsByTheme);
        }
	}

	@Override
	public List<DBObject> findAllFollowTime_1H(Date date, String groupName) {
		List<DBObject> list = new ArrayList<>();
		try 
		{
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.add(Calendar.HOUR_OF_DAY, -1);
			Date startTime = calendar.getTime();
			
			Query mediaQuery = new Query();
			mediaQuery.addCriteria(Criteria.where("time").gte(startTime).lt(date));
			mediaQuery.addCriteria(Criteria.where("groupName").is(groupName));
			mediaQuery.with(new Sort(Direction.DESC,"time"));
			
			List<MediaAndWechatEvent> medias = mediaAndWechatEventDAO.find(mediaQuery);
			
			if (medias.size() > 0 )
			{
				System.out.println(true);
			}
			
			Query weiboQuery = new Query();
			weiboQuery.addCriteria(Criteria.where("createdAt").gte(startTime).lt(date));
			weiboQuery.addCriteria(Criteria.where("groupName").is(groupName));
			weiboQuery.with(new Sort(Direction.DESC,"createdAt"));
			
			List<WeiboBusiness> weibos = weiboBusinessDAO.find(weiboQuery);
			
			for (MediaAndWechatEvent media : medias)
			{
				DBObject obj = Tools.bean2DBObject(media);
				list.add(obj);
			}
			
			for (WeiboBusiness weibo : weibos)
			{
				DBObject obj = Tools.bean2DBObject(weibo);
				list.add(obj);
			}
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		
		return list;
	}
	
	
	private static Date getStartTimeByGroup(Date date, String groupName)
    {
        Date startDate = null;
        int skipDay = 0;
        int skipHour = 0;
        if (StaticConfig.ZJGroup.equals(groupName)||StaticConfig.ZXGroup.equals(groupName)||StaticConfig.OFOGroup.equals(groupName)||StaticConfig.SHENHUGroup.equals(groupName))
        {
            skipDay = -1;
        }
        else if (StaticConfig.BJFZXGroup.equals(groupName) || StaticConfig.JYGroup.equals(groupName))
        {
            skipHour = -4;
            String dateStr = TimeUtil.formatDate(date, "yyyy-MM-dd HH").split(" ")[1];
            if (special.equals(dateStr))
            {
                skipHour = -12;
            }
        }
        startDate = TimeUtil.getSkipTime(date, skipDay, skipHour, 0, 0);
        return startDate;
    }

	
	@Override
	public List<DBObject> findAllFollowTime_XH(Date date, String groupName) {
		List<DBObject> list = new ArrayList<>();
		try 
		{
			Date startTime = getStartTimeByGroup(date, groupName);
			
			Query mediaQuery = new Query();
			mediaQuery.addCriteria(Criteria.where("time").gte(startTime).lt(date));
			mediaQuery.addCriteria(Criteria.where("groupName").is(groupName));
			mediaQuery.with(new Sort(Direction.DESC,"time"));
			
			List<MediaAndWechatEvent> medias = mediaAndWechatEventDAO.find(mediaQuery);
			
			Query weiboQuery = new Query();
			weiboQuery.addCriteria(Criteria.where("createdAt").gte(startTime).lt(date));
			weiboQuery.addCriteria(Criteria.where("groupName").is(groupName));
			weiboQuery.with(new Sort(Direction.DESC,"createdAt"));
			
			List<WeiboBusiness> weibos = weiboBusinessDAO.find(weiboQuery);
			
			for (MediaAndWechatEvent media : medias)
			{
				DBObject obj = Tools.bean2DBObject(media);
				list.add(obj);
			}
			
			for (WeiboBusiness weibo : weibos)
			{
				DBObject obj = Tools.bean2DBObject(weibo);
				list.add(obj);
			}
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		
		return list;
	}

	@Override
	public List<String> getKeywordsByGroup(String groupName) {
		try 
		{
			return keysWordSerivce.findAllKeyByGroup(groupName);
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		return null;
	}

	
	@Override
	public List<Map<String, Object>> getInfoByKeywordAndTime(String keyWord, Date date, String groupName) {
		List<DBObject> dbolist = findAllFollowTime_1H(date, groupName);
        List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
        
        for (DBObject dbObject : dbolist)
        {
            
            // 筛选关键字
            if (!keyWord.equals(dbObject.get("keyword").toString()))
            {
                continue;
            }
            
            Map<String, Object> assay = new HashMap<String, Object>();
            String type = (String)dbObject.get("type");
            if (type == null)
            {
                assay.put("account", dbObject.get("username").toString());
                assay.put("keyword", dbObject.get("keyword").toString());
                assay.put("content", dbObject.get("text").toString());
                assay.put("url", dbObject.get("url").toString());
                assay.put("source", "来自" + "微博");
                assay.put("time", sdf1.format((Date)dbObject.get("createdAt")));
                assay.put("theme", dbObject.get("keyword").toString());
                assay.put("keywords", dbObject.get("keyword").toString());
                lists.add(assay);
                continue;
            }
            if ("百度新闻".equals(type.toString()) || type.toString().indexOf("微信") > -1)
            {
                assay.put("account", dbObject.get("source").toString());
                assay.put("keyword", dbObject.get("keyword").toString());
                assay.put("content", dbObject.get("content").toString());
                assay.put("url", dbObject.get("url").toString());
                assay.put("source", "来自" + type);
                if ("百度新闻".equals(type))
                {
                    assay.put("source", "来自" + "网媒");
                }
                assay.put("time", sdf1.format((Date)dbObject.get("time")));
                assay.put("theme", dbObject.get("keyword").toString());
                assay.put("keywords", dbObject.get("keyword").toString());
                lists.add(assay);
                continue;
            }
            
        }
        
        return (ArrayList<Map<String, Object>>)TreatOrder.treatOrderByDateDesc(lists);
	}
}
