package com.chinacreator.process.job;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.beans.factory.annotation.Autowired;

import com.chinacreator.common.support.util.SpringContextUtil;
import com.chinacreator.process.bean.UserFakeidBean;
import com.chinacreator.process.dao.UserFakeidDao;
import com.chinacreator.process.service.UserFakeidQueryService;

@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class UserFakeidQueryJob {

	private static Logger log = Logger.getLogger(UserFakeidQueryJob.class);
	
	@Autowired
	private UserFakeidDao userFakeidDao;
	
	
	public void doProcess() throws Exception {
		log.info("电商伪码查询开始【======");
		List<UserFakeidBean> list =  null;
		long stime = System.currentTimeMillis();
		
		try {
			list = userFakeidDao.queryNeedQuery();
			log.info("需要查询电商伪码===="+(list == null ? 0 : list.size()));
			if(list != null && list.size() > 0){
				CountDownLatch threadSignal = new CountDownLatch(list.size());
				ExecutorService executorService = new ThreadPoolExecutor(8, 15, 10L, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.CallerRunsPolicy());
				for (UserFakeidBean bean : list) {
					FakeidQueryService fakeidService = new FakeidQueryService(list.size(),threadSignal,bean);
					executorService.execute(fakeidService);
				}
				executorService.shutdown();
				try {
					executorService.awaitTermination(1L, TimeUnit.MINUTES);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.info("电商伪码查询结束===="+((System.currentTimeMillis())-stime));
	}
	
	
}

class FakeidQueryService implements Runnable {
	
	private static Logger logger = Logger.getLogger(ChannelService.class);
	private int totalSize;
	private CountDownLatch threadSignal;
	private UserFakeidBean bo;
	
	
	public FakeidQueryService(int totalSize,CountDownLatch threadSignal,UserFakeidBean bo){
		this.totalSize = totalSize;
		this.threadSignal = threadSignal;
		this.bo = bo;
	}
	
	public void run() {
		long startime = System.currentTimeMillis();
		UserFakeidQueryService service = SpringContextUtil.getBean(UserFakeidQueryService.class);
		String result = service.queryFakeid(bo);
		
		threadSignal.countDown();
		logger.info("["+bo.getUserid()+","+bo.getOrderid()+"]:结果="+result+"["+ totalSize+"/"+(totalSize - threadSignal.getCount())+"],花费时间："+(System.currentTimeMillis()-startime+"/ms"));
	}
}
	

