package teen

import (
	"math/rand"
	"server/common"
	"server/game"
	"server/game/room"
	"server/msg"
	"time"

	"github.com/name5566/leaf/log"
)

// 向每个玩家发送当前回合的房间信息和玩家信息
func sendCurrentRoundInfo(teenPattiRoom *room.Room) {
	for _, player := range teenPattiRoom.Players {
		if player.Agent != nil {
			nextRoundInfo := &msg.NextRound{
				Info: &msg.ReqJoinRoom{
					UserId:   player.Id, // 设置当前玩家的 ID
					GameId:   "teen_patti",
					RoomId:   teenPattiRoom.Id,
					SitPos:   player.SitPos,
					RoomInfo: buildRoom(teenPattiRoom), // 获取房间信息
				},
			}

			// 发送 NextRound 消息
			player.Agent.WriteMsg(nextRoundInfo)
			log.Debug("Sent current round info to player %v in room %v", player.Id, teenPattiRoom.Id)
		}
	}
}

// 打印 teenPattiRoom.Players 的详细信息
func printPlayersInfo(teenPattiRoom *room.Room) {
	// 打印房间中的每个玩家
	for i, player := range teenPattiRoom.Players {
		if player != nil {
			log.Debug("Player %d: ID=%v, SitPos=%v, IsRobot=%v, Nickname=%v",
				i, player.Id, player.SitPos, player.IsRobot)
		} else {
			log.Debug("Player %d: Empty", i)
		}
	}
}

// 获取房间中所有空闲的座位号
func getAvailableSitPos(teenPattiRoom *room.Room) []int32 {
	// 假设一个房间最多有 5 个座位
	maxSeats := int32(5)
	availableSitPos := []int32{}

	// 创建一个已占用座位的集合
	occupiedSeats := make(map[int32]bool)

	// 遍历当前房间的所有玩家
	for _, player := range teenPattiRoom.Players {
		if player != nil {
			occupiedSeats[player.SitPos] = true // 标记已占用的座位
		}
	}

	// 检查哪些座位没有被占用
	for i := int32(0); i < maxSeats; i++ { // 使用 int32 类型
		if !occupiedSeats[i] {
			availableSitPos = append(availableSitPos, i) // 如果座位没有被占用，加入空闲座位列表
		}
	}
	// 返回空闲座位的列表
	return availableSitPos
}

func removeOfflinePlayers(teenPattiRoom *room.Room) {
	// 遍历玩家列表，找出离线玩家
	for _, player := range teenPattiRoom.Players {
		if !player.IsRobot && player.Agent != nil {
			userData, ok := player.Agent.UserData().(*common.UserData)
			if !ok || userData == nil {
				continue // 避免崩溃
			}

			// 判断是否离线
			if userData.Status == 0 {
				// 直接调用 LeaveTeenPattiRoom 移除玩家
				LeaveTeenPattiRoom(teenPattiRoom, player.Id, "0")
			}
		}
	}
}

// 过滤出非机器人的玩家
func filterNonRobotPlayers(teenPattiRoom *room.Room) []*room.Player {
	var players []*room.Player
	for _, player := range teenPattiRoom.Players {
		if !player.IsRobot {
			players = append(players, player)
		}
	}
	return players
}

// 初始化游戏
func startNextRound(teenPattiRoom *room.Room) {
	teenPattiRoom.Status = room.RoomStatusWaiting
	var currentDealerSitPos int32 = -1
	removeOfflinePlayers(teenPattiRoom)
	// 计算房间内的非机器人玩家数量
	nonRobotPlayers := filterNonRobotPlayers(teenPattiRoom)
	if len(nonRobotPlayers) == 0 {
		// 没有真人玩家了，解散房间
		log.Debug("Room %v dissolved due to no players left.", teenPattiRoom.Id)
		// 执行解散房间的逻辑，比如通知玩家、释放资源等
		dissolveRoom(teenPattiRoom)
		return
	}
	// 加减机器人
	adjustRobotCount(teenPattiRoom)
	// 清理上一回合的玩家状态
	for _, player := range teenPattiRoom.Players {
		// 如果该玩家是庄家，记录下座位号
		if player.IsDealer {
			currentDealerSitPos = player.SitPos
		}
		player.IsPacked = false
		player.IsSeen = false
		player.IsShow = false
		player.IsDealer = false // 清空上一回合的庄家状态
		player.CanShow = false
		player.HandCards = []*msg.ReqCard{}
	}
	// 增加回合计数
	teenPattiRoom.Round++

	// 更新回合信息
	// teenPattiRoom.GameRound.Rounds = append(teenPattiRoom.GameRound.Rounds, &msg.ReqRound{
	// 	Round: int32(teenPattiRoom.Round),
	// })
	// 初始化回合数据
	// 旧的需要入库吗?
	teenPattiRoom.GameRound.Rounds = []*msg.ReqRound{}

	teenPattiRoom.GameRound.TotalBet = 0 // 重置总下注

	// 重置下注金额区间
	confInfo := loadTeemConf(teenPattiRoom.ConfId)

	teenPattiRoom.GameRound.ResBet = confInfo

	// 更新座位状态，假设 SelfSitPos 和 RoundSitPos 已正确设置
	teenPattiRoom.RoundSitPos = 0 // 开始新回合，座位重置

	// 设置新的庄家
	setNextDealerSitPos(teenPattiRoom, currentDealerSitPos)
	// 开始下一回合
	log.Debug("Starting round %d for room %s", teenPattiRoom.Round, teenPattiRoom.Id)

	// 向每个玩家发送当前回合的玩家信息
	sendCurrentRoundInfo(teenPattiRoom)
	// room.SaveRoomToRedis(teenPattiRoom)
	// 2秒后开始发牌
	game.Module.Skeleton.AfterFunc(time.Second*2, func() {
		log.Debug("---------------------------------------------------------------------------------------")
		log.Debug("startDealCard(teenPattiRoom) %v in room %v")
		printPlayersInfo(teenPattiRoom)
		go startDealCard(teenPattiRoom) // 继续发牌
	})
}

// 调整房间中的机器人数量
func adjustRobotCount(teenPattiRoom *room.Room) {

	// 初始化随机数生成器
	random := rand.New(rand.NewSource(time.Now().UnixNano()))

	// 随机加减人数，确保人数在2到5之间
	currentPlayerCount := len(teenPattiRoom.Players)
	newPlayerCount := currentPlayerCount

	// 生成随机数来决定是否加人或减人
	if random.Intn(2) == 0 && newPlayerCount < 5 { // 50%几率加一个玩家，且最多不超过5人
		newPlayerCount++
	} else if random.Intn(3) == 0 && newPlayerCount > 2 { // 如果有更多于2个玩家，且随机选择去除玩家
		newPlayerCount--
	}
	// 打印 currentPlayerCount 和 newPlayerCount
	log.Debug("currentPlayerCount: %v", currentPlayerCount)
	log.Debug("newPlayerCount: %v", newPlayerCount)
	// 如果人数发生变化，则调整玩家数量
	if newPlayerCount != currentPlayerCount {
		if newPlayerCount > currentPlayerCount {
			// 获取空闲的座位
			availableSitPos := getAvailableSitPos(teenPattiRoom)
			// 如果没有空座位，不能再加入机器人
			if len(availableSitPos) == 0 {
				log.Debug("No available seats for new robot in room %v", teenPattiRoom.Id)
				return
			}
			// 加入新机器人
			addNewRobot(teenPattiRoom, availableSitPos)
			log.Debug("addNewRobot: %v")
		} else {
			// 随机去除一个机器人
			removeRandomRobot(teenPattiRoom)
			log.Debug("removeRandomRobot: %v")

		}
	}
}
