package Module

import (
	"Server-Core/Server/GameServer/Server/PlaneGame/Utils"
	util "Server-Core/Server/GameServer/Server/PlaneGame/Utils"
	message "Server-Core/Server/Message"
	scheme "Server-Core/Server/Scheme"
	"encoding/json"
	"fmt"
	"math"
	"sort"
	"strconv"
	"sync"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/golang/protobuf/proto"
	log "github.com/sirupsen/logrus"
	"xorm.io/builder"
)

const (
	RoomIdle         int = 1 // 1代表空闲
	RoomBusy         int = 2 //2代表使用中
	GameNotStarted   int = 0 //1 未开始
	GamePlaying      int = 1 // 进行中
	GameEnd          int = 2 // 已结束
	ModeClass        int = 1 //经典
	ModeMatch        int = 2 //匹配
	Plus             int = 1 //加
	Reduce           int = 2 //减
	RoomIn           int = 1 //房间内
	RoomOut          int = 2 //房间外
	BroadcastInvisit int = 1 //1.邀请
	BroadcastStart   int = 2 //2.开始游戏
	PlayerIdle       int = 1 //1.玩家空闲
	PlayerMatching   int = 2 //2.玩家在匹配中
	PlayerRooming    int = 3 //2.玩家在房间内
)

type GameRoom struct {
	
	Id             int                   `xorm:"not null pk autoincr INT(11)" json:"id"`
	Ds             uint32                 `xorm:"-"`
	Players        map[int]*GamePlayer      `xorm:"-"`//开始游戏的总人数
	GzPlayers      []*GamePlayer          `xorm:"-"` //观战玩家人数
	RoomPlayers    map[string]*GamePlayer    `xorm:"-"`//房间内玩家
	PlayerNum      int                    `xorm:"INT(11)" ` //加入游戏房间人数
	StartPlayerNum int                     `xorm:"-"`//开始房间确定的游戏人数
	RankPlayers    map[int]*GamePlayer     `xorm:"-"`//结算时的游戏排行  //通过指针引用同一个玩家的内存地址，不会开辟新的内存空间
	RunnerNum      int                     `xorm:"-"`//逃跑人数
	ArrivalNum     int                     `xorm:"-"`//到达终点人数
	GameEnd        int                  `xorm:"INT(11)" `  //0未开始，1进行中，2已结束
	//	TimeOut     int           //房间内操作倒计时
	ticker       *time.Ticker
	DataList     []*scheme.SzItem   `xorm:"-"`//读取筛子权重的csv数据
	Status       int               `xorm:"INT(11)" ` //1代表空闲 2代表使用中
	MaxNum       int                `xorm:"-"`//最大房间人数
	AdmissionFee uint32             `xorm:"-"`//入场费
	MinNum       int               `xorm:"-"`//最小房间人数
	Type         int               `xorm:"INT(11)" `//1是logo,2 baloot

	Homeowner  int      `xorm:"-"`//房主id
	Mode       int      `xorm:"INT(11)" ` //游戏模式，1是经典，2是匹配
	RoomType   int      `xorm:"-"`//1是房间内开启，2是房间外开启
	ChatRoomId int     `xorm:"-"`//
	CountDown  int      `xorm:"-"`//结算倒计时
	Logo       string    `xorm:"VARCHAR(255)"`//结算倒计时 
}
type GameRoomVo struct {
	Id        int    `json:"id"`
	PlayerNum int    `json:"playerNum"` //加入游戏的人数
	Status    int    `json:"status"`    //房间状态 0未开始，1进行中，2已结束
	Logo      string `json:"logo"`      //房间logo
}

// 根据uid映射对应的房间
// var userRoom map[string]*GameRoom = make(map[string]*GameRoom)
var gameRooms map[int]*GameRoom = make(map[int]*GameRoom)
var DataList []*scheme.SzItem = []*scheme.SzItem{}
var Maps map[int][]int = make(map[int][]int)

type UserInfoReq struct {
	GameType    int        `json:"gameType"`    //游戏类型: 1.ludo 2.其他
	UserWallets []UserInfo `json:"userWallets"` //结算时的游戏排行
}
type UserInfo struct {
	GoldCoins int `json:"goldCoins"` //数量
	Type      int `json:"type"`      //类型: 1.加 2.减
	UserId    int `json:"userId"`    // ⽤户ID

}
type Obj struct {
	core   int //初始化最小对象数 100
	Max    int //最大对象数  1000
	UserId int //扩容阈值  100的倍数
	//每次扩容数
	//转对象池阈值

}

func ObjectPool() sync.Pool {

	// 一个[]byte的对象池，每个对象为一个[]byte
	var roomPool = sync.Pool{
		New: func() interface{} {
			b := make(map[int]*GameRoom)
			return &b
		},
	}
	return roomPool
}

// 房间id初始化
func RoomInit(start int, end int) {

	/*	if len(gameRooms)>2000 {
			var roomPool = sync.Pool{
			New: func() interface{} {
				b := make(map[int]*GameRoom)
				return &b
			},
		}
	}else {*/
	log.Info("min", len(gameRooms))
	log.Info("max", len(gameRooms)+100)
	for i := start; i < end; i++ {
		//mgr.idGenList[i] = 0 //初始化，全部没有被占用
		var room = GameRoom{}
		room.Id = i
		room.Status = RoomIdle
		room.PlayerNum = 0
		//room.DataList = DataList
		room.RunnerNum = 0
		room.ArrivalNum = 0
		room.GameEnd = GameNotStarted
		//room.Status = Busy
		gameRooms[i] = &room
		//roomPool.Put(gameRooms)
	}

}

func RoomInit2(c *gin.Context) SqlResponse{
	users := make([]GameRoom,1000)
	for i := 0; i < 1000; i++ {
			var room =GameRoom{Logo: "https://vr-1314677574.cos.ap-nanjing.myqcloud.com/icon.png"}
			users[i] = room
	}

	affected, err := Engine.Insert(&users)
	log.Println("aff==",affected)
	log.Info("errpppp",err)
	var sqlResponse SqlResponse = SqlResponse{
		Code:    200,
		Message: "成功",
	
	}

	//c.JSON(http.StatusOK, sqlResponse)
	return sqlResponse
}

// 获取空闲房间
func GetIdleRoom(adminfee uint32, maxnum int, mode int) *GameRoom {
	lock5.Lock()
	//var idle = 0
	var gameRoom *GameRoom
	for i := 1; i < len(gameRooms); i++ {
		//mgr.idGenList[i] = 0 //初始化，全部没有被占用
		if gameRooms[i].Status == RoomIdle {
			//	idle = idle + 1
			gameRooms[i].Status = RoomBusy

			//gameRoom = gameRooms[i]
			gameRooms[i].MinNum = 2
			gameRooms[i].AdmissionFee = adminfee
			gameRooms[i].MaxNum = maxnum
			gameRooms[i].Mode = mode
			//gameRooms[i].RoomType = true
			gameRooms[i].DataList = DataList
			//初始化构建玩家
			var rankPlayer = map[int]*GamePlayer{}
			var gzPlayer = []*GamePlayer{}
			var player = map[int]*GamePlayer{}
			var roomPlayer = map[string]*GamePlayer{}
			gameRooms[i].RoomPlayers = roomPlayer
			gameRooms[i].RankPlayers = rankPlayer
			gameRooms[i].GzPlayers = gzPlayer
			gameRooms[i].Players = player
			gameRooms[i].PlayerNum = 0
			gameRooms[i].RunnerNum = 0
			gameRooms[i].ArrivalNum = 0
			gameRooms[i].GameEnd = GameNotStarted

			gameRoom = gameRooms[i]
			break
		}
	}
	if gameRoom == nil {
		RoomInit(len(gameRooms), len(gameRooms)+100)
		lock5.Unlock()
		return GetIdleRoom(adminfee, maxnum, mode)
	}
	lock5.Unlock()
	return gameRoom
	/*if idle == 0 {

	}
	*/
}
func GetIdleRoom2(adminfee uint32, maxnum int, mode int) *GameRoom {
	lock5.Lock()
	//var idle = 0
	var gameRoom GameRoom= GameRoom{Status:1}

	//var gameRoom 
	has, _ := Engine.Get(&gameRoom)
	if has{
		gameRoom.Status = RoomBusy

		//gameRoom = gameRooms[i]
		gameRoom.MinNum = 2
		gameRoom.AdmissionFee = adminfee
		gameRoom.MaxNum = maxnum
		gameRoom.Mode = mode
		//gameRooms[i].RoomType = true
		gameRoom.DataList = DataList
		//初始化构建玩家
		var rankPlayer = map[int]*GamePlayer{}
		var gzPlayer = []*GamePlayer{}
		var player = map[int]*GamePlayer{}
		var roomPlayer = map[string]*GamePlayer{}
		gameRoom.Type=1
		gameRoom.RoomPlayers = roomPlayer
		gameRoom.RankPlayers = rankPlayer
		gameRoom.GzPlayers = gzPlayer
		gameRoom.Players = player
		gameRoom.PlayerNum = 0
		gameRoom.RunnerNum = 0
		gameRoom.ArrivalNum = 0
		gameRoom.GameEnd = GameNotStarted
		Engine.ID(gameRoom.Id).Update(gameRoom)
	}else {
		// RoomInit(len(gameRooms), len(gameRooms)+100)
		// lock5.Unlock()
		Engine.Insert(&gameRoom)
		gameRoom.Status = RoomBusy

		//gameRoom = gameRooms[i]
		gameRoom.MinNum = 2
		gameRoom.AdmissionFee = adminfee
		gameRoom.MaxNum = maxnum
		gameRoom.Mode = mode
		gameRoom.Type=1
		//gameRooms[i].RoomType = true
		gameRoom.DataList = DataList
		//初始化构建玩家
		var rankPlayer = map[int]*GamePlayer{}
		var gzPlayer = []*GamePlayer{}
		var player = map[int]*GamePlayer{}
		var roomPlayer = map[string]*GamePlayer{}
		gameRoom.RoomPlayers = roomPlayer
		gameRoom.RankPlayers = rankPlayer
		gameRoom.GzPlayers = gzPlayer
		gameRoom.Players = player
		gameRoom.PlayerNum = 0
		gameRoom.RunnerNum = 0
		gameRoom.ArrivalNum = 0
		gameRoom.GameEnd = GameNotStarted
		Engine.ID(gameRoom.Id).Update(gameRoom)
	}
	lock5.Unlock()
	return &gameRoom
	/*if idle == 0 {

	}
	*/
}
// 更新房间状态为空闲
func UpdateRoom(room *GameRoom) {
	/*	for for i := 0; i < len(players); i++  {

		}
		gameRooms[id].Players
		delete(userClientIds, uid)
		delete(clientUserIds, ws)*/
	// var room = GameRoom{}
	// room.Id = id
	// room.Status = Idle
	// room.PlayerNum = 0
	// //room.DataList = DataList
	// room.RunnerNum = 0
	// room.ArrivalNum = 0
	// room.GameEnd = 0
	// gameRooms[id] = &room
	if room != nil {
		if room.ticker!=nil{
			room.ticker.Stop()
		}
		room.Status = RoomIdle
	}

	// gameRooms[id].Status = Idle
	// gameRooms[id].PlayerNum = 0
	// gameRooms[id].Players = nil
	// gameRooms[id].GameEnd = 0
	// gameRooms[id].RunnerNum = 0
	// gameRooms[id].RankPlayers = nil
	// gameRooms[id].ticker = nil
	// gameRooms[id].DataList = nil
	// gameRooms[id].ArrivalNum = 0

	//return nil
	/*if idle == 0 {
	}
	*/
}

type SqlResponse struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}
type ResponseUserData struct {
	RoomId   string `json:"roomId"`
	DialogId int    `json:"dialogId"`
}
type ResponseUserData2 struct {
	//RoomId   string `json:"roomId"`
	DialogId int `json:"dialogId"`
}

func GameInit(c *gin.Context) SqlResponse {
	//解析游戏玩家数据
	//更改游戏玩家数据
	var reqData RequestUserData
	if err := c.BindJSON(&reqData); err != nil {
		log.Info("发生了错误")
	}
	//初始化房间地图
	room := GetIdleRoom(1, 1, 1)

	room.Status = RoomBusy
	room.DataList = DataList
	//初始化构建玩家
	var rankPlayer = map[int]*GamePlayer{}
	room.RankPlayers = rankPlayer
	for i := 0; i < len(reqData.Data); i++ {
		//初始化飞机
		var plane = []*GamePlane{}
		for j := 0; j < 4; j++ {
			gamePlane := createPlane(j, reqData.Data[i].Uid)
			plane = append(plane, &gamePlane)
		}
		gamePlayer := createPlayer(i, plane, reqData.Data, room)
		if room.Players[i] == nil {
			room.Players[i] = &gamePlayer
		}
		//room.Players = append(room.Players, &gamePlayer)
		if gamePlayer.GameRoom != nil {
			var sql = SqlResponse{
				Code:    666,
				Message: "有玩家已在游戏房间,不能开始游戏",
				//Data:    ResponseUserData,
			}
			return sql
			//临时初始化用
			//delete(userRoom, gamePlayer.Uid)
		}

		//	userRoom[gamePlayer.Uid] = room
		log.Info("玩家id", gamePlayer.Uid)
		go countdonw2(&gamePlayer, 4)
		//玩家设置倒计时，未连接则解散房间退出游戏 逻辑还未开发

	}

	var ResponseUserData = ResponseUserData{RoomId: strconv.Itoa(int(room.Id))}
	log.Print("response===", ResponseUserData)
	var sql = SqlResponse{
		Code:    200,
		Message: "成功",
		Data:    ResponseUserData,
	}
	return sql

}

// 热更新筛子csv文件
func ReloadConfig(c *gin.Context) {
	sz := util.ReadFile()
	DataList = sz.DataList
	//return room.Id

}

func endGame(uid string) {

	log.Info("广播游戏结束")

	//广播结束游戏
	rsp2 := &message.EndGameRsp{}
	//	uid := clientUserIds[ws]
	//结束游戏
	//log.Printf("uid===", getPlayer(uid))
	//log.Printf("room", getPlayer(uid).GameRoom)
	room := getPlayer(uid).GameRoom
	room.GameEnd = GameEnd
	room.ticker.Stop()
	//if room.GameEnd == 1 {
	/*	if room.ch != nil {
		close(room.ch)
		room.wg.Wait()

	}*/
	var money = []uint32{}
	var seatIds = []uint32{}
	var numberOfCollisions = []uint32{}
	var numberOfHitPieces = []uint32{}
	var nick = []string{}
	var moneytotal uint32 = 0
	for i := len(room.RankPlayers) - 1; i >= 0; i-- {
		moneytotal = moneytotal + room.AdmissionFee
	}
	if room.Mode == ModeClass {
		var homeownergoin = int(float64(moneytotal) * 0.05)
		var lastownergoin = uint32(float64(moneytotal) * 0.95)
		log.Info("排行数据", room.RankPlayers)

		var userInfos = []UserInfo{}

		for i := len(room.RankPlayers) - 1; i >= 0; i-- {
			//两个人玩的时候直接获胜，没逃跑的第一名，逃跑的第二名
			//var Type = 1
			var money1 uint32 = 0
			if len(room.RankPlayers) < 4 {
				if i == len(room.RankPlayers)-1 {
					//小于4个玩家的时候，第一一名玩家会获得除自己外的费用
					//Type = 1
					money1 = lastownergoin
					//不减去入场费
					money = append(money, lastownergoin)
				} else {

					//收入为0
					money = append(money, 0)
				}
			} else {
				if i == len(room.RankPlayers)-1 || i == len(room.RankPlayers)-2 {

					money = append(money, lastownergoin/2)
					//Type = 1
					//小于4个玩家的时候，第一和第二名玩家会获得除自己外的费用
					money1 = lastownergoin / 2
				} else {
					money = append(money, 0)

				}
			}
			uid2, _ := strconv.Atoi(room.RankPlayers[i].Uid)
			if money1 > 0 {
				var userInfo = UserInfo{
					UserId:    uid2,
					GoldCoins: int(money1),
					Type:      Plus,
				}
				userInfos = append(userInfos, userInfo)
			}

			seatIds = append(seatIds, room.RankPlayers[i].SeatId)
			numberOfCollisions = append(numberOfCollisions, room.RankPlayers[i].Kick)
			numberOfHitPieces = append(numberOfHitPieces, room.RankPlayers[i].BeKick)
			nick = append(nick, room.RankPlayers[i].Name)
		}
		var userInfo = UserInfo{
			UserId:    room.Homeowner,
			GoldCoins: homeownergoin,
			Type:      Plus,
		}
		userInfos = append(userInfos, userInfo)

		var userInfoReq = UserInfoReq{GameType: 1, UserWallets: userInfos}
		jsonData2, _ := json.Marshal(userInfoReq)
		Utils.PostData(jsonData2)
	} else if room.Mode == ModeMatch {
		//	var homeownergoin = int(float64(moneytotal) * 0.05)
		//var lastownergoin = uint32(float64(moneytotal) * 0.95)
		log.Info("排行数据", room.RankPlayers)

		var userInfos = []UserInfo{}

		for i := len(room.RankPlayers) - 1; i >= 0; i-- {
			//两个人玩的时候直接获胜，没逃跑的第一名，逃跑的第二名
			//var Type = 0
			var money1 uint32 = 0
			if len(room.RankPlayers) < 4 {
				if i == len(room.RankPlayers)-1 {
					//小于4个玩家的时候，最后一名玩家会获得除自己外的费用
					//Type = 1
					money1 = moneytotal
					//不减去入场费
					money = append(money, moneytotal)
				} else {

					//收入为0
					money = append(money, 0)
				}
			} else {
				if i == len(room.RankPlayers)-1 || i == len(room.RankPlayers)-2 {

					money = append(money, moneytotal/2)
					//Type = 1
					//小于4个玩家的时候，第一和第二名玩家会获得除自己外的费用
					money1 = moneytotal / 2
				} else {
					money = append(money, 0)

				}
			}
			uid2, _ := strconv.Atoi(room.RankPlayers[i].Uid)
			if money1 > 0 {
				var userInfo = UserInfo{
					UserId:    uid2,
					GoldCoins: int(money1),
					Type:      Plus,
				}
				userInfos = append(userInfos, userInfo)
			}

			seatIds = append(seatIds, room.RankPlayers[i].SeatId)
			numberOfCollisions = append(numberOfCollisions, room.RankPlayers[i].Kick)
			numberOfHitPieces = append(numberOfHitPieces, room.RankPlayers[i].BeKick)
			nick = append(nick, room.RankPlayers[i].Name)
		}

		var userInfoReq = UserInfoReq{GameType: 1, UserWallets: userInfos}
		jsonData2, _ := json.Marshal(userInfoReq)
		Utils.PostData(jsonData2)
	}

	//Utils.ChatRoomBroadcast(room.Id, 3, 1, room.Id)
	rsp2.Money = money
	rsp2.SeatID = seatIds
	rsp2.Kick = numberOfCollisions
	rsp2.BeKick = numberOfHitPieces
	//rsp2.Nick = nick
	rData2, _ := proto.Marshal(rsp2) //回包
	room.ticker.Stop()
	BroadInfo(room, int16(message.MSGID_Eng_Game_Rsp), rData2)
	log.Info("发送结束数据", rsp2)

	// result := Utils.ChatRoomBroadcast(room.ChatRoomId, BroadcastInvisit, room.Id)
	// if result.Code != 200 {
	// 	log.Printf("通知语聊房结束游戏失败")
	// }
	for key, _ := range room.Players {
		//value.Status2 = uint32(PlayerIdle)
		room.Players[key].Status = 13
		room.Players[key].FinishNum = 0
		room.Players[key].Num = 0
		room.Players[key].Kick = 0
		room.Players[key].BeKick = 0
		// if room.Mode == 2 {
		room.Players[key].GameRoomId = room.Id
		if room.Mode == ModeMatch {
			room.Players[key].GameRoom = nil

		}

		// }

		var rounds = []*GameNumberOfRounds{}
		var num *GameNumberOfRounds = new(GameNumberOfRounds)
		var nums = []*uint32{}
		(*num).Num = 0
		(*num).NumberOfRounds = nums
		rounds = append(rounds, num)
		room.Players[key].NumberOfRounds = rounds
		//gamePlayers[gamePlayer.Uid] = &gamePlayer
	}
	for i := 0; i < len(room.GzPlayers); i++ {
		room.GzPlayers[i].GameRoomId = room.Id
		room.GzPlayers[i].GameRoom = nil
		room.GzPlayers[i].Status = uint32(0)
	}
	if room.Mode == ModeClass {
		var rankPlayer = map[int]*GamePlayer{}
		var gzPlayer = []*GamePlayer{}
		
		//var player = map[int]*GamePlayer{}
		//var roomplayer = map[string]*GamePlayer{}
		var uid2 = strconv.Itoa(room.Homeowner)
		//退出房主
		for key, v := range room.Players {
			if GamePlayers[v.Uid] != nil {
				GamePlayers[v.Uid].Status = 0
			}
			if v.Uid != uid2 {
				//除了房主外都会被踢出房间
				log.Info("踢出玩家", v.Uid)
				room.Players[key].GameRoom = nil
				delete(room.Players, key)
				

			}

		}
		
		room.RankPlayers = rankPlayer
		room.GzPlayers = gzPlayer
		//room.Players = player
		room.PlayerNum = 0
		//room.RoomPlayers = roomplayer
		room.RunnerNum = 0
		room.ArrivalNum = 0
		room.GameEnd = GameNotStarted
		Engine.ID(room.Id).Update(room)
	} else if room.Mode == ModeMatch {
		for _, v := range room.Players {

				if GamePlayers[v.Uid] != nil {
					GamePlayers[v.Uid].Status = 0
				}
		}
		room.Status = RoomIdle
		var rankPlayer = map[int]*GamePlayer{}
		var gzPlayer = []*GamePlayer{}
		var player = map[int]*GamePlayer{}
		var roomplayer = map[string]*GamePlayer{}
		room.RankPlayers = rankPlayer
		room.GzPlayers = gzPlayer
		room.Players = player
		room.PlayerNum = 0
		room.RunnerNum = 0
		room.ArrivalNum = 0
		room.RoomPlayers = roomplayer
		room.GameEnd = GameNotStarted
		Engine.ID(room.Id).Update(room)
	}
}

 func ClearSocket() {

 	log.Printf("开启定时清理心跳")
	ticker2 := time.NewTicker(time.Second * 30)
 	defer ticker2.Stop()

 	for {
		select {
			case <-ticker2.C:
 				for key, value := range UserClientIds {
 					player := getPlayer(key)
 					if player != nil {
						
 						seconds := time.Since(player.LastHeartbeat).Seconds() // 返回time1与当前时间的秒级差值
						
 						log.Info("second", seconds)
 						if seconds > 20 {
							log.Println("player.LastHeartbeat",player.LastHeartbeat)
							log.Println("timenow",time.Now())
							//清除该用户数据
							log.Printf("清楚用户数据",player.Uid)
							
							QuitRoom(player, value, 0)
							delete(GamePlayers, player.Uid)
							if UserClientIds[player.Uid]!=nil{
								delete(ClientUserIds, UserClientIds[player.Uid])
								delete(UserClientIds, player.Uid)
							}
							
							
						

					
 							}
 						}

 				}

 		}
 	}

 }
func Initmap2() {
	var maps0 = []int{}
	for i := 1; i <= 57; i++ {
		maps0 = append(maps0, i)
	}
	Maps[0] = maps0
	maps1 := initmap(14, 51, 1, 12, 58, 63)
	Maps[1] = maps1
	maps2 := initmap(27, 51, 1, 25, 64, 69)
	Maps[2] = maps2
	maps3 := initmap(40, 51, 1, 38, 70, 75)
	Maps[3] = maps3
}

func initmap(i1start int, i1end int, i2start int, i2end int, i3start int, i3end int) []int {
	//var maps1 = []GameMap{}
	var maps1 = []int{}
	//seat1的行走路线
	for i := i1start; i <= i1end; i++ {
		maps1 = append(maps1, i)
	}
	maps1 = append(maps1, 76)
	for i := i2start; i <= i2end; i++ {
		maps1 = append(maps1, i)
	}
	for i := i3start; i <= i3end; i++ {
		maps1 = append(maps1, i)
	}
	return maps1
}

type Page struct {
	Records []GameRoomVo `json:"records"`
	Total   int          `json:"total"`
}
type gameRoomes []GameRoom

func (rooms gameRoomes) Len() int {
	return len(rooms)
}

func (s gameRoomes) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}
func (s gameRoomes) Less(i, j int) bool {
	return s[i].Id < s[j].Id
}

func GetRoomPage(c *gin.Context) SqlResponse {
	
	page := c.Query("page")
	pageSize := c.Query("pageSize")
	fmt.Printf("page",page)
	fmt.Print("pageSize",pageSize)
	page3, err := strconv.Atoi(page)
	log.Println(err)
	pageSize3, _ := strconv.Atoi(pageSize)
	keys := []GameRoom{}

	for _, value := range gameRooms {
		if value.Status == RoomBusy && value.Mode == ModeClass {
			log.Info("房间正在使用中")
			keys = append(keys, *value)
		}
		//log.Print("data", v)

	}

	sort.Sort(gameRoomes(keys))
	start, end := SlicePage(int64(page3), int64(pageSize3), int64(len(keys))) //第一页1页显示3条数据
	afterLimitData := keys[start:end]                                         //分页后的数据
	//fmt.Println("分页后的数据:", afterLimitData[0])
	fmt.Println("数据总量:", len(keys))
	var page2 Page
	page2.Total = len(keys)
	var gameroomms = []GameRoomVo{}
	for i := 0; i < len(afterLimitData); i++ {
		//afterLimitData[i].ticker=nil
		var gameroomVo = GameRoomVo{}
		gameroomVo.Id = afterLimitData[i].Id
		gameroomVo.PlayerNum = afterLimitData[i].PlayerNum + len(afterLimitData[i].GzPlayers)
		gameroomVo.Status = afterLimitData[i].GameEnd
		gameroomVo.Logo = "https://vr-1314677574.cos.ap-nanjing.myqcloud.com/icon.png"
		gameroomms = append(gameroomms, gameroomVo)
	}

	page2.Records = gameroomms
	var sqlResponse SqlResponse = SqlResponse{
		Code:    200,
		Message: "成功",
		Data:    page2,
	}

	//c.JSON(http.StatusOK, sqlResponse)
	return sqlResponse
	//return maps1
}
func GetRoomPage3(page string,pageSize string) SqlResponse {

	var gameRooms2 =map[int]*GameRoom{}

	gameRooms2[1]=&GameRoom{Status: 2,Mode: 1}
	//page := c.Query("page")
	//pageSize := c.Query("pageSize")
	page3, err := strconv.Atoi(page)
	log.Println(err)
	pageSize3, _ := strconv.Atoi(pageSize)
	keys := []GameRoom{}

	for _, value := range gameRooms2 {
		if value.Status == RoomBusy && value.Mode == ModeClass {
			log.Info("房间正在使用中")
			keys = append(keys, *value)
		}
		//log.Print("data", v)

	}

	sort.Sort(gameRoomes(keys))
	start, end := SlicePage(int64(page3), int64(pageSize3), int64(len(keys))) //第一页1页显示3条数据
	afterLimitData := keys[start:end]                                         //分页后的数据
	//fmt.Println("分页后的数据:", afterLimitData[0])
	
	var page2 Page
	page2.Total = len(keys)
	var gameroomms = []GameRoomVo{}
	for i := 0; i < len(afterLimitData); i++ {
		//afterLimitData[i].ticker=nil
		var gameroomVo = GameRoomVo{}
		gameroomVo.Id = afterLimitData[i].Id
		gameroomVo.PlayerNum = afterLimitData[i].PlayerNum + len(afterLimitData[i].GzPlayers)
		gameroomVo.Status = afterLimitData[i].GameEnd
		gameroomVo.Logo = "https://vr-1314677574.cos.ap-nanjing.myqcloud.com/icon.png"
		gameroomms = append(gameroomms, gameroomVo)
	}

	page2.Records = gameroomms
	var sqlResponse SqlResponse = SqlResponse{
		Code:    200,
		Message: "成功",
		Data:    page2,
	}
	fmt.Println("数据总量:", len(keys),sqlResponse)
	//c.JSON(http.StatusOK, sqlResponse)
	return sqlResponse
	//return maps1
}

func GetRoomPage2(c *gin.Context) SqlResponse {
	page2 := c.Query("page")
	pageSize := c.Query("pageSize")
	page3, err := strconv.Atoi(page2)
	log.Println(err)
	pageSize3, _ := strconv.Atoi(pageSize)
	log.Println(err)

	var tenusers []GameRoom
	//i=要取的条数， j=开始的位置
	Engine.Limit(pageSize3, (page3-1)*pageSize3).Find(&tenusers) //Find only id and name
	firmware := new(GameRoom)
	total, err := Engine.Count(firmware)
	 var page Page
	 page.Total = int(total)
	 var gameroomms = []GameRoomVo{}
	for i := 0; i < len(tenusers); i++ {
		//afterLimitData[i].ticker=nil
		var gameroomVo = GameRoomVo{}
		gameroomVo.Id = tenusers[i].Id
		gameroomVo.PlayerNum = tenusers[i].PlayerNum + len(tenusers[i].GzPlayers)
		gameroomVo.Status = tenusers[i].GameEnd
		gameroomVo.Logo = "https://vr-1314677574.cos.ap-nanjing.myqcloud.com/icon.png"
		
		gameroomms = append(gameroomms, gameroomVo)
	}
	 page.Records = gameroomms
	// page.Records = tenusers
	var sql = SqlResponse{
		Code:    200,
		Message: "成功",
		Data:    page,
	}
	//c.JSON(http.StatusOK, sqlResponse)
	return sql
	//return maps1
}
func SlicePage(page, pageSize, nums int64) (sliceStart, sliceEnd int64) {
	if page <= 0 {
		page = 1
	}
	if pageSize < 0 {
		pageSize = 20 //设置一页默认显示的记录数
	}
	if pageSize > nums {
		return 0, nums
	}
	// 总页数
	pageCount := int64(math.Ceil(float64(nums) / float64(pageSize)))
	if page > pageCount {
		return 0, 0
	}
	sliceStart = (page - 1) * pageSize
	sliceEnd = sliceStart + pageSize

	if sliceEnd > nums {
		sliceEnd = nums
	}
	return sliceStart, sliceEnd
}
func InitRoomDb() () {
	var rooms []GameRoom
	Engine.Where(builder.Eq{"status":2}).Find(&rooms)
   for _,value := range rooms  {
	value.Status=1
	//   i.Status=1
   }
   Engine.Update(rooms)
}
