package com.chinacreator.process.job;

import java.net.URLEncoder;
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.util.AESUtil;
import com.chinacreator.common.util.MD5;
import com.chinacreator.process.bean.NetOrderBean;
import com.chinacreator.process.bean.PreToOrderBean;
import com.chinacreator.process.dao.PreToOrderDao;
import com.chinacreator.process.util.DesUtil;
import com.chinacreator.process.util.JsonUtil;
import com.chinacreator.process.util.URLUtil;

@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class PreToOrderJob {

	private static Logger log = Logger.getLogger(PreToOrderJob.class);
	
	private static Logger logger = Logger.getLogger("pretoorderjob");
	
	@Autowired
	private PreToOrderDao preToOrderDao;
	
	private final static String url = "http://172.16.1.81:809/video-activity/order?";
	
	public void doProcess() throws Exception {
		log.info("========》腾讯20元预定购转订购开始");
		long num =preToOrderDao.getSize()/500+1;
		for (int m = 0; m < num; m++) {
			List<NetOrderBean>  list = preToOrderDao.queryNeedDo();
			for (NetOrderBean netOrderBean : list) {
				PreToOrderBean logBean = new PreToOrderBean();
				String result = "1";
				try{
				String userid = netOrderBean.getUserid();
				logBean.setUserid(userid);
				logBean.setId(netOrderBean.getId());
				if(!netOrderBean.getStatus().equals("0")){
					preToOrderDao.update(netOrderBean.getId(), "3");
					result ="3";
					logBean.setRsp("3");
					continue;
				}
				String cpid =netOrderBean.getCpid();
				String spid=netOrderBean.getSpid();
				String pwd = "tenc1234";
				String timestamp = (System.currentTimeMillis()/1000)+"";
				userid = DesUtil.encode(AESUtil.encrypt(userid, "ac22273abb2f4960"), pwd);
				String signature = MD5.MD5Encode(cpid+spid+userid+pwd+timestamp);
				String href = url+"cpid="+cpid+"&spid="+spid+"&userid="+URLEncoder.encode(userid, "utf-8")+"&signature="+signature+"&timestamp="+timestamp+"&ordertype=1&channel=pre";
				String resultstr= URLUtil.get(href,15000);
				logBean.setRsp(resultstr);
				Map<?,?> map = JsonUtil.jsonToMap(resultstr);
				if(((String)map.get("resultcode")).equals("0")){
					result ="0";
				} 
				}catch(Exception e){
					log.error(netOrderBean.getUserid(),e);
				}finally {
					if(result.equals("0")){
						preToOrderDao.update(netOrderBean.getId(), "0");
					}else if(result.equals("1")){
						preToOrderDao.update(netOrderBean.getId(), "2");
					}
					logger.info(JsonUtil.objectToJson(logBean));
				}
			}
		}
	}
	
	public static void main(String[] args) {
		System.out.println(4031/500);
	}
}
