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


import com.red.circle.component.redis.service.RedisService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

//@Component
@RequiredArgsConstructor
public class HotGameTask {

    private final JdbcTemplate jdbcTemplate;
    private final RedisService redisService;

    /**
     * Redis key 常量定义
     */
    private static final String REDIS_KEY_PREFIX = "HOTGAME:";
    private static final String REDIS_KEY_RATIO = REDIS_KEY_PREFIX + "RATIO";
    private static final String REDIS_KEY_VIP = REDIS_KEY_PREFIX + "VIP";

    /**
     * 大盘数据
     */
    @Scheduled(cron = "0 0 * * * ?")
    public void calculateHotGameRatio() {
        System.out.println("开始执行热游大盘返奖比计算任务...");
        // 获取当前月份
        Calendar cal = Calendar.getInstance();
        String tableSuffix = String.valueOf(cal.get(Calendar.MONTH) + 1);

        String sql = """
            SELECT 
                SUM(IF(event_type LIKE 'HOT_GAME%' AND type = 1, penny_amount, 0)) AS hot_game_water,
                SUM(IF(event_type LIKE 'HOT_GAME%' AND type = 0, penny_amount, 0)) AS hot_game_reward
            FROM lotfun_wallet.wallet_gold_asset_record_{table}
            """.replace("{table}", tableSuffix);

        Map<String, Object> result = jdbcTemplate.queryForMap(sql);

        String waterStr = String.valueOf(result.get("hot_game_water"));
        String rewardStr = String.valueOf(result.get("hot_game_reward"));

        BigDecimal water = new BigDecimal(waterStr);
        BigDecimal reward = new BigDecimal(rewardStr);

        BigDecimal ratio = BigDecimal.ZERO;
        if (water.compareTo(BigDecimal.ZERO) != 0) {
            ratio = reward.multiply(new BigDecimal("100"))
                    .divide(water, 2, RoundingMode.HALF_UP);
        }

        redisService.redisTemplate().opsForValue().set(REDIS_KEY_RATIO, ratio.intValue());
        //结束输出日志
        System.out.println("Hot Game Ratio: " + ratio);

    }

    @Scheduled(cron = "0 0 0 * * ?")
    public void calculateHotGameVIP() {
        System.out.println("开始执行热游VIP计算任务...");
        // 获取当前月份
        Calendar cal = Calendar.getInstance();
        String tableSuffix = String.valueOf(cal.get(Calendar.MONTH) + 1);

        long sevenDaysAgo = System.currentTimeMillis() - 7 * 24 * 60 * 60 * 1000;

        String sql = """
            SELECT user_id, 
                   SUM(IF(type = 1, penny_amount, 0)) as total_water
            FROM lotfun_wallet.wallet_gold_asset_record_{table}
            WHERE event_type LIKE 'HOT_GAME%'
              AND create_time >= ?
            GROUP BY user_id
            ORDER BY total_water DESC
            """.replace("{table}", tableSuffix);

        List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, sevenDaysAgo);

        int totalUsers = results.size();
        int vip1Start = (int) (totalUsers * 0.02);
        int vip1End = (int) (totalUsers * 0.03);
        int vip2Start = (int) (totalUsers * 0.01);
        int vip2End = (int) (totalUsers * 0.02);
        int vip3End = (int) (totalUsers * 0.01);

        Set<String> vip1Users = new HashSet<>();
        Set<String> vip2Users = new HashSet<>();
        Set<String> vip3Users = new HashSet<>();

        for (int i = 0; i < results.size(); i++) {
            String userId = String.valueOf(results.get(i).get("user_id"));

            if (i < vip3End) {
                vip3Users.add(userId);
            } else if (i >= vip2Start && i < vip2End) {
                vip2Users.add(userId);
            } else if (i >= vip1Start && i < vip1End) {
                vip1Users.add(userId);
            }
        }

        // 充值VIP
        String rechargeSql = """
            SELECT 
                user_id,
                SUM(penny_amount) as total_recharge,
                MAX(create_time) as last_recharge_time
            FROM lotfun_wallet.wallet_gold_asset_record_{table}
            WHERE (event_type = 'BUY_GOLD' OR event_type = 'SHIPPING_AGENT')
                AND create_time >= ?
            GROUP BY user_id
            HAVING total_recharge >= 1500000
            """.replace("{table}", tableSuffix);

        List<Map<String, Object>> rechargeResults = jdbcTemplate.queryForList(rechargeSql, sevenDaysAgo);

        long currentTime = System.currentTimeMillis();
        long twoDaysAgo = currentTime - 2 * 24 * 60 * 60 * 1000;
        long fourDaysAgo = currentTime - 4 * 24 * 60 * 60 * 1000;

        for (Map<String, Object> result : rechargeResults) {
            String userId = String.valueOf(result.get("user_id"));
            long lastRechargeTime = Long.parseLong(String.valueOf(result.get("last_recharge_time")));

            if (lastRechargeTime >= twoDaysAgo) {
                vip3Users.add(userId);
            } else if (lastRechargeTime >= fourDaysAgo) {
                vip2Users.add(userId);
            } else {
                vip1Users.add(userId);
            }
        }

        redisService.redisTemplate().opsForHash().put(REDIS_KEY_VIP, "VIP1", vip1Users);
        redisService.redisTemplate().opsForHash().put(REDIS_KEY_VIP, "VIP2", vip2Users);
        redisService.redisTemplate().opsForHash().put(REDIS_KEY_VIP, "VIP3", vip3Users);
        // 添加日志打印
        System.out.println("VIP1用户数量: " + vip1Users.size() + ", 用户列表: " + vip1Users);
        System.out.println("VIP2用户数量: " + vip2Users.size() + ", 用户列表: " + vip2Users);
        System.out.println("VIP3用户数量: " + vip3Users.size() + ", 用户列表: " + vip3Users);
    }

    @Scheduled(cron = "0 0 * * * ?")
    public void calculateLossVIP() {
        System.out.println("开始执行热游亏损VIP计算任务...");
        Calendar cal = Calendar.getInstance();
        String tableSuffix = String.valueOf(cal.get(Calendar.MONTH) + 1);
        long oneDayAgo = System.currentTimeMillis() - 24 * 60 * 60 * 1000;

        String sql = """
            SELECT 
                user_id,
                SUM(IF(event_type LIKE 'HOT_GAME%' AND type = 0, penny_amount, 0)) AS game_income,
                SUM(IF(event_type LIKE 'HOT_GAME%' AND type = 1, penny_amount, 0)) AS game_cost
            FROM lotfun_wallet.wallet_gold_asset_record_{table}
            WHERE create_time >= ?
                AND event_type LIKE 'HOT_GAME%'
            GROUP BY user_id
            HAVING (game_cost - game_income) >= 500000
            """.replace("{table}", tableSuffix);

        List<Map<String, Object>> lossResults = jdbcTemplate.queryForList(sql, oneDayAgo);

        // 获取现有的VIP2用户集合
        Object vip2Obj = redisService.redisTemplate().opsForHash().get(REDIS_KEY_VIP, "VIP2");
        Set<String> existingVip2Users = null;
        if (vip2Obj instanceof Set<?>) {
            // 确认对象是Set类型后进行强制类型转换
            existingVip2Users = (Set<String>) vip2Obj;
        }

        // 如果 existingVip2Users 为 null，创建一个新的 HashSet
        Set<String> vip2Users = existingVip2Users != null ? new HashSet<>(existingVip2Users) : new HashSet<>();

        // 添加亏损用户
        for (Map<String, Object> result : lossResults) {
            vip2Users.add(String.valueOf(result.get("user_id")));
        }

        // 更新Redis
        redisService.redisTemplate().opsForHash().put(REDIS_KEY_VIP, "VIP2", vip2Users);

        // 打印日志
        System.out.println("更新后的VIP2用户数量: " + vip2Users.size() + ", 用户列表: " + vip2Users);
    }
}
