package com.ruoyi.novel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.novel.domain.AdCountRequest;
import com.ruoyi.novel.domain.AdLog;
import com.ruoyi.novel.domain.AdPlatformConfig;
import com.ruoyi.novel.mapper.AdLogMapper;
import com.ruoyi.novel.service.IAdService;
import com.ruoyi.novel.utils.AdPlatformClient;
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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdServiceImpl implements IAdService {
    private static final Logger logger = LoggerFactory.getLogger(AdServiceImpl.class);
    @Autowired
    private AdLogMapper adLogMapper;

    @Autowired
    private AdPlatformClient adPlatformClient;

    private Map<String, AdPlatformConfig> adConfigCache;
    private final Object lock = new Object();
    @Override
    @Transactional
    public void logAdView(AdLog adLog) {
        // 防止重复记录
        int count = adLogMapper.countByUserAndChapter(adLog.getUserId(), adLog.getChapterId());
        if (count > 0) {
            logger.warn("Duplicate ad log: user={}, chapter={}", adLog.getUserId(), adLog.getChapterId());
            return;
        }

        adLog.setSyncStatus(0); // 未同步状态
        adLogMapper.insert(adLog);
    }

//    @Override
//    @Async("adTaskExecutor")
//    public void syncWithAdPlatform(AdLog adLog) {
//        try {
//            adPlatformClient.syncAdPlatform(adLog);
//            adLog.setSyncStatus(1); // 同步成功
//        } catch (Exception e) {
//            logger.error("Ad sync failed: {}", e.getMessage());
//            adLog.setSyncStatus(2); // 同步失败
//        }
//        adLogMapper.updateById(adLog);
//    }

    @Override
    @Scheduled(fixedRateString = "${scheduled.ad-retry-interval:300000}") // 默认5分钟重试
    public void retryFailedSyncs() {
        List<AdLog> failedLogs = adLogMapper.selectList(
                new QueryWrapper<AdLog>().eq("sync_status", 2) // 2=同步失败状态
        );
        failedLogs.forEach(adLog -> {
            try {
                syncWithAdPlatform(adLog);  // 调用同步方法
                adLog.setSyncStatus(1);      // 更新为成功状态
                adLogMapper.updateById(adLog);
            } catch (Exception e) {
                logger.error("广告同步重试失败: ID={}", adLog.getId(), e);
            }
        });
    }

    @Override
    public Map<String, AdPlatformConfig> loadAdConfigs() {
        if (adConfigCache == null) {
            synchronized (lock) {
                if (adConfigCache == null) {
                    // 实际应从数据库加载
                    adConfigCache = new HashMap<>();
                    adConfigCache.put("tencent", new AdPlatformConfig(
                            "tencent", "腾讯广告",
                            "https://ad.tencent.com/track",
                            "token_123",
                            "{\"user_id\":\"${userId}\",\"chapter_id\":\"${chapterId}\"}"
                    ));
                    // 其他平台配置...
                }
            }
        }
        return adConfigCache;
    }
    @Override
    public void logAdView(AdCountRequest request) {
        AdLog log = new AdLog();
        log.setUserId(request.getUserId());
        log.setChapterId(request.getChapterId());
        log.setAdPlatform(request.getAdPlatform());
        log.setDeviceId(request.getDeviceId());
        log.setViewTime(new Date());
        log.setSyncStatus(0); // 未同步

        adLogMapper.insert(log);
    }
    @Override
    public List<AdLog> getAdLogsByUser(Long userId) {
        return adLogMapper.selectList(
                new QueryWrapper<AdLog>().eq("user_id", userId)
        );
    }
    @Override
    public void syncWithAdPlatform(AdLog adLog) {
        // 根据平台选择不同实现
        switch (adLog.getAdPlatform()) {
            case "tencent":
                adPlatformClient.syncTencent(adLog);
                adLog.setSyncStatus(1); // 同步成功
                break;
            case "pangle":
                adPlatformClient.syncPangle(adLog);
                adLog.setSyncStatus(1); // 同步成功
                break;
            default:
                logger.warn("Unknown ad platform: {}", adLog.getAdPlatform());
        }
    }
}
