package cn.com.countrygarden.bi.main.controller.mediaResource;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import cn.com.countrygarden.bi.main.core.ResultGenerator;
import cn.com.countrygarden.bi.main.dao.mediaResource.AdvertistingReserveMapper;
import cn.com.countrygarden.bi.main.dao.mediaResource.MediaCycleLogMapper;
import cn.com.countrygarden.bi.main.dto.AdvertisingResourcesDto;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.mediaResource.MediaCycle;
import cn.com.countrygarden.bi.main.model.mediaResource.MediaCycleLog;
import cn.com.countrygarden.bi.main.model.mediaResource.MediaOrderParam;
import cn.com.countrygarden.bi.main.util.DateUtil;
import cn.com.countrygarden.bi.main.util.SnowflakeUtil;
@Component
public class ReserveSchdule {
	
	@Autowired
	private AdvertistingReserveMapper mapper;
	@Autowired
	private MediaCycleLogMapper mediaCycleLogMapper;
	@Scheduled(cron = "0 0 0 * * ?")
	public void cancelOrder() {
		/**
		以订单创建时间为准,7天预定后如果未锁定则自动取消
		**/
		
		try {
			System.out.println("----------------------------自动释放资源定时器开始执行--------------------------");
			List<String> paramList = mapper.getOverDateCycle();
			List<MediaCycleLog> logList = new ArrayList<MediaCycleLog>();
			for(String orderId:paramList) {
				//订单状态置为已终止
				AdvertisingResourcesDto obj = new AdvertisingResourcesDto();
				obj.setOrderId(orderId);
				obj.setOrderStatus("3");
				obj.setModBy("sysUser");
				obj.setModTime(new Date());
				obj.setModByName("sysUser");
				obj.setRemark("预定超时，系统自动释放");
				mapper.updateOrderStatus(obj);
				//明细置为未使用
				obj.setCycleStatus("0");
				mapper.updateOrderBillStatus(obj);
				//释放资源
				mapper.delCycleMedia(obj);
				//获取订单明细   存储纪录表使用
				logList = mapper.getOrderBillDetail(obj);
			}
			for(MediaCycleLog log:logList) {
				Long  cycleLogId = SnowflakeUtil.INSTANCE.getId();
				log.setCreateBy("sysUser");
				log.setCreateByName("sysUser");
				log.setCreateTime(new Date());
				log.setCycleStatus("0");
				log.setCycleLogId(cycleLogId);
			}
			//保存排期纪录表
			if(logList!=null && logList.size()>0) {
				mediaCycleLogMapper.insertList(logList);
			}
			//释放订单在锁定状态还有预定状态的资源  7 天
			List<String> lockOrderNotLockRes = mapper.findOrderLockResource();
			if (!lockOrderNotLockRes.isEmpty()) {
				mapper.delOrderBillList(lockOrderNotLockRes);
				lockOrderNotLockRes.forEach(i->{mapper.delCycle(i);});
			}
			
		}catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("----------------------------自动释放资源定时器执行结束--------------------------");
	}
	
}
