package org.springblade.modules.finance.service.impl;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.cache.ParamCache;
import org.springblade.common.constant.CacheBizConstant;
import org.springblade.core.redis.cache.BladeRedis;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Author pangqijun
 * Date 2023/5/10
 * Description 处理订单超时的服务类
 */
@Slf4j
@Service
@Configuration
public class OrderTimeoutService {
    // 默认超时时间 30分钟
    private final static Long DEFAULT_TIMEOUT_TIME = 60 * 30L;

    @Resource
    private BladeRedis bladeRedis;

    /**
     * 添加任务到延时队列
     * @param orderId
     * @param transactionId
     * @param timeout
     */
    public void addTask(Long orderId, Long transactionId, long timeout) {
        try {
//            bladeRedis.setEx(CacheBizConstant.ORDER_TIMEOUT_PREFIX + orderId, orderId, timeout);
            bladeRedis.zAdd(CacheBizConstant.TIMEOUT_ORDER_LIST, orderId, DateUtil.currentSeconds() + timeout);
        } catch (Exception e) {
            log.error("添加订单到延时队列失败, orderId: {}, transactionId:{}", orderId, transactionId, e);
        }
    }

    @Async
    public void addTask(Long orderId, Long transactionId) {
        addTask(orderId, transactionId, getTimeoutTime());
    }

    /**
     * 获取订单超时时间，单位：秒
     */
    public long getTimeoutTime() {
        String value = ParamCache.getValueDefault(CacheBizConstant.ORDER_TIMEOUT, DEFAULT_TIMEOUT_TIME.toString());
        log.info("getTimeoutTime[{}]", value);
        return Long.parseLong(value);
    }
}
