package org.wcs.quartzJob;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.wcs.constant.ConstantData;
import org.wcs.plugin.webHttpClient.WebHttpClient;
import org.wcs.plugin.webHttpClient.model.HttpRequest;
import org.wcs.plugin.webHttpClient.model.HttpResponse;
import org.wcs.utils.AppStringUtils;

import java.time.LocalDateTime;
import java.util.Set;

/**
 * 接口重试定时任务
 */
@Slf4j
@DisallowConcurrentExecution
@RequiredArgsConstructor
public class RetryApiRequestJob implements Job {

    private final StringRedisTemplate redisTemplate; // redis字符串操作类

    private static final String HTTP_REQUEST_CACHE = ConstantData.SYSTEM_NAME + ":HTTP:REQUEST";

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        Set<String> keys = redisTemplate.keys(HTTP_REQUEST_CACHE + ":*");
        for (String key : keys) {
            String value = redisTemplate.opsForValue().get(key);
            HttpRequest httpRequest = AppStringUtils.stringToObject(value, HttpRequest.class);
            if(httpRequest == null || !httpRequest.isAutoRetry()) {
                redisTemplate.delete(key);
                continue;
            }
            LocalDateTime nextRetryTime = httpRequest.getNextRetryTime();
            if(nextRetryTime != null && nextRetryTime.isBefore(LocalDateTime.now())) {
                continue;
            }
            httpRequest.setRetryCount(httpRequest.getRetryCount() + 1);
            HttpResponse httpResponse = WebHttpClient.httpRequest(httpRequest);
            log.info("接口重试，请求数据：{}，响应数据：{}", AppStringUtils.objectToString(httpRequest), AppStringUtils.objectToString(httpResponse));
        }
    }
}
