package player

import (
	"context"
	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/internal/param"
	clog "github.com/mhaya/logger"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
	"time"
)

func (p *actorPlayer) lottery(req *param.DrawReq) (*param.DrawResp, int32) {
	if !p.isOnline {
		clog.Infof("[lottery] PlayerNotLogin err node=%v", p.App().NodeId())
		return nil, code.PlayerNotLogin
	}
	var num = 1
	if req.Tp == 2 {
		num = 10
	}
	var resp param.DrawResp
	if p.Player.Item[models.ItemDrawsNumber].Num < num {
		return nil, code.NotEnoughItemsError
	}
	var addItem models.AddItem
	var SubItem models.SubItem
	for i := 0; i < num; i++ {
		draw := p.Player.Draw()
		addItem = addItem.Add(draw.Reward)
		resp.Draws = append(resp.Draws, &param.DrawConfig{ID: draw.ID, ItemID: draw.Reward[0].ItemID, Num: draw.Reward[0].Amount})
	}
	resp.Multi = num
	resp.AddItem = addItem
	si := SubItem.AddById(models.ItemDrawsNumber, num)
	resp.SubItem = si
	p.dirty = true

	p.itemStat(resp.AddItem)

	return &resp, code.OK
}

func (p *actorPlayer) getLotteryHistory(req *param.PageReq) (interface{}, int32) {
	if !p.isOnline {
		clog.Infof("[getLotteryHistory] PlayerNotLogin err node=%v", p.App().NodeId())
		return nil, code.PlayerNotLogin
	}
	findFilter := bson.M{"userName": p.Player.UserName, "source": models.SourceDraw, "createTime": bson.M{"$gte": mhayaTime.Now().Add(-time.Hour * 24 * 7).Unix()}}

	findOptions := options.Find()
	findOptions.SetSkip(int64((req.Page - 1) * 10))
	findOptions.SetLimit(int64(10))
	findOptions.SetSort(bson.D{{"createTime", -1}})

	ctx := context.Background()
	collection := mdb.MDB.Collection(constant.CNamePlayerReward)
	cursor, err := collection.Find(ctx, findFilter, findOptions)
	if err != nil {
		//return nil, code.Error
	}
	defer func() {
		if closeErr := cursor.Close(ctx); closeErr != nil {
			log.Printf("Error closing cursor: %v", closeErr)
		}
	}()

	// 获取总数total
	count, err := collection.CountDocuments(ctx, findFilter)
	if err != nil {
		return nil, code.Error
	}

	// 解析结果
	playerRewardBase := make([]*models.ToPlayerReward, 0)
	for cursor.Next(ctx) {
		var admin models.ToPlayerReward
		err = cursor.Decode(&admin)
		if err != nil {
			continue
		}
		playerRewardBase = append(playerRewardBase, &admin)
	}

	resp := RespReward{List: playerRewardBase, Total: count}

	return resp, code.OK
}

type RespReward struct {
	List  []*models.ToPlayerReward `json:"list"`
	Total int64                    `json:"total"`
}
