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);
					int code = conn.getResponseCode();
					if (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");
						messageService.insert(msg);
					}
				} 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.insert(msg);
				}
				if (null != ping.getPingUrlTwo() && !ping.getPingUrlTwo().equals(""))
					try {
						url = new URL(ping.getPingUrlTwo());
						HttpURLConnection conn = (HttpURLConnection) url.openConnection();
						conn.setConnectTimeout(1000 * 10);
						int code = conn.getResponseCode();
						if (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.insert(msg);
						}
					} 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.insert(msg);
					}
			}
		}
		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() < field.getTestCount()) {
					Template tp = MainThread.mainMap.get(field.getTemplateId());
					Message msg = new Message();
					msg.setCreateDate(new Date());
					msg.setErrorMsg("字段检测发现库内的数据小于预设检测数量：" + field.getTestCount() + "条,实际数据量为" + list.size());
					msg.setHandle(false);
					msg.setPt(field.getPt());
					msg.setTemplateCreator(tp.getCreator());
					msg.setTemplateLv(tp.getTemplateLv());
					msg.setErrorType("field");
					msg.setTempName(field.getTempName());
					messageService.insert(msg);
				}
				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.insert(msg);
					}
				}
			}
		}
		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() < delayed.getTestCount()) {
					Template tp = MainThread.mainMap.get(delayed.getTemplateId());
					Message msg = new Message();
					msg.setCreateDate(new Date());
					msg.setErrorMsg("延时检测发现库内的数据小于预设检测数量：" + delayed.getTestCount() + "条,实际数据量为" + list.size());
					msg.setHandle(false);
					msg.setPt(delayed.getPt());
					msg.setErrorType("delayed");
					msg.setTemplateCreator(tp.getCreator());
					msg.setTemplateLv(tp.getTemplateLv());
					msg.setTempName(delayed.getTempName());
					messageService.insert(msg);
				}
				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;
					} 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.insert(msg);
					}
				}
				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.insert(msg);
				}
			}
		}
	}
}
