package com.ruoyi.novel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.novel.domain.AdLog;
import com.ruoyi.novel.domain.AdPlatformConfig;
import com.ruoyi.novel.mapper.AdLogMapper;
import com.ruoyi.novel.service.AdConfigService;
import com.ruoyi.novel.service.AdLogService;
import com.ruoyi.novel.service.AdSyncService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

// AdLogServiceImpl.java
@Service
@Slf4j
public class AdLogServiceImpl implements AdLogService {
    private static final Logger logger = LoggerFactory.getLogger(AdLogServiceImpl.class);

    @Autowired
    private AdLogMapper adLogMapper;

    @Autowired
    private AdConfigService adConfigService;

    @Autowired
    private AdSyncService adSyncService;

    @Override
    @Transactional
    public void logAdView(AdLog adLog) {
        // 1. 保存到数据库
        adLog.setSyncStatus(0); // 0=未同步
        adLogMapper.insert(adLog);

        // 2. 异步同步到广告平台
        syncAdLogAsync(adLog);
    }

    @Async
    public void syncAdLogAsync(AdLog adLog) {
        try {
            AdPlatformConfig config = adConfigService.getConfig(adLog.getAdPlatform());
            if (config == null) {
                throw new ServiceException("广告平台配置不存在: " + adLog.getAdPlatform());
            }

            // 根据平台选择同步方式
            switch (adLog.getAdPlatform()) {
                case "tencent":
                    adSyncService.syncToTencent(adLog, config);
                    break;
                case "pangle":
                    adSyncService.syncToPangle(adLog, config);
                    break;
                default:
                    throw new ServiceException("不支持的广告平台: " + adLog.getAdPlatform());
            }

            // 更新同步状态
            adLog.setSyncStatus(1); // 1=同步成功
        } catch (Exception e) {
            log.error("广告同步失败: {}", e.getMessage());
            adLog.setSyncStatus(2); // 2=同步失败
        }
        adLogMapper.updateById(adLog);
    }

    @Scheduled(fixedRate = 300000) // 每5分钟执行一次
    public void retryFailedSyncs() {
        List<AdLog> failedLogs = adLogMapper.selectList(
                new QueryWrapper<AdLog>().eq("sync_status", 2)
        );

        failedLogs.forEach(log -> {
            logger.info("重试广告同步: ID={}, 平台={}", log.getId(), log.getAdPlatform());
            syncAdLogAsync(log);
        });
    }
}
