package com.chinacreator.process.job;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.beans.factory.annotation.Autowired;
import com.chinacreator.common.exception.BusinessException;
import com.chinacreator.process.bean.TencentVacOrderBean;
import com.chinacreator.process.dao.DictionaryDao;
import com.chinacreator.process.dao.VacOrderDao;
import com.chinacreator.process.util.JsonUtil;
import com.chinacreator.video.queue.MessageService;
import com.chinacreator.video.queue.bean.MessagePipe;

@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class TencentActivityJob {

	private static Logger log = Logger.getLogger(TencentActivityJob.class);
	private static Logger logger = Logger.getLogger("tencentActivity");
	
	@Autowired
	private DictionaryDao dictionaryDao;
	
	@Autowired
	private MessageService messageService;
	
	@Autowired
	private VacOrderDao vacOrderDao;
	
	public void doProcess() throws Exception {
		if(dictionaryDao.getValue("recivemq").equals("0")){
			log.info("========》腾讯20元0元扣费job启动(接受)");
			long beginTime = System.currentTimeMillis();
			List<MessagePipe> list = messageService
					.reciveBatchMessage("vacorder", 500);
			log.info("腾讯20元0元扣费队列(接受)花费时间："+(System.currentTimeMillis()-beginTime));
			log.info("腾讯20元0元扣费队列(接受)大小："+ (list == null ? 0 : list.size()));
			for (MessagePipe messagePipe : list) {
				String resultcode="0";
				String errorinfo="";
				Map<String,String> logMap = new HashMap<String, String>();
				try{
				TencentVacOrderBean bean = transBean(messagePipe.getBody());
				logMap.put("parmar", JsonUtil.objectToJson(messagePipe.getBody()));
				TencentVacOrderBean localbean = vacOrderDao.query(bean.getCpid(),bean.getSpid(), bean.getUserid());
				if(localbean == null){
					log.info("腾讯20元0元扣费队列(接受)插入");
					vacOrderDao.insert(bean);
				}else if(bean.getStatus().equals("0")){
					log.info("腾讯20元0元扣费队列(接受)order");
					vacOrderDao.order(bean.getOrdertime(), localbean.getId());
				}else{
					log.info("腾讯20元0元扣费队列(接受)cancel");
					vacOrderDao.cancel(bean.getCanceltime(), localbean.getId());
				}
				}catch(Exception e){
					log.error("",e);
					e.printStackTrace();
					if(e instanceof BusinessException){
						resultcode = ((BusinessException) e).getCode();
						errorinfo = ((BusinessException) e).getMessage();
					}else{
						resultcode = "8000";
						errorinfo = "系统错误";
					}
				}finally {
					logMap.put("resultcode", resultcode);
					logMap.put("errorinfo",errorinfo);
					logger.info(JsonUtil.objectToJson(logMap));
				}
			}
		}else{
			log.info("========》腾讯20元接收0元扣费job停止");
		}
	}
	
	public TencentVacOrderBean transBean(Map<String, Object> body) {
		String jsonStr = JsonUtil.objectToJson(body);
		return (TencentVacOrderBean) JsonUtil.jsonToBean(jsonStr, TencentVacOrderBean.class);
	}
	
}

