package com.buy507.mall.component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.buy507.mall.mapper.OmsOrderMapper;
import com.buy507.mall.model.OmsOrder;
import com.buy507.mall.service.DistributionService;

/**
 * 分销冻结账户队列处理类
 * @author wuming
 *
 */
@Component
public class DistributeHandlerQueue implements CommandLineRunner {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(DistributeHandlerQueue.class);
	
	private static LinkedBlockingQueue<Long> queue = new LinkedBlockingQueue<>();
	
	@Autowired
	private DistributionService distributionService;
	
	@Autowired
    private ExecutorService executorService;
	
	@Autowired
	private OmsOrderMapper orderMapper;

	@Override
	public void run(String... args) throws Exception {
		
		executorService.execute(new Runnable() {
			@Override
			public void run() {
				while(true) {
					Long orderId = null;
					try {
						LOGGER.info("distribution handler queue size: {}", queue.size());
						orderId = queue.take();
						LOGGER.info("distribution handler start: {}", orderId);
						
						OmsOrder order = orderMapper.selectByPrimaryKey(orderId);
						
						//1. 分享劳务费和服务劳务费计算
						distributionService.computeRefereeCharge(order.getMemberId(), order);
						
						//2. 店补计算
						distributionService.computeStoreSubsidy(order.getMemberId(), order);
						
						//3. 上级团队的累计消费信息
						distributionService.computeTeamTotalConsume(order.getMemberId(), order);
						
						//4. 团队服务劳务费计算
						distributionService.computeTeamIncome(order.getMemberId(), order);
						
						//5. 会员等级计算，根据参数和消费情况计算会员等级
						distributionService.computMemberLevel(order.getMemberId(), order);
						
						LOGGER.info("distribution handler end: {}", orderId);
						LOGGER.info("distribution handler queue size: {}", queue.size());
					} catch (InterruptedException e) {
						LOGGER.error("distribution handler failed");
						e.printStackTrace();
					} catch (Exception e) {
						if(orderId != null) {
							LOGGER.error("distribution handler failed: {}", orderId);
						} else {
							LOGGER.error("distribution handler failed");
						}
						e.printStackTrace();
					}
					
				}
			}
		});
		
	}
	
	/**
	 * 添加订单到分销处理队列中
	 * @param order
	 */
	public static void addOrderToQueue(Long orderId) {
		try {
			queue.put(orderId);
		} catch (InterruptedException e) {
			LOGGER.error("distribution add order to queue failed: {}", orderId);
			e.printStackTrace();
		}
	}

}
