package com.iamberry.wechat.face.reback;

import com.iamberry.wechat.core.entity.order.Order;
import com.iamberry.wechat.core.entity.reback.RebackInfo;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentLinkedQueue;


@Lazy(false)
@Service("loadRewardTaskService")
public class LoadRewardTaskService {

	@Autowired
	private RebackServices RebackServices;
	
	Logger logger = Logger.getLogger("infoLog");  
	
	private static  ConcurrentLinkedQueue<Order> linkq=new ConcurrentLinkedQueue<Order>();
	private static  ConcurrentLinkedQueue<RebackInfo> Updateq=new ConcurrentLinkedQueue<RebackInfo>();
	
	//增加处理的订单
	public static void addOrder(Order order){
		linkq.add(order);
	}
	
	//增加处理的订单的id
	public static void addOrder(String orderId){
		Order order=new Order();
		order.setSalesOrderid(orderId);
		linkq.add(order);	
	}
	
	//修改返现的状态
	public static void updateStatus(RebackInfo rebackInfo){
		Updateq.add(rebackInfo);
	}
	

	//插入返现记录
	@Async
	public  void getinsertRewardRecord(){
		while(true){
			Order order=linkq.poll();
			if(order==null){
				try {
					Thread.sleep(5000);
					//System.out.println("sleep 5s");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				continue;
			}
			int i=0;
			try{
				i=RebackServices.loadSingleOrderReward(order);
			}catch(Exception ex){
				i=-2;
			}
			String str="订单："+order.getSalesOrderid();
			logger.debug(i>0?str+"插入返现记录成功":str+"插入返现记录失败");
		}
	}
	
	//插入返现记录
	@Async
	public  void getupdateStateRewardRecord(){
		while(true){
			RebackInfo rebackInfo=Updateq.poll();
			if(rebackInfo==null){
				try {
					Thread.sleep(15000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				continue;
			}
			int i=0;
			try{
				i=RebackServices.updateStatus(rebackInfo);
			}catch(Exception ex){
				i=-2;
			}
			String str="订单状态更新："+rebackInfo.getOrderId();
			logger.debug(i>0?str+"插入返现记录成功":str+"插入返现记录失败");
		}
	}
	
	
	
}
