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 javax.print.Doc;

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.util.Config;
import com.zhiwei.util.MongoConnection;
import com.zhiwei.util.ReadExcel;
import com.zw.entity.NewsResult;

import weixin.popular.bean.menu.selfmenu.News;

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

	/**
	 * 获取匹配时终止时间
	 * 
	 * @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) {
		// Calendar cal = Calendar.getInstance();
		// cal.add(Calendar.HOUR_OF_DAY, -20);
		// Calendar cal2 = Calendar.getInstance();
		// cal2.add(Calendar.HOUR_OF_DAY, -4);
		// List<NewsResult> list = new ESUtil().pushByKey(cal.getTime(),
		// cal2.getTime());
		// System.out.println(list.size());
		// String str = "";
		// String url = "C:\\Users\\admin\\Desktop/shenjz.xls";
		// cal.add(Calendar.HOUR_OF_DAY, 9);
		// try {
		// new ExcelUtil().pushDataWithFinance(list, cal.getTime(), url);
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		List<String> sources = new ArrayList<String>();
		String path = PushFinanceByTime.class.getClassLoader().getResource("pushFiles/weibo.xls").getPath();
//		Document doc = con.find("financePush", "excelPath", new Document().append("name", "longSource"));
//		if (doc != null) {
//			if (doc.getString("url") != null) {
//				path = doc.getString("url");
//			}
//		}
		sources = new ReadExcel().getExcel(path);
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.HOUR_OF_DAY, -3);
		List<NewsResult> list = new ESUtil().pushByKey(cal.getTime(), new Date(), sources, "weibo");
		System.out.println(list.size());
	}

	/**
	 * 推送
	 * 
	 * @param start
	 * @param end
	 * @return
	 */
	public 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 {
			Client esClient = ESClient.getInstance();
			for (String key : keys) {
				// 搜索数据
				SearchRequestBuilder srb = esClient.prepareSearch(Config.getVal("indexName." + type));
				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("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"));
					}
					if (type.equals("weibo")) {
						n.setUrl(url);
						if (map.get("roottext") == null) {
							n.setTitle(String.valueOf(map.get("text")));
						} else {
							n.setTitle(String.valueOf(map.get("roottext")));
						}
						try {
							n.setTime(map.get("time")+"");
						} catch (Exception e) {
							n.setTime("");
						}
						n.setSource(String.valueOf(map.get("username")));
						result.add(n);
					} else {
						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;
	}
}
