package service

import (
	"context"
	"log"
	"time"

	mhayaTime "github.com/mhaya/extend/time"
	cutils "github.com/mhaya/extend/utils"
	"github.com/mhaya/game/game_cluster/internal/constant"
	"github.com/mhaya/game/game_cluster/internal/mdb"
	"github.com/mhaya/game/game_cluster/internal/mdb/models"
	"github.com/mhaya/game/game_cluster/nodes/webadmin/entity"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type PlayerManage struct {
}

func NewPlayerManage() *PlayerManage {
	return &PlayerManage{}
}

// 获取玩家列表
func (a *PlayerManage) List(ctx context.Context, req entity.PlayerListReq) ([]*entity.PlayerListResp, int64, error) {
	page := req.Page
	// 验证参数
	if page <= 0 {
		page = 1
	}
	pageSize := req.Size
	if pageSize <= 0 {
		pageSize = 10
	}

	// 构建查询条件
	filter := bson.M{}
	if req.UserName != "" {
		filter["userName"] = bson.M{"$regex": escapeRegex(req.UserName), "$options": "i"}
	}
	if req.NickName != "" {
		filter["nickName"] = bson.M{"$regex": escapeRegex(req.NickName), "$options": "i"}
	}
	if req.OpenId != "" {
		filter["openId"] = req.OpenId
	}
	if req.Pid != "" {
		filter["pid"] = req.Pid
	}
	if req.XID != "" {
		filter["xID"] = req.XID
	}
	if req.TonWall != "" {
		filter["tonWall"] = req.TonWall
	}
	if req.Email != "" {
		filter["email"] = req.Email
	}
	if req.LevelMin > 0 && req.LevelMax == 0 {
		filter["level"] = bson.M{
			"$gte": req.LevelMin,
			"$lte": 1000, // 等级最大值
		}
	}
	if req.LevelMin >= 0 && req.LevelMax > 0 && req.LevelMin <= req.LevelMax {
		filter["level"] = bson.M{
			"$gte": req.LevelMin,
			"$lte": req.LevelMax,
		}
	}
	if req.Status > 0 {
		filter["status"] = req.Status
	}
	if req.LoginIP != "" {
		filter["loginIP"] = req.LoginIP
	}
	if req.JoinTimeMin > 0 && req.JoinTimeMax > 0 && req.JoinTimeMin <= req.JoinTimeMax {
		filter["joinTime"] = bson.M{
			"$gte": req.JoinTimeMin,
			"$lte": req.JoinTimeMax,
		}
	}

	// 设置分页选项
	skip := (page - 1) * pageSize
	limit := pageSize
	findOptions := options.Find().SetSkip(int64(skip)).SetLimit(int64(limit))

	// 执行查询
	cursor, err := mdb.MDB.Collection(constant.CNamePlayer).Find(ctx, filter, findOptions)
	if err != nil {
		return nil, 0, err
	}
	defer func() {
		if closeErr := cursor.Close(ctx); closeErr != nil {
			log.Printf("Error closing cursor: %v", closeErr)
		}
	}()

	// 解析结果
	results := make([]*entity.PlayerListResp, 0)
	for cursor.Next(ctx) {
		var result entity.PlayerListResp
		if err := cursor.Decode(&result); err != nil {
			return nil, 0, err
		}
		results = append(results, &result)
	}
	if err := cursor.Err(); err != nil {
		return nil, 0, err
	}

	count := 0
	playerServerLoadStats, err := NewAdmin().GetServerStatus(ctx)
	if err != nil {
		return nil, 0, err
	}

	for _, v := range playerServerLoadStats {
		count += int(v.TotalUser)
	}

	return results, int64(count), nil
}

// 获取玩家详情
func (a *PlayerManage) PlayerInfo(ctx context.Context, req entity.PlayerInfoReq) (*entity.PlayerInfoResp, error) {
	var player models.Player
	err := mdb.MDB.Collection(constant.CNamePlayer).FindOne(context.Background(), bson.M{"userName": req.UserName}).Decode(&player)
	if err != nil {
		return nil, err
	}

	return &entity.PlayerInfoResp{
		UserName:       player.UserName,
		OpenId:         player.OpenId,
		UserNameMaybe:  player.UserNameMaybe,
		NickName:       player.NickName,
		Pid:            player.Pid,
		XID:            player.XID,
		TonWall:        player.TonWall,
		Email:          player.Email,
		Level:          player.Level,
		Status:         player.Status,
		LoginTime:      player.LoginTime,
		LoginIP:        player.LoginIP,
		JoinIP:         player.JoinIP,
		JoinTime:       player.JoinTime,
		Avatar:         player.Avatar,
		IsRobot:        player.IsRobot,
		IsLeader:       player.IsLeader,
		IsVip:          player.IsVip,
		Successions:    player.Successions,
		MaxSuccessions: player.MaxSuccessions,
		PrevTime:       player.PrevTime,
		UpdateTime:     player.UpdateTime,
		IsDrawShare:    player.Share.IsDrawShare,
		DrawShareTime:  player.Share.DrawShareTime,
		FirstReward:    player.FirstReward,
		Item: func() models.ToItemBasePack {
			item := make(models.ToItemBasePack, 8)
			for key, v := range player.Item {
				if v.ID == 3 || v.ID == 4 {
					item[key] = &models.ToItem{
						ID:       v.ID,
						ItemType: v.ItemType,
						ItemKey:  v.ItemKey,
						Num:      cutils.QuoInt64ByRatioToFloat64(int64(v.Num), constant.MoneyRatio),
						CurNum:   cutils.QuoInt64ByRatioToFloat64(int64(v.CurNum), constant.MoneyRatio),
						Total:    cutils.QuoInt64ByRatioToFloat64(int64(v.Total), constant.MoneyRatio),
						MaxNum:   cutils.QuoInt64ByRatioToFloat64(int64(v.MaxNum), constant.MoneyRatio),
					}
					continue
				}

				item[key] = &models.ToItem{
					ID:       v.ID,
					ItemType: v.ItemType,
					ItemKey:  v.ItemKey,
					Num:      float64(v.Num),
					CurNum:   float64(v.CurNum),
					Total:    float64(v.Total),
					MaxNum:   float64(v.MaxNum),
				}
			}

			return item
		}(),
		SinIn:        player.SinIn,
		DailyTask:    player.DailyTask,
		AchieveTask:  player.AchieveTask,
		RankReward:   player.RankReward,
		Invite:       player.Invite,
		InviteReward: player.InviteReward,
		Roll:         player.Roll,
	}, nil
}

// 获取玩家中奖记录(默认查询最近三天)
func (a *PlayerManage) RewardList(ctx context.Context, req entity.RewardListReq) ([]*models.ToPlayerRewardBase, int64, error) {
	page := req.Page
	// 验证参数
	if page <= 0 {
		page = 1
	}
	pageSize := req.Size
	if pageSize <= 0 {
		pageSize = 10
	}

	// 构建查询条件
	filter := bson.M{}
	if req.UserName != "" {
		filter["userName"] = bson.M{"$regex": escapeRegex(req.UserName), "$options": "i"}
	}
	filter["source"] = models.SourceDraw

	startTime := mhayaTime.Now().Add(-3 * 24 * time.Hour).Unix()
	endTime := mhayaTime.Now().Unix()
	if req.StartTime > 0 && req.StartTime >= startTime {
		if req.StartTime <= req.EndTime || req.EndTime == 0 {
			startTime = req.StartTime
		}
	}

	if req.EndTime > 0 && req.EndTime <= endTime {
		if req.StartTime <= req.EndTime {
			endTime = req.EndTime
		}
	}

	filter["createTime"] = bson.M{
		"$gte": startTime,
		"$lte": endTime,
	}

	// 设置分页选项
	skip := (page - 1) * pageSize
	limit := pageSize
	findOptions := options.Find().SetSkip(int64(skip)).SetLimit(int64(limit))

	collection := mdb.MDB.Collection(constant.CNamePlayerReward)
	// 获取总数total
	count, err := collection.CountDocuments(ctx, filter)
	if err != nil {
		return nil, 0, err
	}

	// 执行查询
	cursor, err := collection.Find(ctx, filter, findOptions)
	if err != nil {
		return nil, 0, err
	}
	defer func() {
		if closeErr := cursor.Close(ctx); closeErr != nil {
			log.Printf("Error closing cursor: %v", closeErr)
		}
	}()

	// 解析结果
	results := make([]*models.ToPlayerRewardBase, 0)
	for cursor.Next(ctx) {
		var result models.PlayerRewardBase
		if err := cursor.Decode(&result); err != nil {
			return nil, 0, err
		}
		results = append(results, result.To())
	}
	if err := cursor.Err(); err != nil {
		return nil, 0, err
	}

	return results, count, nil
}
