package com.zhiwei.manage.handle;

import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.zhiwei.manage.bean.FieldIntegerity;
import com.zhiwei.manage.bean.Message;
import com.zhiwei.manage.bean.NewsDelayed;
import com.zhiwei.manage.bean.PingUrl;
import com.zhiwei.manage.bean.Template;
import com.zhiwei.manage.orm.BeanFactory;
import com.zhiwei.manage.service.MessageService;
import com.zhiwei.manage.service.NewsService;

/**
 * 任务执行线程
 * 
 * @author admin
 *
 */
public class Task implements Runnable {

	private NewsDelayed delayed;
	private PingUrl ping;
	private FieldIntegerity field;
	final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
	private final static Log log = LogFactory.getLog(Task.class);

	public Task(Object runMsg) {
		if (runMsg instanceof NewsDelayed) {
			this.delayed = (NewsDelayed) runMsg;
		} else if (runMsg instanceof PingUrl) {
			this.ping = (PingUrl) runMsg;
		} else if (runMsg instanceof FieldIntegerity) {
			this.field = (FieldIntegerity) runMsg;
		}
	}

	@Override
	public void run() {
		MessageService messageService = BeanFactory.getBean(MessageService.class);
		NewsService newsService = BeanFactory.getBean(NewsService.class);
		// 连通性测试
		if (ping != null) {
			if (MainThread.mainMap.get(ping.getTemplateId()) != null) {
				URL url;
				try {
					url = new URL(ping.getPingUrlOne());
					HttpURLConnection conn = (HttpURLConnection) url.openConnection();
					conn.setConnectTimeout(1000 * 10);
					conn.setRequestProperty("User-Agent",
							"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36");
					int code = conn.getResponseCode();
					if (code > 399 || code < 200) {
						Template tp = MainThread.mainMap.get(ping.getTemplateId());
						Message msg = new Message();
						msg.setCreateDate(new Date());
						msg.setErrorMsg(code == 0 ? "访问超时" : ping.getPingUrlOne() + "访问失败,错误代码" + code);
						msg.setHandle(false);
						msg.setTemplateCreator(tp.getCreator());
						msg.setTempName(ping.getTempName());
						msg.setTemplateLv(tp.getTemplateLv());
						msg.setErrorType("url");
						msg.setPt(ping.getPt());
						messageService.update(msg, ping.getPt());
					} else {
						Message msg = messageService.findMsg(ping.getTempName(), "url");
						if (msg != null) {
							messageService.delete(msg.getMessageId());
						}
					}
				} catch (Exception e) {
					Template tp = MainThread.mainMap.get(ping.getTemplateId());
					Message msg = new Message();
					msg.setCreateDate(new Date());
					msg.setErrorMsg("访问出错,url不可访问");
					msg.setHandle(false);
					msg.setTemplateCreator(tp.getCreator());
					msg.setTempName(ping.getTempName());
					msg.setTemplateLv(1);
					msg.setErrorType("url");
					msg.setPt(ping.getPt());
					messageService.update(msg, ping.getPt());
				}
				if (null != ping.getPingUrlTwo() && !ping.getPingUrlTwo().equals(""))
					try {
						url = new URL(ping.getPingUrlTwo());
						HttpURLConnection conn = (HttpURLConnection) url.openConnection();
						conn.setRequestProperty("User-Agent",
								"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36");
						conn.setConnectTimeout(1000 * 10);
						int code = conn.getResponseCode();
						if (code > 399 || code < 200) {
							Template tp = MainThread.mainMap.get(ping.getTemplateId());
							Message msg = new Message();
							msg.setCreateDate(new Date());
							msg.setErrorMsg(code == 0 ? ping.getPingUrlOne() + "访问失败,错误代码" + code : "访问超时");
							msg.setHandle(false);
							msg.setTemplateCreator(tp.getCreator());
							msg.setTempName(ping.getTempName());
							msg.setTemplateLv(tp.getTemplateLv());
							msg.setErrorType("url");
							msg.setPt(ping.getPt());
							messageService.update(msg, ping.getPt());
						} else {
							Message msg = messageService.findMsg(ping.getTempName(), "url");
							if (msg != null) {
								messageService.delete(msg.getMessageId());
							}
						}
					} catch (Exception e) {
						Template tp = MainThread.mainMap.get(ping.getTemplateId());
						Message msg = new Message();
						msg.setCreateDate(new Date());
						msg.setErrorMsg("访问出错,url不可访问");
						msg.setHandle(false);
						msg.setTemplateCreator(tp.getCreator());
						msg.setTempName(ping.getTempName());
						msg.setPt(ping.getPt());
						msg.setErrorType("url");
						msg.setTemplateLv(tp.getTemplateLv());
						messageService.update(msg, ping.getPt());
					}
			}
		}
		if (delayed != null) {
			log.info(delayed.getTempName() + "开始检测");
			if (MainThread.mainMap.get(delayed.getTemplateId()) != null) {
				List<Map<String, Object>> list = newsService.findNews(delayed.getHost(), delayed.getPort(),
						delayed.getdBName(), delayed.getCollection(), delayed.getTestCount(), delayed.getSpyderInfoId(),
						delayed.getPt());
				log.info("size" + list.size());
				long sum = 0;
				if (list.size() == 0) {
					Template tp = MainThread.mainMap.get(delayed.getTemplateId());
					Message msg = new Message();
					msg.setCreateDate(new Date());
					msg.setErrorMsg("查不到该数据");
					msg.setHandle(false);
					msg.setPt(delayed.getPt());
					msg.setErrorType("count2");
					msg.setTemplateCreator(tp.getCreator());
					msg.setTemplateLv(1);
					msg.setTempName(delayed.getTempName());
					messageService.update(msg, delayed.getPt());
				} else {
					Message msg = null;
					msg = messageService.findMsg(delayed.getTempName(), "count2");
					if (msg != null) {
						messageService.delete(msg.getMessageId());
					}
					double delay = 0;
					List<Double> dNum = new ArrayList<Double>();
					for (Map<String, Object> map : list) {
						Date time = null;
						Date savetime = null;
						if (map.get(delayed.getTime()) != null) {
							String date = null;
							try {
								date = String.valueOf(map.get(delayed.getTime())).replace("Z", " UTC");
								time = sdf.parse(String.valueOf(date));
							} catch (ParseException e) {
								log.info("时间:" + date);
								log.error("时间转换出错【{}】", e);
							}
						}
						if (map.get(delayed.getSavetime()) != null) {
							Date d = new Date((Long) map.get(delayed.getSavetime()));
							savetime = d;
						}
						if (time != null && savetime != null) {
							delay = savetime.getTime() - time.getTime();
							dNum.add(delay);
							sum += delay;
						} else {
							Template tp = MainThread.mainMap.get(delayed.getTemplateId());
							msg = new Message();
							msg.setCreateDate(new Date());
							msg.setErrorMsg("延时检测发现时间字段缺失");
							msg.setHandle(false);
							msg.setPt(delayed.getPt());
							msg.setErrorType("timeIsNull");
							msg.setTemplateCreator(tp.getCreator());
							msg.setTemplateLv(tp.getTemplateLv());
							msg.setTempName(delayed.getTempName());
							messageService.update(msg, delayed.getPt());
						}
					}
					Collections.sort(dNum);
					int cutSize = (int) (dNum.size() * 0.8 / 1);
					for (int i = cutSize; i < dNum.size(); i++) {
						sum -= dNum.get(i);
					}
					if (sum / 1.0 / 1000 / 60 / cutSize > delayed.getNewsDelayed()) {
						Template tp = MainThread.mainMap.get(delayed.getTemplateId());
						msg = new Message();
						msg.setCreateDate(new Date());
						msg.setErrorMsg("延时过高，延时检测为" + sum / 1.0 / 1000 / 60 / cutSize + "分");
						msg.setHandle(false);
						msg.setErrorType("delayed");
						msg.setTemplateCreator(tp.getCreator());
						msg.setTemplateLv(tp.getTemplateLv());
						msg.setPt(delayed.getPt());
						msg.setTempName(delayed.getTempName());
						messageService.update(msg, delayed.getPt());
					} else {
						msg = messageService.findMsg(delayed.getTempName(), "delayed");
						if (msg != null) {
							List<String> ids = new ArrayList<>();
							ids.add(msg.getMessageId());
							messageService.delete(ids);
						}
					}
				}
			}
		}
	}
}
