package com.qs.mp.quartz.task;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.qs.mp.channel.domain.ChannelOrder;
import com.qs.mp.channel.service.IChannelOrderService;
import com.qs.mp.common.enums.ChannelOrderStatusEnum;
import com.qs.mp.common.enums.DeliverOrderStatusEnum;
import com.qs.mp.common.utils.DateUtils;
import com.qs.mp.common.utils.LogUtil;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.qs.mp.user.domain.UserDeliverOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zhongcp
 * @Date 2022/3/17
 */
@Component("channelOrderTask")
public class ChannelOrderTask {

  protected final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());

  @Autowired
  private IChannelOrderService channelOrderService;

  private final int PAGE_SIZE = 500;


  /**
   * x天前的待收货订单自动确认收货任务
   */
  public void confirm(Integer day) {
    LogUtil.info(logger, "...渠道商订单自动确认收货任务开始...");
    LocalDateTime now = LocalDateTimeUtil.now();
    LocalDateTime deliveryTime = LocalDateTimeUtil.offset(now, -day, ChronoUnit.DAYS);

    List<ChannelOrder> channelOrderList = channelOrderService.list(new LambdaQueryWrapper<ChannelOrder>()
            .eq(ChannelOrder::getStatus, ChannelOrderStatusEnum.NOT_CONFIRM.getValue())
            .le(ChannelOrder::getDeliveryTime, deliveryTime));

    if (CollectionUtils.isNotEmpty(channelOrderList)) {
      for (ChannelOrder channelOrder : channelOrderList) {
        channelOrderService.confirm(channelOrder);
      }
    }

    LogUtil.info(logger, "...渠道商订单自动确认收货任务结束...");
  }



  /**
   * 订单取消到期任务
   */
  public void cancel() {
    LogUtil.info(logger, "...渠道未支付订单定时取消任务开始...");
    int total = PAGE_SIZE;
    while (total == PAGE_SIZE) {
      // 捞取30分钟前未支付订单
      List<ChannelOrder> channelOrderList = channelOrderService.list(
          new LambdaQueryWrapper<ChannelOrder>()
              .eq(ChannelOrder::getStatus, ChannelOrderStatusEnum.NOT_PAY)
              .lt(ChannelOrder::getCreatedTime, DateUtils.addMinutes(DateUtils.getNowDate(), -30))
              .last("limit " + PAGE_SIZE));
      total = channelOrderList.size();
      for (ChannelOrder channelOrder : channelOrderList) {
        try {
          channelOrderService.cancelOrder(channelOrder.getChannelId(), channelOrder.getOrderId());
        } catch (Exception e) {
          LogUtil.error(logger, e, "定时取消未支付渠道订单异常。orderId:{0}", channelOrder.getOrderId());
        }
      }
    }
    LogUtil.info(logger, "...渠道未支付订单定时取消任务结束...");
  }
}
