package com.chinacreator.process.service;

import java.util.List;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.chinacreator.common.exception.BusinessException;
import com.chinacreator.process.bean.OrderBean;
import com.chinacreator.process.dao.NewYearActiveDao;

@Component
public class BestvOrderService {

	private static Logger log = Logger.getLogger(BestvOrderService.class);

	@Autowired
	private NewYearActiveDao newYearctiveDao;

	public void order(OrderBean orderBean) throws Exception {
		List<OrderBean> oldOrderBeans = newYearctiveDao.existUserBestv(orderBean.getUserid(), orderBean.getCpid(),
				orderBean.getSpid());
		log.info("oldOrderBeans数目：" + oldOrderBeans.size());
		orderBean.setIscharge("2");
		if (oldOrderBeans == null || oldOrderBeans.size() == 0) {
			orderBean.setFlowstatus("8");
			orderBean.setVipstatus("2");
			newYearctiveDao.insertBeansBestv(orderBean);
		} else if (oldOrderBeans.size() == 1 && oldOrderBeans.get(0).getActiveType() == orderBean.getActiveType()) {
			OrderBean oldOrderBean = oldOrderBeans.get(0);
			if (oldOrderBean.getOrderType().equals("0")) {//已订购
				throw new BusinessException("9040", "队列入库失败，重复订购");
			} else {//退订或者老用户
					orderBean.setId(oldOrderBean.getId());
					if(NumberUtils.toLong(oldOrderBean.getEndtime()) >= NumberUtils.toLong(orderBean.getUpdateTime())){
						orderBean.setVipstatus(oldOrderBean.getVipstatus());
						newYearctiveDao.UpdateRelationsBestv(orderBean);
					}else{
						orderBean.setVipstatus("2");
						newYearctiveDao.UpdateRelationsBestv(orderBean);
					}
			}
		}
	}

	public void cancel(OrderBean orderBean) throws Exception {
		List<OrderBean> oldOrderBeans = newYearctiveDao.existUserBestv(orderBean.getUserid(), orderBean.getCpid(),
				orderBean.getSpid());
		if (oldOrderBeans == null || oldOrderBeans.size() == 0) {
			throw new BusinessException("9041", "退订失败，活动无该用户");
		} else {
			if (oldOrderBeans.size() == 1) {
				OrderBean oldOrderBean = oldOrderBeans.get(0);
				if (oldOrderBean.getOrderType().equals("0")) {
					orderBean.setId(oldOrderBean.getId());
					newYearctiveDao.cancelOrderBestv(orderBean);
				} else {
						throw new BusinessException("9042", "队列入库失败，重复退订");
				}
			}  
		}
	}
}
