package com.zhiweidata.bjfzxWebapp.esDao;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zhiweidata.bjfzxWebapp.entity.MediaAndWechatEvent;
import com.zhiweidata.bjfzxWebapp.entity.WeiboBusiness;
import com.zhiweidata.bjfzxWebapp.timerTask.ESSearchTimer;

public class EsFatherDAO {

	protected TransportClient transportClient = new ESClient().getInstance();
	private static Logger log = LoggerFactory.getLogger(EsFatherDAO.class);
	
	
	public List<SearchHit> findSearchHit(SearchRequestBuilder searchRequestBuilder) {
		List<SearchHit> hits = new ArrayList<SearchHit>();
		SearchResponse response = searchRequestBuilder.setSize(1).execute().actionGet();
		SearchHits searchHits = response.getHits();// 获取结果，初次只拿总数
		long count = searchHits.getTotalHits();
		int size = 500;// 500不怎么会漏数据
		// if (count < 10000)
		// {
		// size = 10000;
		// }
//		log.info("查询到数据量为【{}】", count);
		response = searchRequestBuilder.setSize(size).setScroll(TimeValue.timeValueMillis(10000)).execute().actionGet();
		searchHits = response.getHits();// 获取结果
		if (searchHits.getHits() != null && searchHits.getHits().length > 0) {
			hits.addAll(Arrays.asList(searchHits.getHits()));
		}

		long sum = searchHits.hits().length;
		long addNum;
		String scrollId = "";
		for (int i = 0; sum < count; i++) {
			scrollId = response.getScrollId();// 获取查询记录点，相当于游标
			response = transportClient.prepareSearchScroll(scrollId)
					// 直接由断点继续获取
					.setScroll(TimeValue.timeValueMillis(80000)).execute().actionGet();
			searchHits = response.getHits();
			addNum = searchHits.hits().length;
			if (searchHits.getHits() != null && searchHits.getHits().length > 0) {
				hits.addAll(Arrays.asList(searchHits.getHits()));
			}
			sum += addNum;
			if (addNum <= 0) {
				break;
			}
		}
		return hits;
	}
	
	/**
	 * 
	 * @Title: findSearchWechat   
	 * @Description: TODO(断点查询时直接转换为数据对象)     
	 * @param: @param searchRequestBuilder
	 * @param: @param groupName
	 * @param: @param key
	 * @param: @return      
	 * @return: List<MediaAndWechatEvent>      
	 * @throws  
	 * @date:   2018年4月11日 上午10:58:14
	 */
	public List<MediaAndWechatEvent> findSearchWechat(SearchRequestBuilder searchRequestBuilder,String groupName,String key) {
		List<MediaAndWechatEvent> hits = new ArrayList<MediaAndWechatEvent>();
		SearchResponse response = searchRequestBuilder.setSize(1).execute().actionGet();
		SearchHits searchHits = response.getHits();// 获取结果，初次只拿总数
		long count = searchHits.getTotalHits();
		int size = 500;// 500不怎么会漏数据
		// if (count < 10000)
		// {
		// size = 10000;
		// }
		// log.debug("查询到数据量为【{}】", count);
		response = searchRequestBuilder.setSize(size).setScroll(TimeValue.timeValueMillis(10000)).execute().actionGet();
		searchHits = response.getHits();// 获取结果
		if (searchHits.getHits() != null && searchHits.getHits().length > 0) {
			hits.addAll(ResultHis2Wechat(Arrays.asList(searchHits.getHits()), groupName, key));
		}

		long sum = searchHits.hits().length;
		long addNum;
		String scrollId = "";
		for (int i = 0; sum < count; i++) {
			scrollId = response.getScrollId();// 获取查询记录点，相当于游标
			response = transportClient.prepareSearchScroll(scrollId)
					// 直接由断点继续获取
					.setScroll(TimeValue.timeValueMillis(80000)).execute().actionGet();
			searchHits = response.getHits();
			addNum = searchHits.hits().length;
			if (searchHits.getHits() != null && searchHits.getHits().length > 0) {
				hits.addAll(ResultHis2Wechat(Arrays.asList(searchHits.getHits()), groupName, key));
			}
			sum += addNum;
			if (addNum <= 0) {
				break;
			}
		}
		return hits;
	}
	
	public List<MediaAndWechatEvent> findSearchMedia(SearchRequestBuilder searchRequestBuilder,String groupName,String key) {
		List<MediaAndWechatEvent> hits = new ArrayList<MediaAndWechatEvent>();
		SearchResponse response = searchRequestBuilder.setSize(1).execute().actionGet();
		SearchHits searchHits = response.getHits();// 获取结果，初次只拿总数
		long count = searchHits.getTotalHits();
		int size = 500;// 500不怎么会漏数据
		// if (count < 10000)
		// {
		// size = 10000;
		// }
		// log.debug("查询到数据量为【{}】", count);
		response = searchRequestBuilder.setSize(size).setScroll(TimeValue.timeValueMillis(10000)).execute().actionGet();
		searchHits = response.getHits();// 获取结果
		if (searchHits.getHits() != null && searchHits.getHits().length > 0) {
			hits.addAll(ResultHis2Media(Arrays.asList(searchHits.getHits()), groupName, key));
		}

		long sum = searchHits.hits().length;
		long addNum;
		String scrollId = "";
		for (int i = 0; sum < count; i++) {
			scrollId = response.getScrollId();// 获取查询记录点，相当于游标
			response = transportClient.prepareSearchScroll(scrollId)
					// 直接由断点继续获取
					.setScroll(TimeValue.timeValueMillis(80000)).execute().actionGet();
			searchHits = response.getHits();
			addNum = searchHits.hits().length;
			if (searchHits.getHits() != null && searchHits.getHits().length > 0) {
				hits.addAll(ResultHis2Media(Arrays.asList(searchHits.getHits()), groupName, key));
			}
			sum += addNum;
			if (addNum <= 0) {
				break;
			}
		}
		return hits;
	}
	
	public List<WeiboBusiness> findSearchWeibo(SearchRequestBuilder searchRequestBuilder,String groupName,String key) {
		List<WeiboBusiness> hits = new ArrayList<WeiboBusiness>();
		SearchResponse response = searchRequestBuilder.setSize(1).execute().actionGet();
		SearchHits searchHits = response.getHits();// 获取结果，初次只拿总数
		long count = searchHits.getTotalHits();
		int size = 500;// 500不怎么会漏数据
		response = searchRequestBuilder.setSize(size).setScroll(TimeValue.timeValueMillis(10000)).execute().actionGet();
		searchHits = response.getHits();// 获取结果
		if (searchHits.getHits() != null && searchHits.getHits().length > 0) {
			hits.addAll(ResultHis2Weibo(Arrays.asList(searchHits.getHits()), groupName, key));
		}

		long sum = searchHits.hits().length;
		long addNum;
		String scrollId = "";
		for (int i = 0; sum < count; i++) {
			scrollId = response.getScrollId();// 获取查询记录点，相当于游标
			response = transportClient.prepareSearchScroll(scrollId)
					// 直接由断点继续获取
					.setScroll(TimeValue.timeValueMillis(80000)).execute().actionGet();
			searchHits = response.getHits();
			addNum = searchHits.hits().length;
			if (searchHits.getHits() != null && searchHits.getHits().length > 0) {
				hits.addAll(ResultHis2Weibo(Arrays.asList(searchHits.getHits()), groupName, key));
			}
			sum += addNum;
			if (addNum <= 0) {
				break;
			}
		}
		return hits;
	}
	
	private List<WeiboBusiness> ResultHis2Weibo(List<SearchHit> hits, String groupName, String key) {
		List<WeiboBusiness> list = new ArrayList<>();
		try {
			if (hits.size() <= 0) {
				return null;
			}
			for (SearchHit hit : hits) {
				Map<String, Object> news = hit.getSource();

				WeiboBusiness weiboBusiness = new WeiboBusiness();
				weiboBusiness.setId(key + news.get("id"));
				weiboBusiness.setKeyword(key);
				weiboBusiness.setUid(news.get("user_id").toString());
				weiboBusiness.setUsername(news.get("username").toString());
				weiboBusiness.setVtype(0);
				weiboBusiness.setFensi(0);
				weiboBusiness.setGuanzhu(0);
				weiboBusiness.setWeibo(0);
				weiboBusiness.setSex(news.get("sex").toString());
				weiboBusiness.setLocation(news.get("location").toString());
				weiboBusiness.setDescription(news.get("description").toString());
				weiboBusiness.setReason("");
				weiboBusiness.setImg_url(news.get("weibo_img").toString());
				weiboBusiness.setMid(news.get("id").toString());
				weiboBusiness.setReposts_count(0);
				weiboBusiness.setComments_count(0);
				weiboBusiness.setHdl_count(0);
				weiboBusiness.setUrl(news.get("url").toString());
				weiboBusiness.setText(news.get("text").toString());

				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				weiboBusiness.setCreatedAt(sdf.parse(news.get("time").toString()));

				weiboBusiness.setSource(news.get("source").toString());
				weiboBusiness.setIsForword((Integer) news.get("isForword"));
				weiboBusiness.setSaveTime(new Date().getTime());
				weiboBusiness.setGroupName(groupName);

				list.add(weiboBusiness);
			}
		} catch (Exception e) {
			return list;
		}
		return list;
	}

	private List<MediaAndWechatEvent> ResultHis2Media(List<SearchHit> hits, String groupName, String key) {
		List<MediaAndWechatEvent> list = new ArrayList<>();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");

			if (hits.size() <= 0) {
				return null;
			}
			String content;
			for (SearchHit hit : hits) {
				Map<String, Object> news = hit.getSource();

				MediaAndWechatEvent event = new MediaAndWechatEvent();
				event.set_id(news.get("id") + "_" + key);
				event.setUrl(news.get("id").toString());
				event.setTitle(news.get("title").toString());

				String date = news.get("time").toString().replaceAll("Z", " UTC");
				Date d = sdf.parse(date);
				event.setTime(d);
				content = news.get("content").toString();
				content = content.length() > 100 ? content.substring(0, 100) : content;
				event.setContent(content);
				event.setSource(news.get("source").toString());
				event.setPt("百度新闻");
				event.setType("百度新闻");
				event.setSavetime(new Date().getTime());
				event.setGroupName(groupName);
				event.setKeyword(key);

				list.add(event);
			}
		} catch (Exception e) {
			return list;
		}
		return list;
	}

	private List<MediaAndWechatEvent> ResultHis2Wechat(List<SearchHit> hits, String groupName, String key) {
		List<MediaAndWechatEvent> list = new ArrayList<>();

		try {
			String content;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
			for (SearchHit hit : hits) {
				Map<String, Object> news = hit.getSource();
				MediaAndWechatEvent event = new MediaAndWechatEvent();
				event.set_id(news.get("id") + "_" + key);
				event.setUrl(news.get("id").toString());
				event.setTitle(news.get("title").toString());
				String date = news.get("time").toString().replaceAll("Z", " UTC");
				Date d = sdf.parse(date);
				event.setTime(d);
				content = news.get("content").toString();
				content = content.length() > 100 ? content.substring(0, 100) : content;
				event.setContent(content);
				event.setSource(news.get("source").toString());
				event.setPt("微信");
				event.setType("微信");
				event.setSavetime(new Date().getTime());
				event.setGroupName(groupName);
				event.setKeyword(key);
				list.add(event);
			}
		} catch (Exception e) {
			return list;
		}
		return list;
	}
}
