package com.czg.task;

import com.czg.config.RedisCst;
import com.czg.constants.PpPackageConstants;
import com.czg.market.entity.PpPackageOrder;
import com.czg.market.service.PpPackageOrderService;
import com.czg.order.entity.GbOrder;
import com.czg.service.RedisService;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 套餐推广定时任务
 *
 * @author yjjie
 * @date 2025/12/19 10:05
 */
@Slf4j
@Component
public class PpPackageTask {

    @Resource
    private RedisService redisService;

    @Resource
    private PpPackageOrderService ppPackageOrderService;

    /**
     * 订单 过期
     * 每两小时 触发一次
     */
    public void ppOrderExpire() {
        // 当前系统时间
        LocalDateTime now = LocalDateTime.now();
        // 过期时间下限：当前时间往前推4小时（只查最近4小时内过期的）
        LocalDateTime expire4HoursAgo = now.minusHours(4);
        List<PpPackageOrder> expiredOrderList = ppPackageOrderService.list(QueryWrapper.create()
                .eq(PpPackageOrder::getStatus, PpPackageConstants.OrderStatus.PROCESSING)
                .le(PpPackageOrder::getExpireTime, now)
                .ge(PpPackageOrder::getExpireTime, expire4HoursAgo));

        // 处理已过期订单
        for (PpPackageOrder expiredOrder : expiredOrderList) {
            //退款
            ppPackageOrderService.expiredOrder(expiredOrder.getId());
        }

        //查询【当前时间往后2小时内】将要过期的订单
        LocalDateTime willExpire2HoursLater = now.plusHours(2);
        List<PpPackageOrder> willExpireOrderList = ppPackageOrderService.list(QueryWrapper.create()
                .eq(PpPackageOrder::getStatus, PpPackageConstants.OrderStatus.PROCESSING)
                .ge(PpPackageOrder::getExpireTime, now)
                .le(PpPackageOrder::getExpireTime, willExpire2HoursLater));
        // 处理将要过期订单（如推送提醒、催参团等）
        for (PpPackageOrder willExpireOrder : willExpireOrderList) {
            LocalDateTime endTime = willExpireOrder.getExpireTime();
            Duration duration = Duration.between(now, endTime);
            long seconds = duration.getSeconds();
            redisService.set(RedisCst.classKeyExpired.EXPIRED_PP_ORDER + willExpireOrder.getId(), willExpireOrder.getId(), seconds);
        }
    }
}
