package org.springblade.modules.quartz.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springblade.common.constant.CacheBizConstant;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.modules.finance.service.IOrderService;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Author pangqijun
 * Date 2023/7/19
 * Description
 */
@Slf4j
@Component
public class OrderTimeoutTask {

    @Lazy
    @Resource
    private IOrderService orderService;
    @Resource
    private BladeRedis bladeRedis;
    @Resource
    private RedissonClient redissonClient;


    public void task() {
        RLock lock = redissonClient.getLock("order:timeout:local");
        lock.lock(10, TimeUnit.SECONDS);
        try {
            Set set = bladeRedis.zRange(CacheBizConstant.TIMEOUT_ORDER_LIST, 0, 5);
            if (CollUtil.isNotEmpty(set)) {
                for (Object next : set) {
                    long score = Math.round(bladeRedis.zScore(CacheBizConstant.TIMEOUT_ORDER_LIST, next));
                    long currentSeconds = DateUtil.currentSeconds();
                    if (currentSeconds >= score) {
                        log.info("处理超时订单,orderId[{}]", next);
                        orderService.orderTimeout((Long) next, null);
                        bladeRedis.zRem(CacheBizConstant.TIMEOUT_ORDER_LIST, next);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        } finally {
            if (lock.isLocked()) {
                lock.unlock();
            }
        }
    }
}
