package com.njcn.device.pq.controller.file;

import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.utils.HttpResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.async.DeferredResult;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class PendingRequestManager {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 本地映射：msgId -> DeferredResult，主要用于超时清理和主动完成
    private final ConcurrentHashMap<String, DeferredResult<Object>> deferredResultMap = new ConcurrentHashMap<>();

    // 创建挂起请求
    public DeferredResult<Object> createPendingRequest(String msgId, long timeoutMs) {
        DeferredResult<Object> deferredResult = new DeferredResult<>(timeoutMs);
        // 超时回调
        deferredResult.onTimeout(() -> {
            // 清理 Redis 中的等待记录
            redisTemplate.delete("pending:" + msgId);
            deferredResultMap.remove(msgId);
            deferredResult.setErrorResult(new BusinessException("前置超时...."));
        });
        // 完成回调（正常或异常后移出本地映射）
        deferredResult.onCompletion(() -> deferredResultMap.remove(msgId));

        deferredResultMap.put(msgId, deferredResult);
        return deferredResult;
    }

    // 收到 Redis 通知后，根据 msgId 完成请求
    public void completeRequest(String msgId) {
        if (deferredResultMap.containsKey(msgId)) {
            DeferredResult<Object> deferredResult = deferredResultMap.get(msgId);

            // 从 Redis 中获取结果内容
            String key = "pending:" + msgId;
            Object result = redisTemplate.opsForValue().get(key);
            if (result != null) {
                deferredResult.setResult( HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result,""));
            } else {
                log.info("Receive notification for unknown msgId: " + msgId);
                deferredResult.setErrorResult(new BusinessException("前置未返回结果"));
            }
            // 清理 Redis 中的记录（可选，利用过期时间自动删除也可）
            redisTemplate.delete(key);
        } else {
            // 可能请求已超时被移除了，仅记录日志即可
            log.info("Receive notification for unknown msgId: " + msgId);
        }
    }
}