package com.zhiwei.finance;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import org.bson.Document;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
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.tools.timeparse.TimeParse;
import com.zhiwei.util.Config;
import com.zhiwei.util.MongoConnection;
import com.zhiwei.util.ReadExcel;
import com.zw.entity.NewsResult;

/**
 * es工具类
 * 
 * @author admin
 */
@Component
public class ESUtil {
	private static final Logger log = LoggerFactory.getLogger(ESUtil.class);
	private static MongoConnection con = new MongoConnection();
	private static Client esClient = ESClient.getInstance();

	/**
	 * 获取匹配时终止时间
	 * 
	 * @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 date
	 * @return
	 */
	public static Calendar getStringToCal(String date) {
		final String year = date.substring(0, 4);
		final String month = date.substring(5, 7);
		final String day = date.substring(8, 10);
		final String hour = date.substring(11, 13);
		final String minute = date.substring(14, 16);
		final String second = date.substring(17, 19);
		final int millisecond = Integer.valueOf(date.substring(20, 23));
		Calendar result = new GregorianCalendar(Integer.valueOf(year), Integer.valueOf(month) - 1, Integer.valueOf(day),
				Integer.valueOf(hour), Integer.valueOf(minute), Integer.valueOf(second));
		result.set(Calendar.MILLISECOND, millisecond);
		result.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
		return result;
	}

	public static void main(String[] args) {
		Client esClient = ESClient.getInstance();
		SearchRequestBuilder srb = esClient.prepareSearch("mediaspider*");
		BoolQueryBuilder bb = new BoolQueryBuilder();
		// if (type.equals("weibo")) {
		// QueryBuilder matchQuery = QueryBuilders.termQuery("messages", key);
		// bb.should(matchQuery);
		// srb.setQuery(bb);
		// } else {
		QueryBuilder matchQuery = QueryBuilders.termQuery("title", "王者荣耀：看老外是如何玩王者荣耀的？");
		bb.should(matchQuery);
		srb.setQuery(bb);
		// }
		srb.setSize(1);
		SearchResponse response = srb.execute().actionGet();
		SearchHits searchHits = response.getHits();
		for (SearchHit hit : searchHits.getHits()) {
			System.out.println(hit.getSource().get("title"));
		}
	}

	/**
	 * 推送
	 * 
	 * @param start
	 * @param end
	 * @return
	 */
	public static List<NewsResult> pushByKey(Date start, Date end, List<String> sources, String type) {
		log.info("开始执行检索" + type + ":" + Config.getVal("indexName." + type));
		List<NewsResult> result = new ArrayList<>();
		List<NewsResult> lists = new ArrayList<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar startTime = Calendar.getInstance();
		startTime.setTime(start);
		startTime.add(Calendar.HOUR, -8);
		Calendar endTime = Calendar.getInstance();
		endTime.setTime(end);
		endTime.add(Calendar.HOUR, -8);
		System.out.println("===============");
		int startHour = startTime.get(Calendar.HOUR_OF_DAY);
		int endHour = endTime.get(Calendar.HOUR_OF_DAY);
		System.out.println(
				sdf.format(startTime.getTime()) + "T" + (startHour > 10 ? startHour : "0" + startHour) + ":00:00.000Z");
		System.out.println(
				sdf.format(endTime.getTime()) + "T" + (endHour > 10 ? endHour : "0" + endHour) + ":00:00.000Z");
		System.out.println("===============");
		List<String> keys = new ArrayList<String>();
		String path = "";
		path = ESUtil.class.getClassLoader().getResource("pushFiles/pushkey.xls").getPath();
		Document doc = con.find("financePush", "excelPath", new Document().append("name", "key"));
		if (doc != null) {
			if (doc.getString("url") != null) {
				path = doc.getString("url");
			}
		}
		keys = new ReadExcel().getExcel(path);
		try {
			String indexName = getIndex(start, type);
			for (String key : keys) {
				SearchRequestBuilder srb = esClient.prepareSearch(indexName);
				BoolQueryBuilder bb = new BoolQueryBuilder();
				QueryBuilder matchQuery = QueryBuilders.termQuery("content", key);
				bb.should(matchQuery);
				srb.setQuery(bb);
				srb.setPostFilter(QueryBuilders.rangeQuery("time")
						.gte(sdf.format(startTime.getTime()) + "T" + (startHour > 10 ? startHour : "0" + startHour)
								+ ":00:00.000Z")
						.lte(sdf.format(endTime.getTime()) + "T" + (endHour > 10 ? endHour : "0" + endHour)
								+ ":00:00.000Z"));
				srb.setSize(500);
				SearchResponse response = srb.execute().actionGet();
				SearchHits searchHits = response.getHits();
				for (SearchHit hit : searchHits.getHits()) {
					Map<String, Object> map = hit.getSource();
					NewsResult n = new NewsResult();
					SimpleDateFormat myFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String url = hit.getSource().get("url") != null ? String.valueOf(hit.getSource().get("url"))
							: String.valueOf(hit.getId());
					if (!url.contains("http")) {
						url = String.valueOf(map.get("id"));
					}
					n.setUrl(url);
					n.setTitle(String.valueOf(map.get("title")));
					try {
						Calendar cal = getStringToCal(map.get("time").toString());
						n.setTime(myFmt.format(cal.getTime()));
					} catch (Exception e) {
						n.setTime("");
					}
					n.setSource(String.valueOf(map.get("source")));
					result.add(n);
				}
			}
			log.info("金融结束");
		} catch (Exception e) {
			log.error("es检索出错，错误信息【{}】", e);
		}
		for (NewsResult news : result) {
			for (String source : sources) {
				if (news.getSource().contains(source)) {
					lists.add(news);
					break;
				}
			}
		}
		result = new ArrayList<>();
		String str = "";
		for (NewsResult news : lists) {
			if (str.contains(news.getTitle())) {

			} else {
				str += news.getTitle() + ",";
				result.add(news);
			}
		}
		return result;
	}
	
	
	/**
	 * 根据时间处理微博+网媒 index
	 * @param start
	 * @param type
	 * @return
	 */
	private static String getIndex(Date startDate,String type){
		String index = "network";
		if(!type.contains("weibo")){
			index = "mediaspider";
		}
		Date endData = TimeParse.stringFormartDate("2017-08-03 00:00:00");
		String year = TimeParse.dateFormartString(startDate, "yyyyMM");
		if(endData.before(startDate)){
			index = index+"_"+year;
		}
		return index;
	}
	
	/**
	 * 根据查询时间处理微信大库index
	 * @param start
	 * @return
	 */
	private static String getWechatIndex(Date startDate){
		String index = "wx_tanglihua";
		Date endData = TimeParse.stringFormartDate("2017-05-01 00:00:00");
		String year = TimeParse.dateFormartString(startDate, "yyyyMM");
		if(endData.before(startDate)){
			index = index+"_"+year;
		}
		return index;
	}
	
}
