package service

import (
	"context"
	"time"

	mhayaTime "github.com/mhaya/extend/time"
	"github.com/mhaya/game/game_cluster/internal/code"
	"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/common"
	"github.com/mhaya/game/game_cluster/nodes/webadmin/entity"
	mhayaLogger "github.com/mhaya/logger"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type PlayerManage struct {
	db *mongo.Database
}

func NewPlayerManage() *PlayerManage {
	return &PlayerManage{
		db: mdb.MDB,
	}
}

// 获取玩家列表
func (a *PlayerManage) List(ctx context.Context, req entity.PlayerListReq) (*entity.PlayerListResp, *code.Result) {
	page, pageSize := checkPageParam(req.Page, req.Size)

	// 构建查询条件
	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 := a.db.Collection(constant.CNamePlayer).Find(ctx, filter, findOptions)
	if err != nil {
		mhayaLogger.Warnf("List Find error:%v", err)
		return nil, common.NewResult(code.InternalError)
	}
	defer func() {
		if closeErr := cursor.Close(ctx); closeErr != nil {
			mhayaLogger.Warnf("Error closing cursor: %v", closeErr)
		}
	}()

	// 解析结果
	details := make([]*entity.PlayerListDetail, 0)
	for cursor.Next(ctx) {
		var detail entity.PlayerListDetail
		if err := cursor.Decode(&detail); err != nil {
			mhayaLogger.Warnf("List Decode error:%v", err)
			return nil, common.NewResult(code.InternalError)
		}
		details = append(details, &detail)
	}
	if err := cursor.Err(); err != nil {
		mhayaLogger.Warnf("List cursor error:%v", err)
		return nil, common.NewResult(code.InternalError)
	}

	count, codeResult := a.GetPlayerTotalCount()
	if codeResult != nil {
		mhayaLogger.Warnf("List GetPlayerTotalCount codeResult:%v", codeResult)
		return nil, codeResult
	}

	return &entity.PlayerListResp{
		Details: details,
		Total:   count,
	}, nil
}

func (a *PlayerManage) GetPlayerTotalCount() (int64, *code.Result) {
	count := 0
	playerServerLoadStats, codeResult := NewAdmin().GetServerStatus(context.Background())
	if codeResult != nil {
		return 0, codeResult
	}

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

	return int64(count), nil
}

// 获取玩家详情
func (a *PlayerManage) PlayerInfo(ctx context.Context, req entity.PlayerInfoReq) (*entity.PlayerInfoResp, *code.Result) {
	var player models.Player
	err := a.db.Collection(constant.CNamePlayer).FindOne(context.Background(), bson.M{"userName": req.UserName}).Decode(&player)
	if err != nil {
		mhayaLogger.Warnf("PlayerInfo cursor error:%v", err)
		return nil, common.NewResult(code.InternalError)
	}

	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:           player.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) (*entity.RewardListResp, *code.Result) {
	page, pageSize := checkPageParam(req.Page, req.Size)

	// 构建查询条件
	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 := a.db.Collection(constant.CNamePlayerReward)
	// 获取总数total
	count, err := collection.CountDocuments(ctx, filter)
	if err != nil {
		mhayaLogger.Warnf("RewardList count error:%v", err)
		return nil, common.NewResult(code.InternalError)
	}

	// 执行查询
	cursor, err := collection.Find(ctx, filter, findOptions)
	if err != nil {
		mhayaLogger.Warnf("RewardList Find error:%v", err)
		return nil, common.NewResult(code.InternalError)
	}
	defer func() {
		if closeErr := cursor.Close(ctx); closeErr != nil {
			mhayaLogger.Warnf("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 {
			mhayaLogger.Warnf("RewardList Decode error:%v", err)
			return nil, common.NewResult(code.InternalError)
		}
		results = append(results, result.To())
	}
	if err := cursor.Err(); err != nil {
		mhayaLogger.Warnf("RewardList cursor error:%v", err)
		return nil, common.NewResult(code.InternalError)
	}

	return &entity.RewardListResp{
		Details: results,
		Total:   count,
	}, nil
}
