package main

import (
	"fmt"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

func main() {
	dsn := "root:bindbox2025kdy@tcp(106.54.232.2:3306)/bindbox_game?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Info)})
	if err != nil {
		panic("failed to connect database: " + err.Error())
	}

	// 检查对对碰活动
	fmt.Println("========== 检查对对碰活动 (activity_category_id=3) ==========")

	type Activity struct {
		ID                 int64
		Name               string
		PlayType           string
		ActivityCategoryID int64
	}
	var matchingActs []Activity
	db.Table("activities").Where("activity_category_id = ?", 3).Limit(5).Find(&matchingActs)
	fmt.Printf("找到 %d 个对对碰活动\n", len(matchingActs))

	for _, act := range matchingActs {
		fmt.Printf("\n--- Activity ID=%d Name='%s' PlayType='%s' ---\n", act.ID, act.Name, act.PlayType)

		// 获取该活动的 issues
		type Issue struct {
			ID         int64
			ActivityID int64
		}
		var issues []Issue
		db.Table("activity_issues").Where("activity_id = ?", act.ID).Find(&issues)
		if len(issues) == 0 {
			fmt.Println("  No issues found")
			continue
		}

		issueIDs := make([]int64, len(issues))
		for i, iss := range issues {
			issueIDs[i] = iss.ID
		}
		fmt.Printf("  Issues: %v\n", issueIDs)

		// 统计 activity_draw_logs
		var drawLogsCount int64
		db.Table("activity_draw_logs").Where("issue_id IN ?", issueIDs).Count(&drawLogsCount)
		fmt.Printf("  Draw Logs count: %d\n", drawLogsCount)

		// 检查 reward_settings
		type RewardStat struct {
			Level       int32
			TotalOrig   int64
			TotalRemain int64
		}
		var rewardStats []RewardStat
		db.Table("activity_reward_settings").
			Select("level, SUM(original_qty) as total_orig, SUM(quantity) as total_remain").
			Where("issue_id IN ?", issueIDs).
			Group("level").
			Scan(&rewardStats)

		for _, rs := range rewardStats {
			issued := rs.TotalOrig - rs.TotalRemain
			fmt.Printf("  Level %d: OrigQty=%d Remain=%d Issued(库存差)=%d\n", rs.Level, rs.TotalOrig, rs.TotalRemain, issued)
		}

		// 统计 draw_logs 按 level
		type DrawLogStat struct {
			Level    int32
			WinCount int64
		}
		var drawStats []DrawLogStat
		db.Table("activity_draw_logs").
			Joins("JOIN activity_reward_settings ON activity_reward_settings.id = activity_draw_logs.reward_id").
			Where("activity_draw_logs.issue_id IN ?", issueIDs).
			Where("activity_draw_logs.is_winner = ?", 1).
			Select("activity_reward_settings.level, COUNT(activity_draw_logs.id) as win_count").
			Group("activity_reward_settings.level").
			Scan(&drawStats)

		for _, ds := range drawStats {
			fmt.Printf("  Level %d: WinCount(实际抽奖)=%d\n", ds.Level, ds.WinCount)
		}
	}

	fmt.Println("\n============================================")
}
