package com.red.circle.other.app.scheduler;


import com.red.circle.component.redis.annotation.TaskCacheLock;
import com.red.circle.other.app.manager.activity.award.WeeklyRewardsSentManager;
import com.red.circle.other.infra.database.mongo.entity.sys.ActivityConfig;
import com.red.circle.other.infra.database.mongo.service.sys.ActivityConfigService;
import com.red.circle.tool.core.collection.CollectionUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * rankingActivity 活动奖励发放
 */

@Slf4j
@Component
@RequiredArgsConstructor
public class RankingActivityRewardTask {

    private final WeeklyRewardsSentManager weeklyRewardsSentManager;
    private final ActivityConfigService activityConfigService;

    @Value("${activity.ranking.reward.ids:}")
    private String configuredActivityIds;

    /**
     * 每周一 0点0分执行.
     */
    @Scheduled(cron = "0 0 0 ? * MON", zone = "Asia/Riyadh")
    @TaskCacheLock(key = "RANKING_ACTIVITY_REWARD_TASK", expireSecond = 86400)
    public void sendRankingActivityReward() {
        long startTime = System.currentTimeMillis();
        log.warn("========== rankingActivity 活动奖励发放定时任务开始 ==========");

        try {
            // 解析配置的活动ID列表
            List<Long> activityIds = parseConfiguredActivityIds();
            
            if (CollectionUtils.isEmpty(activityIds)) {
                log.warn("未配置需要发放奖励的活动ID，跳过执行");
                return;
            }

            log.info("配置的活动ID列表: {}", activityIds);

            int successCount = 0;
            int skipCount = 0;
            int errorCount = 0;

            // 遍历每个活动ID
            for (Long activityId : activityIds) {
                try {
                    // 查询活动配置
                    ActivityConfig activityConfig = activityConfigService.getById(activityId);
                    
                    if (activityConfig == null) {
                        log.warn("活动不存在，跳过, activityId={}", activityId);
                        skipCount++;
                        continue;
                    }

                    // 检查活动是否上架
                    if (!isActivityOnline(activityConfig)) {
                        log.info("活动未上架，跳过, activityId={}, status={}", 
                                activityId, activityConfig.getShowcase());
                        skipCount++;
                        continue;
                    }

                    // 检查是否已发放过奖励
                    if (isRewardAlreadySent(activityConfig)) {
                        log.info("活动已发放过奖励，跳过, activityId={}", activityId);
                        skipCount++;
                        continue;
                    }

                    // 发放奖励
                    log.info("开始发放活动奖励, activityId={}, templateId={}, activityType={}", 
                            activityId, activityConfig.getTemplateId(), activityConfig.getActivityType());
                    
                    weeklyRewardsSentManager.sendLastRankingActivity(
                            activityConfig.getTemplateId(), 
                            activityConfig.getActivityType()
                    );

                    successCount++;
                    log.info("活动奖励发放成功, activityId={}", activityId);
                    
                } catch (Exception e) {
                    errorCount++;
                    log.error("活动奖励发放失败, activityId={}", activityId, e);
                }
            }

            log.warn("========== rankingActivity 活动奖励发放定时任务完成，耗时：{} ms, 成功：{}, 跳过：{}, 失败：{} ==========",
                    System.currentTimeMillis() - startTime, successCount, skipCount, errorCount);
                    
        } catch (Exception e) {
            log.error("========== rankingActivity 活动奖励发放定时任务异常 ==========", e);
        }
    }

    /**
     * 解析配置的活动ID列表
     */
    private List<Long> parseConfiguredActivityIds() {
        if (configuredActivityIds == null || configuredActivityIds.trim().isEmpty()) {
            return List.of();
        }
        
        return Arrays.stream(configuredActivityIds.split(","))
                .filter(id -> !id.isEmpty())
                .map(String::trim)
                .map(Long::valueOf)
                .toList();
    }

    /**
     * 检查活动是否上架
     */
    private boolean isActivityOnline(ActivityConfig activityConfig) {
        return Objects.equals(activityConfig.getShowcase(), Boolean.TRUE);
    }

    /**
     * 检查是否已发放过奖励
     * 
     * @param activityConfig 活动配置
     * @return true-已发放，false-未发放
     */
    private boolean isRewardAlreadySent(ActivityConfig activityConfig) {
        return activityConfig.getAwardStatus();
    }
}
