package com.fs.app.task;


import cn.hutool.json.JSONUtil;
import com.fs.common.annotation.DistributeLock;
import com.fs.common.constant.SystemConstant;
import com.fs.newAdv.domain.ConversionLog;
import com.fs.newAdv.enums.AdvertiserTypeEnum;
import com.fs.newAdv.integration.client.IApiClient;
import com.fs.newAdv.integration.factory.AdvertiserHandlerFactory;
import com.fs.newAdv.mapper.ConversionLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 转化回传重试定时任务
 * 每10分钟执行一次，重试失败的转化回传
 *
 * @author zhangqin
 * @date 2025-11-03
 */
@Slf4j
@Component
public class ConversionRetryTask {

    @Autowired
    private ConversionLogMapper conversionLogMapper;
    @Autowired
    private AdvertiserHandlerFactory advertiserHandlerFactory;

    /**
     * 转化回传重试任务
     * cron: 每10分钟执行
     */
    // @Scheduled(cron = "0 */5 * * * ?")
    @DistributeLock(scene = "task", key = "conversion_retry", waitTime = 0, errorMsg = "conversion_retry任务已执行")
    public void execute() {
        // 查询待重试的转化记录
        List<ConversionLog> pendingList = conversionLogMapper.selectPendingConversions();
        log.info("查询到 {} 条待重试的转化记录", pendingList.size());

        int successCount = 0;
        int failCount = 0;

        for (ConversionLog conversionLog : pendingList) {
            try {
                // 重试回传
                boolean success = retryConversion(conversionLog);
                if (success) {
                    successCount++;
                } else {
                    failCount++;
                }
            } catch (Exception e) {
                log.error("重试转化回传失败，ID：{}", conversionLog.getId(), e);
                failCount++;
            }
        }
        log.info("========== 转化回传重试任务完成，成功：{}，失败：{} ==========", successCount, failCount);
    }

    /**
     * 重试转化回传
     */
    private boolean retryConversion(ConversionLog conversionLog) {
        log.info("重试转化回传，ID：{}，重试次数：{}", conversionLog.getId(), conversionLog.getRetryCount());
        IApiClient apiClient = advertiserHandlerFactory.getApiClient(AdvertiserTypeEnum.getByCode(conversionLog.getAdvertiserId()));
        boolean b = apiClient.reportConversion(JSONUtil.parseObj(conversionLog.getCallbackParams()));
        if (b) {
            conversionLog.setCallbackStatus(1);
            conversionLog.setSuccessTime(LocalDateTime.now());
        }
        // 更新重试次数
        conversionLog.setRetryCount(conversionLog.getRetryCount() + 1);

        // 如果重试次数超过最大值，标记为失败
        if (conversionLog.getRetryCount() >= SystemConstant.MAX_RETRY_COUNT) {
            conversionLog.setCallbackStatus(2); // 失败
            log.warn("转化回传重试次数已达上限，ID：{}", conversionLog.getId());
        }
        conversionLog.setUpdateTime(LocalDateTime.now());
        conversionLogMapper.updateById(conversionLog);
        return b;
    }
}

