package com.zhiwei.manage.handle;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.zhiwei.manage.bean.Channel;
import com.zhiwei.manage.bean.CrawTemplate;
import com.zhiwei.manage.bean.Data;
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.CrawTemplateServiceImpl;
import com.zhiwei.manage.service.DataServiceImpl;
import com.zhiwei.manage.service.MessageServiceImpl;
import com.zhiwei.manage.service.ServerServiceImpl;
import com.zhiwei.manage.util.TimeUtil;
import com.zhiwei.manage.util.Tools;

@Component
public class MainThread extends Thread {

	private static final Log log = LogFactory.getLog(MainThread.class);
	public static Map<String, Template> mainMap = new ConcurrentHashMap<String, Template>();
	public static Map<String, Template> allTmp = new ConcurrentHashMap<String, Template>();
	private static Lock mainLock = new ReentrantLock();

	public MainThread() {
		this.start();
	}

	/**
	 * 加入执行map
	 * 
	 * @param template
	 */
	public static boolean pushMap(String templateId) {
		Template template = allTmp.get(templateId);
		if (mainMap.get(templateId) != null) {
			return false;
		} else {
			mainMap.put(template.getTemplateId(), template);
			System.out.println("加入模板" + template);
			if (template.isNeedDelayed()) {
				NewsDelayed nd = new NewsDelayed();
				nd.setCollection(template.getCollection());
				nd.setNewsDelayed(template.getNewsDelayed());
				nd.setDelayedInterval(template.getDelayedInterval());
				nd.setdBName(template.getdBName());
				nd.setHost(template.getHost());
				nd.setPort(template.getPort());
				nd.setStartNow(false);
				nd.setPt(template.getPt());
				nd.setSavetime(template.getSavetime());
				nd.setTime(template.getTime());
				nd.setSpyderInfoId(template.getSpyderInfoId());
				nd.setTempName(template.getTempName());
				nd.setNextRun(new Date());
				nd.setTestCount(template.getTestCount());
				nd.setTemplateId(templateId);
				DelayedThread.runMap.put(template.getTemplateId(), nd);
			}
			if (template.isNeedPing()) {
				log.info("ping测试添加");
				PingUrl ping = new PingUrl();
				ping.setNextRun(new Date());
				ping.setPingInterval(template.getPingInterval());
				ping.setPingUrlOne(template.getPingUrlOne());
				ping.setPingUrlTwo(template.getPingUrlTwo());
				ping.setPt(template.getPt());
				ping.setTemplateId(templateId);
				ping.setTempName(template.getTempName());
				ping.setStartNow(false);
				PingThread.runMap.put(templateId, ping);
			}
			if (template.isNeedField()) {
				FieldIntegerity fb = new FieldIntegerity();
				fb.setTestCount(template.getTestCount());
				fb.setCollection(template.getCollection());
				fb.setTemplateId(templateId);
				fb.setdBName(template.getdBName());
				fb.setHost(template.getHost());
				fb.setPort(template.getPort());
				fb.setNextRun(new Date());
				fb.setStartNow(false);
				fb.setPt(template.getPt());
				fb.setSpyderInfoId(template.getSpyderInfoId());
				fb.setTempName(template.getTempName());
				fb.setField(template.getField());
				fb.setFieldIntegrityRate(template.getFieldIntegrityRate());
				fb.setFieldInterval(template.getFieldInterval());
				FieldThread.runMap.put(template.getTemplateId(), fb);
			}
			return true;
		}
	}

	/**
	 * 停止该执行
	 * 
	 * @param template
	 */
	public static boolean removeMap(String templateId) {
		try {
			// Template template = allTmp.get(templateId);
			if (DelayedThread.runMap.get(templateId) != null)
				DelayedThread.runMap.remove(templateId);
			if (PingThread.runMap.get(templateId) != null)
				PingThread.runMap.remove(templateId);
			if (FieldThread.runMap.get(templateId) != null)
				FieldThread.runMap.remove(templateId);
			if (mainMap.get(templateId) != null)
				mainMap.remove(templateId);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public static boolean delete(String templateId) {
		allTmp.remove(templateId);
		return true;
	}

	@Override
	public void run() {
		log.info("=======日常入库启动======");
		CrawTemplateServiceImpl crawService = BeanFactory.getBean(CrawTemplateServiceImpl.class);
		DataServiceImpl dataService = BeanFactory.getBean(DataServiceImpl.class);
		ServerServiceImpl serverService = BeanFactory.getBean(ServerServiceImpl.class);
		MessageServiceImpl msgService = BeanFactory.getBean(MessageServiceImpl.class);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		// int num = 1;
		while (true) {
			Calendar countTest = Calendar.getInstance();
			Calendar start = Calendar.getInstance();
			Calendar end = Calendar.getInstance();
			// start.set(Calendar.HOUR_OF_DAY, 0);
			// end.set(Calendar.HOUR_OF_DAY, 0);
			if (start.get(Calendar.HOUR_OF_DAY) < 1) {
				try {
					countTest.setTime(sdf.parse(sdf.format(countTest.getTime())));
					start.setTime(sdf.parse(sdf.format(countTest.getTime())));
					end.setTime(sdf.parse(sdf.format(countTest.getTime())));
				} catch (ParseException e1) {
					e1.printStackTrace();
				}
				// int num = 1;
				// for (int i = 0; i < 19; i++) {
				start.add(Calendar.DATE, -1);
				countTest.add(Calendar.DATE, -3);
				try {
					mainLock.lock();
					int count = 0;
					List<Channel> channel = serverService.findDisChannel();
					for (Channel chan : channel) {
						if (chan.getPt().equals("网媒")) {
							List<CrawTemplate> list = crawService.findAll();
							// 每日的数据量入库（对应模板）
							System.out.println(list.size());
							for (CrawTemplate cr : list) {
								count = (int) dataService.finCountByDayData(start.getTime(), end.getTime(),
										chan.getPt(), cr.getId());
								Data data = new Data();
								data.setCount(count);
								data.setTempName(cr.getConfigName());
								data.setTime(start.getTime());
								data.setSpyderInfoId(cr.getId());
								dataService.insert(data);
								if (count == 0) {
									// if (num == 1) {
									int testCount = (int) dataService.finCountByDayData(countTest.getTime(),
											end.getTime(), chan.getPt(), cr.getId());
									if (testCount == 0) {
										Message m = new Message();
										m.setHandle(false);
										m.setCreateDate(start.getTime());
										m.setTemplateLv(1);
										m.setTempName("未定义");
										m.setPt("网媒");
										m.setErrorMsg("未定义，" + cr.getConfigName() + "," + chan.getId() + "数据为0");
										msgService.insert(m);
									}
									// }
								}
								log.info(TimeUtil.yearToDay(start.getTime()) + "|" + data.getTempName() + "|入库");
							}
							count = (int) dataService.finCountByDayData(start.getTime(), end.getTime(), chan.getPt(),
									null);
							Data data = new Data();
							data.setCount(count);
							data.setPt(chan.getPt());
							data.setTime(start.getTime());
							dataService.insert(data);
						} else {
							count = (int) dataService.finCountByDayData(start.getTime(), end.getTime(), chan.getPt(),
									null);
							Data data = new Data();
							data.setCount(count);
							data.setPt(chan.getPt());
							data.setTime(start.getTime());
							dataService.insert(data);
							log.info(TimeUtil.yearToDay(start.getTime()) + "|" + chan.getPt() + "|入库");
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					mainLock.unlock();
				}
				// end.add(Calendar.DATE, -1);
				// num++;
				// }
				Tools.sleep(1000 * 60 * 60);
			}
			Tools.sleep(1000 * 30);
		}
	}

}
