package com.qs.mp.quartz.task;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qs.mp.common.enums.TicketTypeEnum;
import com.qs.mp.common.enums.UserTicketOrderStatusEnum;
import com.qs.mp.common.utils.DateUtils;
import com.qs.mp.common.utils.LogUtil;
import com.qs.mp.user.domain.UserTicketOrder;
import com.qs.mp.user.service.IUserTicketOrderService;
import java.util.List;
import java.util.stream.Collectors;
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("ticketOrderTask")
public class TicketOrderTask {

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

  @Autowired
  private IUserTicketOrderService userTicketOrderService;

  private final int PAGE_SIZE = 500;

  /**
   * 订单取消到期任务
   */
  public void cancel() {
    LogUtil.info(logger, "...盲票购买未支付订单定时取消任务开始...");
    int total = PAGE_SIZE;
    while (total == PAGE_SIZE) {
      // 捞取30分钟前未支付在线盲票购买订单
      List<UserTicketOrder> ticketOrderList = userTicketOrderService.list(
          new QueryWrapper<UserTicketOrder>()
              .select("distinct box_id")
              .lambda().eq(UserTicketOrder::getResource, TicketTypeEnum.ONLINE)
              .eq(UserTicketOrder::getStatus, UserTicketOrderStatusEnum.NOT_PAY)
              .lt(UserTicketOrder::getCreatedTime,
                  DateUtils.addMinutes(DateUtils.getNowDate(), -30))
              .last("limit " + PAGE_SIZE));
      total = ticketOrderList.size();
      // 按票组分批次取消
      for (UserTicketOrder ticketOrder : ticketOrderList) {
        int boxTotal = 10;
        while (boxTotal == 10) {
          List<UserTicketOrder> orderList = userTicketOrderService.list(
              new QueryWrapper<UserTicketOrder>()
                  .select("order_id")
                  .lambda().eq(UserTicketOrder::getBoxId, ticketOrder.getBoxId())
                  .eq(UserTicketOrder::getStatus, UserTicketOrderStatusEnum.NOT_PAY)
                  .lt(UserTicketOrder::getCreatedTime,
                      DateUtils.addMinutes(DateUtils.getNowDate(), -30))
                  .last("limit " + 10));
          boxTotal = orderList.size();
          try {
            userTicketOrderService.batchCancelOrder(ticketOrder.getBoxId(),
                orderList.stream().map(UserTicketOrder::getOrderId).collect(
                    Collectors.toList()));
          } catch (Exception e) {
            LogUtil.error(logger, e, "定时取消未支付盲票购买订单异常。boxId:{0}, orderList:{1}",
                ticketOrder.getBoxId(),
                JSONObject.toJSONString(orderList));
          }

        }
      }
    }
    LogUtil.info(logger, "...盲票购买未支付订单定时取消任务结束...");
  }
}
