package com.starry.admin.common.task;

import com.starry.admin.modules.order.module.entity.PlayOrderInfoEntity;
import com.starry.admin.modules.order.service.IPlayOrderInfoService;
import com.starry.admin.utils.SecurityUtils;
import java.util.ArrayList;
import java.util.Set;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 超时未接单的订单退款处理任务
 *
 * @author admin
 * @since 2024/8/15 13:24
 **/
@Slf4j
@Component
public class OverdueOrderHandlerTask {

    private static final String QUEUE_KEY = "random_order_queue";

    private static final int MAX_TIME = 24 * 60 * 40;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IPlayOrderInfoService playOrderInfoService;

    public void enqueue(String message) {
        enqueue(message, MAX_TIME);
    }

    public void enqueue(String message, long delaySeconds) {
        long score = System.currentTimeMillis() / 1000 + delaySeconds;
        stringRedisTemplate.opsForZSet().add(QUEUE_KEY, message, score);
    }

    /**
     * 每10秒钟检测，判断任务是否到期
     *
     * @author admin
     * @since 2024/8/15 13:47
     **/
    @Scheduled(fixedRate = 10000)
    public void processMessages() {
        long now = System.currentTimeMillis() / 1000;
        Set<String> messages = stringRedisTemplate.opsForZSet().rangeByScore(QUEUE_KEY, 0, now);
        if (messages == null) {
            return;
        }
        for (String message : messages) {
            log.info("处理消息{}", message);
            // 处理消息
            // 订单退款
            String[] strs = message.split("_");
            orderHandler(strs[0], strs[1]);
            // 移除已经处理的消息
            stringRedisTemplate.opsForZSet().remove(QUEUE_KEY, message);
        }
    }

    public void orderHandler(String orderId, String tenantId) {
        SecurityUtils.setTenantId(tenantId);
        PlayOrderInfoEntity orderInfo = playOrderInfoService.getById(orderId);
        if (orderInfo == null) {
            return;
        }
        // 如果订单未接单，进行退款处理
        if ("0".equals(orderInfo.getOrderStatus())) {
            try {
                playOrderInfoService.updateStateTo4("2", "admin", orderInfo.getId(), "订单长时间未接单", new ArrayList<>());
            } catch (Exception e) {
                log.error("订单退款失败", e);
            }

        }
    }
}
