package com.iamberry.rent.handlers.listener;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.rent.face.order.RentOrderService;
import com.iamberry.wechat.core.entity.admin.ShopSystemRule;
import com.iamberry.wechat.core.entity.rent.RentOrder;
import com.iamberry.wechat.face.admin.SystemService;

public class RentOrderListener {
	
	@Autowired
	private RatFWLogger logger;
	@Autowired
	private RentOrderService rentOrderService;
	@Autowired
    private SystemService systemService;
	
	public void closeRentOrder() throws Exception {
		//获取规则表中对于订单关闭限定的时间
		logger.info("==============订单关闭开始==================");
		ShopSystemRule shopSystemRuleOne = systemService.selectOneShopRuleById(234);
		List<Integer> couponList = new ArrayList<Integer>();//用于存放服务费抵扣券id
		List<String> rentOrderList = new ArrayList<String>();//用于存放订单orderid
		RentOrder rentOrder = new RentOrder();
		rentOrder.setRentStatus(1);
		//获取的时间以分钟为单位，这里转换成秒，按秒计算
		rentOrder.setDeadline((int)(shopSystemRuleOne.getRuleNum() * 60));
		//根据状态和时间查询是否有需要关闭的订单
		List<RentOrder> orderList = rentOrderService.listOrderByDeadline(rentOrder);
		if (orderList == null || orderList.size() <= 0) {
			logger.info("==============订单关闭结束，没有可关闭订单==================");
			return;
		}
		//循环订单，将订单id和抵扣券id添加到集合中
		for (RentOrder order : orderList) {
			rentOrderList.add(order.getRentOrderId());
			if (order.getRentServiceId() != null) {
				couponList.add(order.getRentServiceId());
			}
		}
		
		boolean flag = rentOrderService.updateOrderAndCoupon(rentOrderList, couponList);
		
		if (flag) {
			logger.info("==============订单关闭成功==================");
		} else {
			logger.info("==============订单关闭失败，有错误==================rentOrderList=" + rentOrderList);
		}
	}
}
