package com.czg.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.czg.market.service.OrderInfoService;
import com.czg.order.entity.CashierCart;
import com.czg.order.entity.OrderInfo;
import com.czg.order.entity.OrderPayment;
import com.czg.order.service.CashierCartService;
import com.czg.order.service.OrderPaymentService;
import com.czg.service.order.enums.OrderStatusEnums;
import com.czg.service.order.service.PayService;
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.LocalDateTime;
import java.util.List;

/**
 * 订单定时任务
 *
 * @author ww
 * @description
 */
@Slf4j
@Component
public class OTimeTask {
    @Resource
    private OrderInfoService orderInfoService;
    @Resource
    private CashierCartService cartService;
    @Resource
    private OrderPaymentService orderPaymentService;
    @Resource
    private PayService payService;

    /**
     * order 过期
     */
    @Scheduled(cron = "0 0 1 * * ? ")
    public void run() {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setStatus(OrderStatusEnums.CANCELLED.getCode());
        orderInfoService.update(orderInfo, QueryWrapper.create()
                .eq(OrderInfo::getStatus, OrderStatusEnums.UNPAID.getCode())
                .lt(OrderInfo::getTradeDay, DateUtil.format(DateUtil.yesterday(), "yyyy-MM-dd")));

        QueryWrapper cartUpdateWrapper = new QueryWrapper();
        cartUpdateWrapper.lt(CashierCart::getCreateTime, DateUtil.format(DateUtil.yesterday(), "yyyy-MM-dd HH:mm:ss"))
                .and(wrapper -> {
                    wrapper.isNull(CashierCart::getUpdateTime).or(CashierCart::getUpdateTime).lt(DateUtil.format(DateUtil.yesterday(), "yyyy-MM-dd HH:mm:ss"));
                });
        cartService.remove(cartUpdateWrapper);
    }

    /**
     * 退钱补偿
     */
    @Scheduled(cron = "0 50 23 * * ? ")
    public void refundCompensate() {
        LocalDateTime tenMinutesAgo = LocalDateTime.now().minusMinutes(10);
        LocalDateTime thirdDayAgo = LocalDateTime.now().minusDays(3);
        List<OrderPayment> list = orderPaymentService.list(QueryWrapper.create()
                .gt(OrderPayment::getUpdateTime, thirdDayAgo)
                .lt(OrderPayment::getUpdateTime, tenMinutesAgo)
                .eq(OrderPayment::getPayType, "refund")
                .ne(OrderPayment::getPayStatus, "success"));
        for (OrderPayment payment : list) {
            String refPayOrderNo = "REP" + IdUtil.getSnowflakeNextId();
            payService.unifyRefund(payment, refPayOrderNo);
        }
    }
}
