package com.zhiwei.manage.handle;

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

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;

public class Task implements Runnable {

	private NewsDelayed delayed;
	private PingUrl ping;
	private FieldIntegerity field;

	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) {
							List<String> list = new ArrayList<>();
							list.add(msg.getMessageId());
							messageService.delete(list, ping.getPt());
						}
					}
				} 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) {
								List<String> list = new ArrayList<>();
								list.add(msg.getMessageId());
								messageService.delete(list, ping.getPt());
							}
						}
					} 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 (field != null) {
			if (MainThread.mainMap.get(field.getTemplateId()) != null) {
				List<Map<String, Object>> list = newsService.findNews(field.getHost(), field.getPort(),
						field.getdBName(), field.getCollection(), field.getTestCount(), field.getSpyderInfoId(),
						field.getPt());
				if (list.size() ==0) {
					Template tp = MainThread.mainMap.get(field.getTemplateId());
					Message msg = new Message();
					msg.setCreateDate(new Date());
					msg.setErrorMsg("字段检测发现库内的数据为0");
					msg.setHandle(false);
					msg.setPt(field.getPt());
					msg.setTemplateCreator(tp.getCreator());
					msg.setTemplateLv(tp.getTemplateLv());
					msg.setErrorType("count2");
					msg.setTempName(field.getTempName());
					messageService.update(msg,field.getPt());
				} else {
					Message msg = messageService.findMsg(field.getTempName(), "count2");
					if (msg != null) {
						List<String> ids = new ArrayList<>();
						ids.add(msg.getMessageId());
						messageService.delete(ids, field.getPt());
					}
				}
				String[] fields = field.getField().split(",");
				int count = list.size();
				for (String fid : fields) {
					String str = "";
					int num = count;
					for (Map<String, Object> map : list) {
						if (map.get(fid) == null) {
							num--;
							str = String.valueOf(map.get("_id"));
						} else if (String.valueOf(map.get(fid)).length() < 1) {
							num--;
							str = String.valueOf(map.get("_id"));
						}
					}
					if (num / 1.0 / count < field.getFieldIntegrityRate() / 100.0) {
						Template tp = MainThread.mainMap.get(field.getTemplateId());
						Message msg = new Message();
						msg.setCreateDate(new Date());
						msg.setErrorMsg(fid + "字段存在缺失,完整率" + num / 1.0 / count + "其中一条：" + str);
						msg.setHandle(false);
						msg.setPt(field.getPt());
						msg.setErrorType("field");
						msg.setTemplateCreator(tp.getCreator());
						msg.setTemplateLv(tp.getTemplateLv());
						msg.setTempName(field.getTempName());
						messageService.update(msg,field.getPt());
					} else {
						Message msg = messageService.findMsg(field.getTempName(), "field");
						if (msg != null) {
							List<String> ids = new ArrayList<>();
							ids.add(msg.getMessageId());
							messageService.delete(ids, field.getPt());
						}
					}
				}
			}
		}
		if (delayed != null) {
			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());
				long sum = 0;
				if (list.size() ==0) {
				} else {
					Message msg = messageService.findMsg(delayed.getTempName(), "count2");
					if (msg != null) {
						List<String> ids = new ArrayList<>();
						ids.add(msg.getMessageId());
						messageService.delete(ids, delayed.getPt());
					}
				}
				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) {
						time = (Date) map.get(delayed.getTime());
					}
					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;
						Message msg = messageService.findMsg(delayed.getTempName(), "delayed");
						if (msg != null) {
							List<String> ids = new ArrayList<>();
							ids.add(msg.getMessageId());
							messageService.delete(ids, delayed.getPt());
						}
					} else {
						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("delayed");
						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);
				}
				System.out.println(sum);
				if (sum / 1.0 / 1000 / 60 / cutSize > delayed.getNewsDelayed()) {
					Template tp = MainThread.mainMap.get(delayed.getTemplateId());
					Message 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 {
					Message msg = messageService.findMsg(delayed.getTempName(), "delayed");
					if (msg != null) {
						List<String> ids = new ArrayList<>();
						ids.add(msg.getMessageId());
						messageService.delete(ids, delayed.getPt());
					}
				}
			}
		}
	}
}
