package com.zhiwei.manage.handle;

import java.net.HttpURLConnection;
import java.net.URL;
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() {
		System.out.println("开始做检测");
		MessageService messageService = BeanFactory.getBean(MessageService.class);
		NewsService newsService = BeanFactory.getBean(NewsService.class);

		// 连通性测试
		if (ping != 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());
					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(tp.getTemplateLv());
				msg.setPt(ping.getPt());
				messageService.insert(msg);
			}
			System.out.println(ping);
			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.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.setTemplateLv(tp.getTemplateLv());
					messageService.insert(msg);
				}
		}
		if (field != null) {
			List<Map<String, Object>> list = newsService.findNews(field.getHost(), field.getPort(), field.getdBName(), field.getCollection(),
						field.getTestCount(), field.getSpyderInfoId(), field.getPt());
			System.out.println("field检测数据长度"+list.size());
			if(list.size()<field.getTestCount()){
				Template tp = MainThread.mainMap.get(field.getTemplateId());
				Message msg = new Message();
				msg.setCreateDate(new Date());
				msg.setErrorMsg("字段检测发现库内的数据小于预设检测数量："+delayed.getTestCount()+"条,实际数据量为"+list.size());
				msg.setHandle(false);
				msg.setPt(field.getPt());
				msg.setTemplateCreator(tp.getCreator());
				msg.setTemplateLv(tp.getTemplateLv());
				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.setTemplateCreator(tp.getCreator());
					msg.setTemplateLv(tp.getTemplateLv());
					msg.setTempName(field.getTempName());
					messageService.insert(msg);
				}
			}
		}
		if (delayed != null) {
			List<Map<String, Object>> list = newsService.findNews(delayed.getHost(), delayed.getPort(), delayed.getdBName(),
						delayed.getCollection(), delayed.getTestCount(), delayed.getSpyderInfoId(), delayed.getPt());
			System.out.println("delay检测数据长度"+list.size());
			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.setTemplateCreator(tp.getCreator());
				msg.setTemplateLv(tp.getTemplateLv());
				msg.setTempName(delayed.getTempName());
				messageService.insert(msg);
			}
			long top=0,top_2=0;
			long delay=0;
			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();
					if(delay>top){
						top=delay;
					}else if(delay>top_2){
						top_2=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.setTemplateCreator(tp.getCreator());
					msg.setTemplateLv(tp.getTemplateLv());
					msg.setTempName(delayed.getTempName());
					messageService.insert(msg);
				}
			}
			System.out.println("sum"+sum);
			if ((sum-top-top_2) / 1.0 / 1000 / 60/(delayed.getTestCount()-2) > delayed.getNewsDelayed()) {
				Template tp = MainThread.mainMap.get(delayed.getTemplateId());
				Message msg = new Message();
				msg.setCreateDate(new Date());
				msg.setErrorMsg("延时过高，延时检测为" + (sum-top-top_2) / 1.0 / 1000 / 60/(delayed.getTestCount()-2) + "分");
				msg.setHandle(false);
				msg.setTemplateCreator(tp.getCreator());
				msg.setTemplateLv(tp.getTemplateLv());
				msg.setPt(delayed.getPt());
				msg.setTempName(delayed.getTempName());
				messageService.insert(msg);
			}
		}
	}
}

