package com.inspect.analysis.service.impl;

import com.inspect.analysis.constant.AnalyseConstants;
import com.inspect.base.redis.service.RedisService;
import com.inspect.partrolresult.domain.AnalyseRequest;
import com.inspect.partrolresult.service.IAnalyseRequestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.io.IOException;

//@Component
public class AlgorithmRequestProcessConsumer {
    private final Logger logger = LoggerFactory.getLogger(AlgorithmRequestProcessConsumer.class);

    @Value("${task.test-mode:false}")
    private boolean testMode;

    @Resource
    private RedisService redisService;

    @Resource
    private IAnalyseRequestService analyseRequestService;

    //@Scheduled(fixedDelay = 1000)
//    @Scheduled(fixedDelayString = "${task.scheduler.request.delay-ms:3000}")
//    public void pollAndProcess() {
//        //logger.info(Color.YELLOW + "AlgorithmRequestProcessConsumerTracer" + Color.END);
//        String requestDataInRedis;
//        RedisTemplate<String, String> redisTemplate = redisService.redisTemplate;
//        while ((requestDataInRedis = redisTemplate.opsForList().leftPop(AnalyseConstants.ALGORITHM_REQUEST_QUEUE, Duration.ofMillis(500))) != null) {
//            try {
//                logger.info(Color.CYAN + "AlgorithmRequestProcessConsumerTracer queueSize: {}, requestData: {}"  + Color.END, getQueueSize(), requestDataInRedis);
//                AnalyseRequest analyseRequest = new Gson().fromJson(requestDataInRedis, AnalyseRequest.class);
//                analyseRemoteService.sendRequest(analyseRequest, analyseRequest.getTypeList(), analyseRequest.isFilter());
//            } catch (Exception e) {
//                logger.error(e.getMessage(), e);
//            }
//        }
//    }

    @Scheduled(fixedDelayString = "${task.scheduler.request.delay-ms:3000}")
    public void pollAndProcess() {
        RedisQueueConsumer<AnalyseRequest> consumer = new RedisQueueConsumer<AnalyseRequest>(
                redisService.redisTemplate,
                AnalyseConstants.ALGORITHM_REQUEST_QUEUE,
                AnalyseRequest.class,
                1000, // 每条消息间隔 1000ms 处理
                500, // 空队列时等待 500ms
                request -> {
                    try {
                        analyseRequestService.sendRequest(request, request.getTypeList(), request.isFilter());
                    } catch (IOException e) {
                        logger.error(e.getMessage(), e);
                    }
                }
        );

        consumer.consumeLoop(); // 开始消费本轮队列
    }

    public long getQueueSize() {
        return redisService.redisTemplate.opsForList().size(AnalyseConstants.ALGORITHM_REQUEST_QUEUE);
    }
}
