package com.zhiwei.manage.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
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 org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.recycler.Recycler.C;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.zhiwei.manage.bean.Data;
import com.zhiwei.manage.handle.MainThread;

/**
 * es工具类
 * 
 * @author admin
 */
@Component
public class ESUtil {
	private static final Logger log = LoggerFactory.getLogger(ESUtil.class);
	static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	/**
	 * 获取匹配时终止时间
	 * 
	 * @param hour
	 * @return
	 */
	public static String getTimeMax(int hour) {
		SimpleDateFormat smf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		String time = "";
		time = smf.format(date) + "T0" + (hour - 8) + ":00:00.000Z";
		return time;
	}

	/**
	 * 数据查询。获取数量
	 * 
	 * @param start
	 * @param end
	 * @param pt
	 * @param type
	 * @param value
	 * @param spyderInfoId
	 * @return
	 */
	public int getDatas(Date start, Date end, String pt, String type, String value, String spyderInfoId) {
		Calendar startTime = Calendar.getInstance();
		startTime.setTime(start);
		startTime.add(Calendar.HOUR, -8);
		Calendar endTime = Calendar.getInstance();
		endTime.setTime(end);
		endTime.add(Calendar.HOUR, -8);
		try {
			Client esClient = ESClient.getInstance();
			// 搜索数据
			SearchRequestBuilder srb = esClient.prepareSearch(Config.getVal(MainThread.map.get(pt) + ".indexName"));
			BoolQueryBuilder bb = new BoolQueryBuilder();
			srb.setQuery(bb);
			addQuerys(pt, startTime, endTime, srb, bb);
			QueryBuilder matchQuery = QueryBuilders.matchPhraseQuery(type, value);
			bb.should(matchQuery);
			srb.setSize(1);
			SearchResponse response = srb.execute().actionGet();
			SearchHits searchHits = response.getHits();
			return (int) searchHits.getTotalHits();
		} catch (Exception e) {
			log.error("es检索出错，错误信息【{}】", e);
		}
		return 0;
	}

	public static void main(String[] args) throws ParseException {
		System.out.println(new ESUtil().getCountByPt(sdf.parse("2018-04-19"), new Date(), "网媒", "media"));

	}

	public int getCounts(Date start, Date end, String pt, String value, String spid) {
		Calendar startTime = Calendar.getInstance();
		startTime.setTime(start);
		startTime.add(Calendar.HOUR, -8);
		Calendar endTime = Calendar.getInstance();
		endTime.setTime(end);
		endTime.add(Calendar.HOUR, -8);
		try {
			Client esClient = ESClient.getInstance();
			// 搜索数据
			System.out.println(pt);
			System.out.println(Config.getVal(MainThread.map.get(pt) + ".indexName"));
			SearchRequestBuilder srb = esClient.prepareSearch(Config.getVal(MainThread.map.get(pt) + ".indexName"));
			BoolQueryBuilder bb = new BoolQueryBuilder();
			srb.setQuery(bb);
			addQuerys(pt, startTime, endTime, srb, bb);
			QueryBuilder matchQuery = QueryBuilders.matchPhraseQuery("spyderInfoId", spid);
			bb.should(matchQuery);
			srb.setSize(1);
			SearchResponse response = srb.execute().actionGet();
			SearchHits searchHits = response.getHits();
			return (int) searchHits.getTotalHits();
		} catch (Exception e) {
			log.error("es检索出错，错误信息【{}】", e);
		}
		return 0;
	}

	/**
	 * 获取数量
	 * 
	 * @param start
	 * @param end
	 * @param pt
	 * @param value
	 * @return
	 */
	public int getCountByPt(Date start, Date end, String pt, String value) {
		Calendar startTime = Calendar.getInstance();
		startTime.setTime(start);
		startTime.add(Calendar.HOUR, -8);
		Calendar endTime = Calendar.getInstance();
		endTime.setTime(end);
		endTime.add(Calendar.HOUR, -8);
		try {
			Client esClient = ESClient.getInstance();
			// 搜索数据
			SearchRequestBuilder srb = esClient.prepareSearch(Config.getVal(value + ".indexName"));
			BoolQueryBuilder bb = new BoolQueryBuilder();
			srb.setQuery(bb);
			addQuerys(pt, startTime, endTime, srb, bb);
			srb.setSize(1);
			SearchResponse response = srb.execute().actionGet();
			SearchHits searchHits = response.getHits();
			return (int) searchHits.getTotalHits();
		} catch (Exception e) {
			log.error("es检索出错，错误信息【{}】", e);
		}
		return 0;
	}

	private void addQuerys(String pt, Calendar startTime, Calendar endTime, SearchRequestBuilder srb,
			BoolQueryBuilder bb) {
		if (pt.equals("微博")) {
			srb.setPostFilter(QueryBuilders.rangeQuery("ins").gte(sendTime(startTime)).lt(sendTime(endTime)));
		} else if (pt.equals("知乎")) {
			srb.setPostFilter(QueryBuilders.rangeQuery("insert_at").gte(sendTime(startTime)).lt(sendTime(endTime)));
		} else if (pt.equals("微信全量")) {
			srb.setPostFilter(QueryBuilders.rangeQuery("time").gte(sendTime(startTime)).lt(sendTime(endTime)));
		} else if (pt.equals("今日头条")) {
			srb.setPostFilter(QueryBuilders.rangeQuery("time").gte(sendTime(startTime)).lt(sendTime(endTime)));
			QueryBuilder matchQuery = QueryBuilders.matchPhraseQuery("type", pt);
			bb.should(matchQuery);
		} else if (pt.equals("客户端")) {
			srb.setPostFilter(QueryBuilders.rangeQuery("time").gte(sendTime(startTime)).lt(sendTime(endTime)));
			QueryBuilder matchQuery = QueryBuilders.wildcardQuery("type", "*客户端");
			QueryBuilder matchQuery2 = QueryBuilders.wildcardQuery("type", "脉脉");
			bb.should(matchQuery2);
			bb.should(matchQuery);
		} else {
			srb.setPostFilter(QueryBuilders.rangeQuery("time").gte(sendTime(startTime)).lt(sendTime(endTime)));
			QueryBuilder matchQuery = QueryBuilders.matchPhraseQuery("pt", pt);
			QueryBuilder matchQuery2 = QueryBuilders.matchPhraseQuery("type", pt);
			bb.should(matchQuery);
			bb.should(matchQuery2);
		}
	}

	public static String sendTime(Calendar time) {
		return sdf.format(time.getTime()) + "T"
				+ (time.get(Calendar.HOUR_OF_DAY) >= 10 ? time.get(Calendar.HOUR_OF_DAY) + ""
						: "0" + time.get(Calendar.HOUR_OF_DAY))
				+ ":00:00.000Z";
	}

	public static List<String> getNewsForWechatWithMechanism(Date start, Date end) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd日HH:mm:ss");
		Calendar startTime = Calendar.getInstance();
		// startTime.setTime(start);
		// startTime.add(Calendar.HOUR, -8);
		// Calendar endTime = Calendar.getInstance();
		// endTime.setTime(end);
		// endTime.add(Calendar.HOUR, -8);
		try {
			log.info("检索开始");
			Client esClient = ESClient.getInstance();
			// 搜索数据
			SearchRequestBuilder srb = esClient.prepareSearch(Config.getVal("weibo.indexName"));
			BoolQueryBuilder bb = new BoolQueryBuilder();
			// QueryBuilder matchQuery2 = QueryBuilders.matchPhraseQuery("pt", "");
			// bb.should(matchQuery2);
			srb.setQuery(bb);
			srb.setPostFilter(
					QueryBuilders.rangeQuery("ins").gte("2018-04-17T00:00:00.000Z").lt("2018-04-18T00:00:00.000Z"));
			srb.setSize(1);
			SearchResponse response = srb.execute().actionGet();
			SearchHits searchHits = response.getHits();
			System.out.println(searchHits.getTotalHits());
			for (SearchHit hit : searchHits.getHits()) {
				Map<String, Object> map = hit.getSource();
			}
			log.info("结束");
		} catch (Exception e) {
			log.error("es检索出错，错误信息【{}】", e);
		}
		return null;
	}
}
