package com.iamberry.wechat.handles.order.orderListener;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

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

import com.iamberry.wechat.core.entity.admin.ShopSystemRule;
import com.iamberry.wechat.core.entity.coupon.CouponItem;
import com.iamberry.wechat.core.entity.order.Order;
import com.iamberry.wechat.face.coupon.CouponItemService;
import com.iamberry.wechat.face.order.AdminOrderService;
import com.iamberry.wechat.tools.DateTimeUtil;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.utils.SendMessageUtil;

public class OrderCloseListener {

	@Autowired
	private AdminOrderService adminOrderService; 
	
	@Autowired
	private CouponItemService couponItemService;
	
	@Autowired
	private SendMessageUtil sendMessageUtil;
	
	public final static Map<String, Object> validateCodeMap = new ConcurrentHashMap<>(); //已给出提醒的！
	
	
	@SuppressWarnings("null")
	public void closeOrderByCreateTime() {
//		System.out.println("走一走关闭订单的这个");
		
		Order order = new Order();
		//获取规则表中对于订单关闭限定的时间
		ShopSystemRule shopSystemRule = adminOrderService.getReluByRid(104);
		if (shopSystemRule == null) {
			return;
		}
		//获取的时间以分钟为单位，这里转换成秒，按秒计算
		order.setDeadline((int)(shopSystemRule.getRuleNum() * 60));
		
		//这里查看是否有5分钟还有为支付的订单
		List<Order> fiveorderList = adminOrderService.getOrderByCreateTimeAndFiveMinutes(order);
		if (fiveorderList != null || fiveorderList.size() != 0) {
			for (Order orders : fiveorderList) {
//System.out.println("来发送---------");
				//判断是否5分钟，是否已经发送过
				if(!validateCodeMap.containsKey(orders.getSalesOrderid())){ //没有存在
					//发送消息 DateTimeUtil.format(new Date(),NameUtils.DATE_TIME_FORMAT)
					String temp = ResultInfo.ORDERWEIZHIFU;
					temp = temp.replaceFirst("firstValueIamberry", ResultInfo.ORDERGUOQI)
							.replaceFirst("ordertapeValue",DateTimeUtil.format(orders.getSalesCreateDate(),NameUtils.DATE_TIME_FORMAT))
							.replaceFirst("ordeIDVALUE",orders.getSalesOrderid() )
							.replaceFirst("remarkValueIamberry", ResultInfo.INTOSHOP);
//					sendMessageUtil.sendTemplateMessageToOpenid(temp, orders.getSalesOpenid(), ResultInfo.ORDER_GUOQI,4);	
					//时间---订单id
					validateCodeMap.put(orders.getSalesOrderid(), DateTimeUtil.format(new Date(),NameUtils.DATE_TIME_FORMAT));
				}
				
			}
		}
		moveValidateCodeMap();
		
//System.out.println(validateCodeMap.size()+"这里大小咯");
		
		//根据规定时间查询订单，查询出的订单都是大于45分钟的待支付订单，这时应关闭订单
		List<Order> orderList = adminOrderService.getOrderByCreateTime(order);
		List<String> list = new ArrayList<String>();
		List<CouponItem> itemList = new ArrayList<CouponItem>();
		if (orderList == null || orderList.size() == 0) {
			return;
		}	
		for (Order orders : orderList) {
			list.add(orders.getSalesOrderid());
			CouponItem couponItem = new CouponItem();
			couponItem.setCouponItemId(orders.getCouponId());
			couponItem.setCouponItemUseropenid(orders.getSalesOpenid());
			couponItem.setOldCouponUseStatus(7);
			couponItem.setCouponUseStatus(1);
			itemList.add(couponItem);
		}
		//如果查询出了结果，则将这些订单调整为订单关闭状态
		adminOrderService.updateOrderByOrderId(list);
		//修改优惠券状态
		if (itemList.size()> 0) {
			couponItemService.updateCouponItemList(itemList);
		}
	}
	
	//时间大于5分钟的，全部都 移除.......
	public void moveValidateCodeMap() {
		Iterator it=validateCodeMap.keySet().iterator();      
		for (Entry<String, Object> item : validateCodeMap.entrySet()){
            Object dateString =item.getValue();
            Date begintime = DateTimeUtil.parse(dateString.toString(), NameUtils.DATE_TIME_FORMAT);
            Long diffMinutes =  DateTimeUtil.getDiffTimeMinutes(new Date(),begintime);
            if(diffMinutes>=15){
            	 validateCodeMap.remove(item.getKey());  
            }
            
        }   
	
	}
}
