package api

import (
	"bytes"
	"encoding/json"
	"fmt"
	"gadmin/config"
	"gadmin/internal/admin/consts"
	"gadmin/internal/admin/data"
	"gadmin/internal/admin/forms"
	"gadmin/internal/admin/gm_services"
	"gadmin/internal/admin/service"
	"gadmin/internal/gorm/model"
	"gadmin/internal/gorm/query"
	"gadmin/package/gmdata"
	"gadmin/package/platformPay"
	"gadmin/utility"
	"gadmin/utility/player"
	"gadmin/utility/serializer"
	"gadmin/utility/token"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/jinzhu/now"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cast"
)

func GetServerDate(c *gin.Context) {
	c.JSON(200, serializer.Suc(map[string]interface{}{
		"date": time.Now().Format("2006-01-02 15:04:05"),
	}))
	return
}

func GetVersionIndex(c *gin.Context) {
	var (
		req forms.GetVersionIndexReq
		err error
	)

	if err = c.ShouldBind(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	type response struct {
		Error string `json:"error"`
		Data  any    `json:"data"`
		Msg   string `json:"msg"`
	}

	logrus.Warnf("GetVersionIndex req:%+v", req)

	params := url.Values{}
	params.Set("v", req.Version)

	resp, err := http.Get(fmt.Sprintf("%s/%s?%s", os.Getenv("VERSION_URL"), "version/index", params.Encode()))
	if err != nil {
		c.JSON(200, gin.H{"code": 1, "msg": fmt.Sprintf("获取版本号列表失败，请联系技术处理. err:%v", err.Error())})
		return
	}
	defer resp.Body.Close()

	var result response
	if err = json.NewDecoder(resp.Body).Decode(&result); err != nil {
		c.JSON(200, gin.H{"code": 1, "msg": fmt.Sprintf("获取版本号列表失败，请联系技术处理. err:%v", err.Error())})
		return
	}

	if result.Error != "" {
		c.JSON(200, gin.H{"code": 1, "msg": fmt.Sprintf("获取版本号列表失败，请联系技术处理. err:%v", result.Error)})
		return
	}

	// res, err := sshx.GetVersionIndex(req)
	// if err != nil || res == nil {
	// 	c.JSON(200, gin.H{"code": 1, "msg": fmt.Sprintf("获取版本服务器异常. err:%v", err.Error())})
	// 	return
	// }

	// if res.Code != 0 {
	// 	c.JSON(200, gin.H{"code": 1, "msg": fmt.Sprintf("获取版本服务器异常-2. err:%v", res.Err)})
	// 	return
	// }

	c.JSON(200, serializer.Suc(map[string]interface{}{
		"index": result.Data,
	}))
}

func VersionList(c *gin.Context) {

	resp, err := http.Get(fmt.Sprintf("%s/%s", os.Getenv("VERSION_URL"), "version/scan"))
	if err != nil {
		c.JSON(200, gin.H{"code": 1, "msg": fmt.Sprintf("获取版本号列表失败，请联系技术处理. err:%v", err.Error())})
		return
	}
	defer resp.Body.Close()

	type opt struct {
		Value string `json:"value"`
		Label string `json:"label"`
	}

	type response struct {
		Error string `json:"error"`
		Data  any    `json:"data"`
		Msg   string `json:"msg"`
	}
	var opts []*opt
	var result response
	if err = json.NewDecoder(resp.Body).Decode(&result); err != nil {
		c.JSON(200, gin.H{"code": 1, "msg": fmt.Sprintf("获取版本号列表失败，请联系技术处理. err:%v", err.Error())})
		return
	}

	if result.Error != "" {
		c.JSON(200, gin.H{"code": 1, "msg": fmt.Sprintf("获取版本号列表失败，请联系技术处理. err:%v", result.Error)})
		return
	}

	for _, val := range result.Data.([]interface{}) {
		d, _ := val.(string)
		opts = append(opts, &opt{Value: d, Label: d})
	}
	c.JSON(200, serializer.Suc(map[string]interface{}{
		"versionOptions": opts,
	}))

	// ds, err := sshx.VersionList()
	// if err != nil {
	// 	c.JSON(200, gin.H{"code": 1, "msg": fmt.Sprintf("获取版本号列表失败，请联系技术处理. err:%v", err.Error())})
	// 	return
	// }

	// type opt struct {
	// 	Value string `json:"value"`
	// 	Label string `json:"label"`
	// }

	// var opts []*opt
	// for _, d := range ds {
	// 	opts = append(opts, &opt{Value: d, Label: d})
	// }
	// c.JSON(200, serializer.Suc(map[string]interface{}{
	// 	"versionOptions": opts,
	// }))
}

func ReleaseVersion(c *gin.Context) {
	var (
		req forms.ReleaseVersionReq
		err error
	)

	if err = c.ShouldBind(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	reqBytes, err := json.Marshal(req)
	if err != nil {
		c.JSON(200, gin.H{"code": 1, "msg": fmt.Sprintf("更新过程发生错误，请联系技术处理. err:%v", err.Error())})
		return
	}

	resp, err := http.Post(fmt.Sprintf("%s/%s", os.Getenv("VERSION_URL"), "version/update"), "application/json", bytes.NewBuffer(reqBytes))
	if err != nil {
		c.JSON(200, gin.H{"code": 1, "msg": fmt.Sprintf("更新过程发生错误，请联系技术处理. err:%v", err.Error())})
		return
	}
	defer resp.Body.Close()

	type response struct {
		Error string `json:"error"`
		Data  any    `json:"data"`
		Msg   string `json:"msg"`
	}

	var result response
	if err = json.NewDecoder(resp.Body).Decode(&result); err != nil {
		c.JSON(200, gin.H{"code": 1, "msg": fmt.Sprintf("更新过程发生错误，请联系技术处理. err:%v", err.Error())})
		return
	}

	c.JSON(200, serializer.Suc(nil))
}

func EditServerDate(c *gin.Context) {
	var (
		req forms.EditServerDateReq
		err error
	)

	if os.Getenv("GIN_MODE") == "release" {
		c.JSON(200, gin.H{"code": 1, "msg": "正式服不允许操作！"})
		return
	}

	if err = c.ShouldBind(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	t, _ := time.Parse("2006-01-02 15:04:05", req.Date)
	command := fmt.Sprintf(`date -s "%v"`, t.Format("20060102 15:04:05"))

	user := token.CurrentUser(c)
	logrus.Infof("用户 [%v] 于 [%v] 修改服务器时间为 [%v]", user.ID, time.Now().Format("2006-01-02 15:04:05"), t.Format("2006-01-02 15:04:05"))

	o, err := exec.Command("/bin/bash", "-c", command).Output()
	if err != nil {
		c.JSON(200, gin.H{"code": 1, "msg": fmt.Sprintf("命令执行失败:%+v", err.Error())})
		return
	}

	logrus.Warnf("EditServerDate o:%+v", string(o))
	c.JSON(200, serializer.Suc(nil))
	return
}

func MsdBalance(c *gin.Context) {
	var (
		req forms.MsdBalanceReq
		err error
	)

	if err = c.ShouldBind(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	if err = forms.ParseParams(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	user := data.GetUser(req.UserID)
	if user == nil {
		logrus.Warnf("未找到玩家 req.UserID:%v", req.UserID)
		c.JSON(200, gin.H{"code": 1, "msg": "未找到玩家"})
		return
	}

	if user.OpenID == "" {
		c.JSON(200, gin.H{"code": 1, "msg": "玩家未设置openid"})
		return
	}
	//定位平台
	openid := user.OpenID

	platform := platformPay.GetAdminPlatform()
	balance, err := platformPay.QueryBalanceAndCheck(int(platform), openid)
	if err != nil {
		c.JSON(200, gin.H{"code": 1, "msg": err.Error()})
		return
	}

	if balance == nil {
		c.JSON(200, gin.H{"code": 1, "msg": "查询余额失败！"})
		return
	}

	c.JSON(200, serializer.Suc(map[string]interface{}{
		"userId":  user.ID,
		"openid":  openid,
		"balance": balance.Balance,
	}))
}

func MsdSettle(c *gin.Context) {
	var (
		req forms.MsdSettleReq
		err error
	)

	if os.Getenv("GIN_MODE") != "release" {
		c.JSON(200, gin.H{"code": 1, "msg": "测试服不允许操作！"})
		return
	}

	if err = c.ShouldBind(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	if err = forms.ParseParams(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	user := data.GetUser(req.UserID)
	if user == nil {
		logrus.Warnf("未找到玩家 req.UserID:%v", req.UserID)
		c.JSON(200, gin.H{"code": 1, "msg": "未找到玩家"})
		return
	}

	if user.OpenID == "" {
		c.JSON(200, gin.H{"code": 1, "msg": "玩家未设置openid"})
		return
	}

	openid := user.OpenID
	platform := platformPay.GetAdminPlatform()
	balance, err := platformPay.QueryBalanceAndCheck(platform, openid)
	if err != nil {
		c.JSON(200, gin.H{"code": 1, "msg": err.Error()})
		return
	}

	if balance == nil {
		c.JSON(200, gin.H{"code": 1, "msg": "查询余额失败！"})
		return
	}

	if balance.Balance < req.Balance {
		c.JSON(200, gin.H{"code": 1, "msg": "平账余额不能大于米大师余额"})
		return
	}

	if req.Remark == "" {
		c.JSON(200, gin.H{"code": 1, "msg": "平账理由不能为空"})
		return
	}

	var response *platformPay.ResponsePay
	orderSn := platformPay.CreateOutTradeNo(user.ID)
	defer func() {
		var (
			status    int32 = 1
			errorTxt        = ""
			responseB []byte
		)
		if err != nil {
			status = 2
			errorTxt = err.Error()
		}

		if response != nil {
			responseB, _ = json.Marshal(response)
		}
		var settle = query.Use(config.DB).OrdersSettle
		settleData := model.OrdersSettle{
			Type:      1,
			UserID:    req.UserID,
			Openid:    openid,
			Balance:   int32(req.Balance),
			Remark:    req.Remark,
			OrderSn:   orderSn,
			CreatedBy: token.GetUID(c),
			Status:    status,
			Error:     errorTxt,
			Response:  string(responseB),
			CreatedAt: time.Now(),
		}

		if err = settle.Create(&settleData); err != nil {
			logrus.Errorf("OrdersSettle Create err :%+v, settleData:%+v", err, settleData)
		}
	}()
	logrus.Infof("平帐参数 platform:%d, openId:%s, orderSn:%s, balance:%d", platform, openid, orderSn, req.Balance)
	response, err = platformPay.PayAndCheck(platform, openid, orderSn, req.Balance)
	if err != nil {
		c.JSON(200, gin.H{"code": 1, "msg": err.Error()})
		return
	}

	if response == nil {
		c.JSON(200, gin.H{"code": 1, "msg": "米大师返回异常,请登录米大师平台确认是否操作成功！ "})
		return
	}

	c.JSON(200, serializer.Suc(nil))
}

func GetBalance(c *gin.Context) {
	var (
		req forms.GetBalanceReq
		err error
	)

	if err = c.ShouldBind(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	if err = forms.ParseParams(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	user := data.GetUser(req.UserID)
	if user == nil {
		logrus.Warnf("未找到玩家 req.UserID:%v", req.UserID)
		c.JSON(200, gin.H{"code": 1, "msg": "未找到玩家"})
		return
	}

	if user.OpenID == "" {
		c.JSON(200, gin.H{"code": 1, "msg": "玩家未设置openid"})
		return
	}

	openid := user.OpenID
	//获取后端平台
	plat := platformPay.WxPlat
	if os.Getenv("ADMIN_PLATFORM") == "dy" {
		plat = platformPay.DyPlat
	}
	balance, err := platformPay.QueryBalanceAndCheck(int(plat), openid)
	if err != nil {
		c.JSON(200, gin.H{"code": 1, "msg": err.Error()})
		return
	}

	if balance == nil {
		c.JSON(200, gin.H{"code": 1, "msg": "查询余额失败！"})
		return
	}

	c.JSON(200, serializer.Suc(map[string]interface{}{
		"userId":  user.ID,
		"openid":  openid,
		"balance": balance.Balance,
	}))
}

/*func DelRank(c *gin.Context) {
	var (
		req forms.DelRankReq
		err error
	)

	if err = c.ShouldBind(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	if err = forms.ParseParams(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	c.JSON(200, service.Gm.DelRank(c, req))
}*/

func GetUserRolesInfo(ctx *gin.Context) {

	type Result struct {
		RoleNums int `json:"role_nums"`
		Count    int `json:"count"`
	}

	endStamp := cast.ToInt64(ctx.Query("emdstamp"))
	if endStamp <= 0 {
		endStamp = now.With(time.Now().AddDate(0, 0, -1)).EndOfDay().Unix()
	}

	key := config.UKey("GetUserRolesInfo", endStamp)
	if foo, found := config.Cache.Get(key); found {
		ctx.JSON(200, gin.H{"code": 200, "data": foo})
		return
	}

	tx := config.GDB1.Raw(fmt.Sprintf("select b.role_nums, count(1) as count from (SELECT ua.id, floor(length(pm.roles)/30) as role_nums FROM grave.user_account ua left join grave.player_material pm on ua.id = pm.playerid where ua.createtime <= %d and pm.roles is not null) b group by b.role_nums", endStamp))
	var result []Result
	err := tx.Scan(&result).Error
	if err != nil {
		ctx.JSON(200, gin.H{"code": 500, "msg": err.Error()})
	} else {
		ctx.JSON(200, gin.H{"code": 200, "data": result})
		config.Cache.Set(key, result, time.Hour*3)
	}

}

func GetIdiomRankingList(ctx *gin.Context) {
	var params forms.GetIdiomRankingListReq
	ctx.ShouldBind(&params)

	if params.ServerId <= 0 {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: "请选择一个有效的服务器"})
		return
	}

	DB, err := player.GetDBByServerID(params.ServerId)
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	type Models struct {
		ID         int64   `json:"id"`
		UserID     int64   `json:"user_id"`
		Score      float64 `json:"score"`
		NickName   string  `json:"nickName"`
		Createtime int64   `json:"createtime"`
	}

	var (
		models []Models
		res    forms.ListRes
		key    = fmt.Sprintf("idiom_ranking:%v", utility.WeekIndexDate())
	)

	list, err := config.RedisGroup[DB].ZRevRangeWithScores(key, 0, 99).Result()
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	for i := 0; i < len(list); i++ {
		user := data.GetUser(cast.ToInt64(list[i].Member))
		NickName := ""
		var Createtime int64 = 0
		if user != nil {
			NickName = user.NickName
			Createtime = user.CreateTime.Unix()
		}

		models = append(models, Models{
			ID:         int64(i + 1),
			UserID:     cast.ToInt64(list[i].Member),
			Score:      cast.ToFloat64(list[i].Score) / 10000000,
			NickName:   NickName,
			Createtime: Createtime,
		})
	}

	res.List = models
	res.Page = 1
	res.PerPage = 100
	res.PageCount = 1

	ctx.JSON(200, serializer.Suc(res))
}

func GetBossRankingList(ctx *gin.Context) {
	var params forms.GetBossRankingListReq
	ctx.ShouldBind(&params)

	if params.ServerId <= 0 {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: "请选择一个有效的服务器"})
		return
	}

	DB, err := player.GetDBByServerID(params.ServerId)
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	type Models struct {
		ID         int64   `json:"id"`
		UserID     int64   `json:"user_id"`
		Score      float64 `json:"score"`
		NickName   string  `json:"nickName"`
		Createtime int64   `json:"createtime"`
	}

	var (
		models []Models
		res    forms.ListRes
		key    = fmt.Sprintf("bossranking:%v", time.Now().Format("20060102"))
	)

	list, err := config.RedisGroup[DB].ZRevRangeWithScores(key, 0, 99).Result()
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	for i := 0; i < len(list); i++ {
		user := data.GetUser(cast.ToInt64(list[i].Member))
		NickName := ""
		var Createtime int64 = 0
		if user != nil {
			NickName = user.NickName
			Createtime = user.CreateTime.Unix()
		}

		models = append(models, Models{
			ID:         int64(i + 1),
			UserID:     cast.ToInt64(list[i].Member),
			Score:      cast.ToFloat64(list[i].Score) / 1000_0000,
			NickName:   NickName,
			Createtime: Createtime,
		})
	}

	res.List = models
	res.Page = 1
	res.PerPage = 100
	res.PageCount = 1

	ctx.JSON(200, serializer.Suc(res))
}

func GetCurioRankingList(ctx *gin.Context) {
	var params forms.GetCurioRankingListReq
	ctx.ShouldBind(&params)

	if params.ServerId <= 0 {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: "请选择一个有效的服务器"})
		return
	}

	DB, err := player.GetDBByServerID(params.ServerId)
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	type Models struct {
		ID         int64   `json:"id"`
		UserID     int64   `json:"user_id"`
		Score      float64 `json:"score"`
		NickName   string  `json:"nickName"`
		Createtime int64   `json:"createtime"`
	}

	var (
		models []Models
		res    forms.ListRes
		key    = fmt.Sprintf("curio_ranking:%v", utility.WeekIndexDate())
	)

	list, err := config.RedisGroup[DB].ZRevRangeWithScores(key, 0, 99).Result()
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	for i := 0; i < len(list); i++ {
		user := data.GetUser(cast.ToInt64(list[i].Member))
		NickName := ""
		var Createtime int64 = 0
		if user != nil {
			NickName = user.NickName
			Createtime = user.CreateTime.Unix()
		}

		models = append(models, Models{
			ID:         int64(i + 1),
			UserID:     cast.ToInt64(list[i].Member),
			Score:      list[i].Score / 1000_0000, //cast.ToFloat64(list[i].Score) / (1000 * 1000 * 1000 * 1000 * 10), // 转MB
			NickName:   NickName,
			Createtime: Createtime,
		})
	}

	res.List = models
	res.Page = 1
	res.PerPage = 100
	res.PageCount = 1

	ctx.JSON(200, serializer.Suc(res))
}

func getCurrentRankingListKey() string {
	tm := time.Now()
	y, w := tm.ISOWeek()
	k := y*100 + w
	return fmt.Sprintf("ranking_pvp:%d", k)
}

func GetPVPRankingList(ctx *gin.Context) {
	var params forms.GetPVPRankingListReq
	ctx.ShouldBind(&params)

	if params.ServerId <= 0 {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: "请选择一个有效的服务器"})
		return
	}

	DB, err := player.GetDBByServerID(params.ServerId)
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	type Models struct {
		ID         int64  `json:"id"`
		UserID     int64  `json:"user_id"`
		Score      int64  `json:"score"`
		NickName   string `json:"nickName"`
		Createtime int64  `json:"createtime"`
	}

	var (
		models []Models
		res    forms.ListRes
		key    = getCurrentRankingListKey()
	)

	logrus.Warnf("GetPVPRankingList key:%+v", key)
	list, err := config.RedisGroup[DB].ZRevRangeWithScores(key, 0, 99).Result()
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	for i := 0; i < len(list); i++ {
		user := data.GetUser(cast.ToInt64(list[i].Member))
		NickName := ""
		var Createtime int64 = 0
		if user != nil {
			NickName = user.NickName
			Createtime = user.CreateTime.Unix()
		}

		models = append(models, Models{
			ID:         int64(i + 1),
			UserID:     cast.ToInt64(list[i].Member),
			Score:      cast.ToInt64(list[i].Score) / 1000000,
			NickName:   NickName,
			Createtime: Createtime,
		})
	}

	res.List = models
	res.Page = 1
	res.PerPage = 100
	res.PageCount = 1

	ctx.JSON(200, serializer.Suc(res))
}

func ClearPVPRank(ctx *gin.Context) {
	var (
		params     forms.ClearPVPRankReq
		week       = utility.WeekByDate(time.Now()) - 1
		rankKey    = fmt.Sprintf("ranking_pvp:%v", week)
		playersKey = fmt.Sprintf("pvpplayers:%v", week)
	)

	ctx.ShouldBind(&params)
	if params.UserID <= 0 {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: "玩家ID不能为空"})
		return
	}

	if params.ServerId <= 0 {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: "请选择一个有效的服务器"})
		return
	}

	DB, err := player.GetDBByServerID(params.ServerId)
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	res1, err := config.RedisGroup[DB].ZRem(rankKey, params.UserID).Result()
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	res2, err := config.RedisGroup[DB].HDel(playersKey, strconv.FormatInt(params.UserID, 10)).Result()
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	logrus.Warnf("ClearPVPRank res1:%+v, res2:%+v", res1, res2)

	ctx.JSON(200, serializer.Suc(nil))
	//ZADD ranking_pvp:2 123 666
	//ZREM ranking_pvp:2 666

	//HMSET "pvpplayers:2" "666" "{\"playerId\":1472097,\"level\":46,\"nickName\":\"ID_78LYDJ4\",\"headImg\":\"https://restianjianhu.mg.xhgame.com/grave/res/1111.jpg\",\"roles\":[100000020],\"parts\":[{\"part\":1,\"level\":1,\"step\":0,\"eId\":10504001,\"slot\":[0,0,0,0]},{\"part\":2,\"level\":1,\"step\":0,\"eId\":20104001,\"slot\":[0,0,0,0]},{\"part\":3,\"level\":1,\"step\":0,\"eId\":30104001,\"slot\":[0,0,0,0]},{\"part\":4,\"level\":1,\"step\":0,\"eId\":40104001,\"slot\":[0,0,0,0]},{\"part\":5,\"level\":1,\"step\":0,\"eId\":50104001,\"slot\":[0,0,0,0]},{\"part\":6,\"level\":1,\"step\":0,\"eId\":60104001,\"slot\":[0,0,0,0]}],\"talents\":null,\"multiWin\":0,\"score\":990,\"rank\":2,\"lastJoin\":2,\"matchCount\":3,\"battleId\":0,\"lastMatchTick\":0,\"selectRival\":0,\"rivals\":null,\"historys\":[268323713429012480,268323854869331968,268323897768673280]}"
	//HDEL pvpplayers:2 666
}

func ClearCurioRank(ctx *gin.Context) {
	var (
		params  forms.ClearCurioRankReq
		rankKey = fmt.Sprintf("curio_ranking:%v", utility.WeekIndexDate())
	)

	ctx.ShouldBind(&params)
	if params.UserID <= 0 {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: "玩家ID不能为空"})
		return
	}

	if params.ServerId <= 0 {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: "请选择一个有效的服务器"})
		return
	}

	DB, err := player.GetDBByServerID(params.ServerId)
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	res1, err := config.RedisGroup[DB].ZRem(rankKey, params.UserID).Result()
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	var q = query.Use(config.GDBGroup[DB]).Curiomake
	updates, err := q.WithContext(ctx).
		Where(q.Playerid.Eq(params.UserID)).
		Updates(map[string]interface{}{"silver": "0", "totalSilver": 0})
	if err != nil {
		return
	}

	logrus.Warnf("ClearCurioRank res1:%+v, updates:%+v", res1, updates)

	ctx.JSON(200, serializer.Suc(nil))
}

func ClearIdiomRank(ctx *gin.Context) {
	type DayScoreReward struct {
		Day      int   `json:"day"`      //yd
		DayScore int   `json:"dayScore"` //日积分
		SumScore int   `json:"sumScore"` //总积分
		Reward   []int `json:"reward"`   //领取箱子
	}

	var (
		params  forms.ClearIdiomRankReq
		rankKey = fmt.Sprintf("idiom_ranking:%v", utility.WeekIndexDate())
		score   *DayScoreReward
	)

	ctx.ShouldBind(&params)
	if params.UserID <= 0 {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: "玩家ID不能为空"})
		return
	}

	if params.ServerId <= 0 {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: "请选择一个有效的服务器"})
		return
	}

	DB, err := player.GetDBByServerID(params.ServerId)
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	var q = query.Use(config.GDBGroup[DB]).Idiommatch
	models, err := q.WithContext(ctx).Where(q.Playerid.Eq(params.UserID)).First()
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	if models == nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: "玩家金榜题名数据获取失败！"})
		return
	}

	err = json.Unmarshal([]byte(models.Score), &score)
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	// 清空积分
	score.DayScore = 0
	score.SumScore = 0
	newScore, err := json.Marshal(score)
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	updates, err := q.WithContext(ctx).
		Where(q.Playerid.Eq(params.UserID)).
		Updates(map[string]interface{}{"score": string(newScore)})
	if err != nil {
		return
	}

	res1, err := config.RedisGroup[DB].ZRem(rankKey, params.UserID).Result()
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	logrus.Warnf("ClearIdiomRank res1:%+v, updates:%+v, models:%+v", res1, updates, models)

	ctx.JSON(200, serializer.Suc(nil))
}

func ClearBossRank(ctx *gin.Context) {
	var (
		params   forms.ClearBossRankReq
		rankKey  = fmt.Sprintf("bossranking:%v", time.Now().Format("20060102"))
		joinsKey = fmt.Sprintf("bossjoins")
	)

	ctx.ShouldBind(&params)
	if params.UserID <= 0 {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: "玩家ID不能为空"})
		return
	}

	if params.ServerId <= 0 {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: "请选择一个有效的服务器"})
		return
	}

	DB, err := player.GetDBByServerID(params.ServerId)
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	res1, err := config.RedisGroup[DB].ZRem(rankKey, params.UserID).Result()
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	res2, err := config.RedisGroup[DB].HDel(joinsKey, strconv.FormatInt(params.UserID, 10)).Result()
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	logrus.Warnf("ClearBossRank res1:%+v, res2:%+v", res1, res2)

	ctx.JSON(200, serializer.Suc(nil))
	//ZADD ranking_pvp:2 123 666
	//ZREM ranking_pvp:2 666

	//HMSET "pvpplayers:2" "666" "{\"playerId\":1472097,\"level\":46,\"nickName\":\"ID_78LYDJ4\",\"headImg\":\"https://restianjianhu.mg.xhgame.com/grave/res/1111.jpg\",\"roles\":[100000020],\"parts\":[{\"part\":1,\"level\":1,\"step\":0,\"eId\":10504001,\"slot\":[0,0,0,0]},{\"part\":2,\"level\":1,\"step\":0,\"eId\":20104001,\"slot\":[0,0,0,0]},{\"part\":3,\"level\":1,\"step\":0,\"eId\":30104001,\"slot\":[0,0,0,0]},{\"part\":4,\"level\":1,\"step\":0,\"eId\":40104001,\"slot\":[0,0,0,0]},{\"part\":5,\"level\":1,\"step\":0,\"eId\":50104001,\"slot\":[0,0,0,0]},{\"part\":6,\"level\":1,\"step\":0,\"eId\":60104001,\"slot\":[0,0,0,0]}],\"talents\":null,\"multiWin\":0,\"score\":990,\"rank\":2,\"lastJoin\":2,\"matchCount\":3,\"battleId\":0,\"lastMatchTick\":0,\"selectRival\":0,\"rivals\":null,\"historys\":[268323713429012480,268323854869331968,268323897768673280]}"
	//HDEL pvpplayers:2 666
}

func UpdatePlayerElRank(ctx *gin.Context) {
	var params forms.UpdatePlayerElRankReq

	ctx.ShouldBind(&params)
	if params.PlayerId <= 0 || params.RoomCount < 0 {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: "参数不可用"})
		return
	}

	err := gm_services.UpdateElRank(ctx, params)
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}
	ctx.JSON(200, forms.Resp{})
}

func AddEquipment(ctx *gin.Context) {
	var params forms.AddMaterialReq
	ctx.ShouldBind(&params)

	err := gm_services.AddEquipment(ctx, params)
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}
	ctx.JSON(200, forms.Resp{})
}

func AddMaterial(ctx *gin.Context) {
	var params forms.AddMaterialReq
	ctx.ShouldBind(&params)

	err := gm_services.AddMaterial(ctx, params)
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}
	ctx.JSON(200, forms.Resp{})
}

func AddRune(ctx *gin.Context) {
	var params forms.AddMaterialReq
	ctx.ShouldBind(&params)

	err := gm_services.AddRune(ctx, params)
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}
	ctx.JSON(200, forms.Resp{})
}

func AddLegend(ctx *gin.Context) {
	var params forms.AddMaterialReq
	ctx.ShouldBind(&params)

	err := gm_services.AddLegend(ctx, params)
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}
	ctx.JSON(200, forms.Resp{})
}

func GetAllTalents(ctx *gin.Context) {
	ctx.JSON(200, forms.Resp{Code: 0, Data: gmdata.Talents})
}

func GetAllEquipments(ctx *gin.Context) {
	var data = make(map[int]gmdata.Equipment, len(gmdata.EquipmentDict))
	for _, v := range gmdata.EquipmentDict {
		data[int(v.LevelId)] = v
	}

	ctx.JSON(200, forms.Resp{Code: 0, Data: gin.H{"list": data}})
}

func GetAllExp(ctx *gin.Context) {
	ctx.JSON(200, forms.Resp{Code: 0, Data: gmdata.PlayLevel})
}

func GetAllMaterials(ctx *gin.Context) {
	type Material struct {
		ID   int    `json:"ItemId"`
		Type int    `json:"ItemType"`
		Name string `json:"ItemName"`
	}
	var data = make(map[string][]Material)
	for _, v := range gmdata.MaterialsDict {
		type1 := fmt.Sprintf("%d", v.Type)

		data[type1] = append(data[type1], Material{
			ID:   v.ID,
			Type: v.Type,
			Name: v.Name,
		})

	}
	ctx.JSON(200, forms.Resp{Code: 0, Data: data})
}

func GetAllRunes(ctx *gin.Context) {
	type Material struct {
		ID   int    `json:"ItemId"`
		Type int    `json:"ItemType"`
		Name string `json:"ItemName"`
	}
	var data = make(map[string][]Material)
	for _, v := range gmdata.RunesDict {
		type1 := fmt.Sprintf("%d", v.Type)

		data[type1] = append(data[type1], Material{
			ID:   v.ID,
			Type: v.Type,
			Name: v.Name,
		})

	}
	ctx.JSON(200, forms.Resp{Code: 0, Data: data})
}

func GetAllLegends(ctx *gin.Context) {
	type Material struct {
		ID   int    `json:"ItemId"`
		Type int    `json:"ItemType"`
		Name string `json:"ItemName"`
	}
	var data = make(map[string][]Material)
	for _, v := range gmdata.LegendsDict {
		type1 := fmt.Sprintf("%d", v.Type)

		data[type1] = append(data[type1], Material{
			ID:   v.ID,
			Type: v.Type,
			Name: v.Name,
		})

	}
	ctx.JSON(200, forms.Resp{Code: 0, Data: data})
}

func GetAllRoles(ctx *gin.Context) {
	ctx.JSON(200, forms.Resp{Code: 0, Data: gmdata.Roles})
}

func GetAllGoods(ctx *gin.Context) {
	ctx.JSON(200, forms.Resp{Code: 0, Data: gmdata.GoodsInfo})
}

func GetAllChapters(ctx *gin.Context) {
	ctx.JSON(200, forms.Resp{Code: 0, Data: gmdata.Chapters})
}

func MailList(ctx *gin.Context) {
	var params = forms.EmailListReq{Page: 1, PerPage: 30}
	ctx.ShouldBind(&params)
	mails, total, _ := gm_services.GetEmails(params.Page, params.PerPage)

	for _, v := range mails {
		if v.OperatorId > 0 {
			user, err := service.User.GetUser(v.OperatorId)
			if err != nil {
				logrus.Warnf("MailList GetUser err:%+v", err)
			}

			if user != nil {
				v.Sender = fmt.Sprintf("%v(%v)", user.UserName, v.OperatorId)
			}
		}
	}
	var models forms.ListRes
	models.List = mails
	models.Page = int64(params.Page)
	models.PerPage = int64(params.PerPage)

	if total <= 0 {
		total = 1
	}
	models.PageCount = int64(total / params.PerPage)
	ctx.JSON(200, serializer.Suc(models))
}

func SendMail(ctx *gin.Context) {
	var item forms.EmailItemReq
	ctx.ShouldBind(&item)

	item.OperatorId = token.GetUID(ctx)
	_, err := gm_services.AddEmails(&item)
	if err != nil {
		ctx.JSON(200, gin.H{"code": 1, "msg": err.Error()})
	} else {

		ctx.JSON(200, gin.H{"data": item, "code": 0})
	}
}

func DeleteMail(ctx *gin.Context) {
	var item forms.EmailItemReq
	ctx.ShouldBind(&item)
	err := gm_services.DeleteEmail(item.Id)
	if err != nil {
		ctx.JSON(200, gin.H{"code": 1, "msg": err.Error()})
	} else {

		ctx.JSON(200, gin.H{"data": item, "code": 0})
	}
}

func GetNoticeList(c *gin.Context) {
	var params forms.NoticeListReq
	c.ShouldBind(&params)

	resp, err := gm_services.GetNoticeList(params)

	if err != nil {
		c.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	var models forms.ListRes
	models.List = resp

	c.JSON(200, serializer.Suc(models))
}

func AddNotice(c *gin.Context) {
	var params forms.AddNoticeReq
	c.ShouldBind(&params)

	_, err := gm_services.AddNotice(params)

	if err != nil {
		c.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}
	c.JSON(200, forms.Resp{})
}

func DelNotice(c *gin.Context) {
	var params forms.DeleteNoticeReq
	c.ShouldBind(&params)

	err := gm_services.DelNotice(params.Id)

	if err != nil {
		c.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}
	c.JSON(200, forms.Resp{})
}

func UpdateSwitcher(c *gin.Context) {
	var params = forms.UpdateSwitcherReq{IosPay: -1, DoubleAd: 0}
	c.ShouldBind(&params)

	err := gm_services.UpdateSwitcher(c, params)

	if err != nil {
		c.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}
	c.JSON(200, forms.Resp{})
}

func GetConfig(ctx *gin.Context) {
	list, simple, json1 := service.ServerOption.ConfigOption(ctx)
	ctx.JSON(200, forms.Resp{Code: 0, Data: map[string]interface{}{
		"mode":                     os.Getenv("GIN_MODE"),
		"admin_template":           os.Getenv("ADMIN_TEMPLATE"),
		"socket_url":               os.Getenv("ADMIN_SOCKET_URL"),
		"json_version":             os.Getenv("JSON_VERSION"),
		"admin_web_title":          os.Getenv("ADMIN_WEB_TITLE"),
		"amount_multiple":          cast.ToInt64(os.Getenv("AMOUNT_MULTIPLE")),
		"channel_option":           service.Channel.Option(ctx),
		"channel_tree_option":      service.Channel.TreeOption(ctx),
		"server_option":            list,
		"server_simple_option":     simple,
		"server_json_option":       json1,
		"flag_option":              getUserFlagOption(),
		"deploy_type_option":       deployTypeOption(),
		"deploy_serv_group_option": deployServGroupOption(),
		"chapter_option":           gmdata.ChapterOption,
	}})
}

func deployTypeOption() (lst []forms.Option) {
	lst = append(lst, forms.Option{
		Value: nil,
		Label: "全部",
		Name:  "全部",
	})

	for _, v := range consts.DeployTypeSlice {
		lst = append(lst, forms.Option{
			Value: v,
			Label: v,
			Name:  v,
		})
	}
	return
}

func deployServGroupOption() (lst map[string][]forms.Option) {
	lst = make(map[string][]forms.Option)
	for _, v := range consts.DeployTypeSlice {
		switch v {

		case consts.DeployTypeLogin:
			lst[v] = append(lst[v], forms.Option{
				Value: "all",
				Label: "全选",
				Name:  "全选",
			})
			for _, v2 := range consts.DeployServLoginGroup {
				lst[v] = append(lst[v], forms.Option{
					Value: v2,
					Label: v2,
					Name:  v2,
				})
			}
		default: //consts.DeployTypeGrave:
			lst[v] = append(lst[v], forms.Option{
				Value: "all",
				Label: "全选",
				Name:  "全选",
			})
			for _, v2 := range consts.DeployServGraveGroup {
				lst[v] = append(lst[v], forms.Option{
					Value: v2,
					Label: v2,
					Name:  v2,
				})
			}
			// case consts.DeployTypeGate:
			// 	lst[v] = append(lst[v], forms.Option{
			// 		Value: "all",
			// 		Label: "全选",
			// 		Name:  "全选",
			// 	})
			// 	for _, v2 := range consts.DeployServGateGroup {
			// 		lst[v] = append(lst[v], forms.Option{
			// 			Value: v2,
			// 			Label: v2,
			// 			Name:  v2,
			// 		})
			// 	}
		}
	}

	return
}

func getUserFlagOption() (lst []forms.Option) {
	lst = append(lst, forms.Option{
		Value: "-1",
		Label: "全部",
		Name:  "全部",
	})
	for _, flag := range consts.UserFlags {
		lst = append(lst, forms.Option{
			Value: flag,
			Label: consts.UserFlagMap[flag],
			Name:  consts.UserFlagMap[flag],
		})
	}
	return
}

func GetJSONPath(ctx *gin.Context) {
	ctx.JSON(200, forms.Resp{Code: 0, Data: os.Getenv("JSON_PATH") + "/" + os.Getenv("JSON_VERSION")})
}

func SetNewJsonPath(ctx *gin.Context) {
	var params forms.SetConfPathReq
	ctx.ShouldBind(&params)

	err := gmdata.SetConfPath(params.Path)
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}
	ctx.JSON(200, forms.Resp{})
}

func ToolsRestartView(c *gin.Context) {
	var params = forms.ToolsRestartViewReq{}
	err := c.ShouldBind(&params)
	if err != nil {
		c.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	if params.ID < 1 {
		c.JSON(200, forms.Resp{Code: 1, Msg: "ID不能为空"})
		return
	}
	models, err := gm_services.ToolsRestartView(c, params)
	if err != nil {
		c.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}
	c.JSON(200, forms.Resp{Code: 0, Data: models})
}

func ToolsRestart(c *gin.Context) {
	var params = forms.ToolsRestartReq{}
	err := c.ShouldBind(&params)
	if err != nil {
		c.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	if params.Version == "" {
		c.JSON(200, forms.Resp{Code: 1, Msg: "版本号不能为空"})
		return
	}

	if err = gm_services.ToolsRestart(c, params); err != nil {
		c.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}
	c.JSON(200, forms.Resp{Code: 0, Msg: "Execute Command finished"})
}

func ToolsRestartLog(c *gin.Context) {
	var params = forms.ToolsRestartLogReq{}
	err := c.ShouldBind(&params)
	if err != nil {
		c.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	res, err := gm_services.ToolsRestartLogList(c, params)
	if err != nil {
		c.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	var models forms.ListRes
	models.List = res.List
	if res.TotalCount <= 0 {
		res.TotalCount = 1
	}
	models.Page = int64(params.Page)
	models.PerPage = int64(params.Limit)
	models.PageCount = res.TotalCount / 10
	c.JSON(200, serializer.Suc(models))
}

func UpdateGuides(c *gin.Context) {

	var (
		req forms.UpdateGuidesReq
		err error
	)

	if err = c.ShouldBind(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	if err = forms.ParseParams(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	c.JSON(200, service.Gm.UpdateGuides(c, req))
}

func UpdateChapter(c *gin.Context) {

	var (
		req forms.UpdateChapterReq
		err error
	)

	if err = c.ShouldBind(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	if err = forms.ParseParams(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	c.JSON(200, service.Gm.UpdateChapter(c, req))
}

/* func UpdateTalents(c *gin.Context) {
	var (
		req forms.UpdateTalentReq
		err error
	)

	if err = c.ShouldBind(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	if err = forms.ParseParams(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	c.JSON(200, service.Gm.UpdateTalent(c, req))
}

func UpdatePlayerBase(c *gin.Context) {
	var (
		req forms.UpdatePlayerBaseReq
		err error
	)

	if err = c.ShouldBind(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	if err = forms.ParseParams(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	c.JSON(200, service.Gm.UpdatePlayerBase(c, req))
}*/

////////////.....///

func AddRoleExp(ctx *gin.Context) {
	var (
		params forms.UpdateRoleReq
		err    error
	)
	if err = ctx.ShouldBind(&params); err != nil {
		ctx.JSON(200, ErrorResponse(err))
		return
	}

	if err = gm_services.UpdatePlayAttr(ctx, params); err != nil {
		ctx.JSON(200, ErrorResponse(err))
		return
	}
	ctx.JSON(200, serializer.Suc(nil))
}

func AddRoleStamina(ctx *gin.Context) {
	var params forms.UpdateRoleReq
	ctx.ShouldBindJSON(&params)

	err := gm_services.UpdatePlayAttr(ctx, params)
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}
	ctx.JSON(200, forms.Resp{})
}

func UpgradeRole(ctx *gin.Context) {
	var params forms.UpgradeRoleReq
	ctx.ShouldBind(&params)

	err := gm_services.UpgradeRole(ctx, params)
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}
	ctx.JSON(200, forms.Resp{})
}

func GetRoleLevel(ctx *gin.Context) {
	var params forms.GetRoleLevelReq
	if err := ctx.ShouldBind(&params); err != nil {
		ctx.JSON(200, ErrorResponse(err))
		return
	}
	params.RoleName = ctx.Query("role_name")
	//fmt.Println()
	levelList, err := gm_services.GetRoleLevel(ctx, params)
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}

	ctx.JSON(200, forms.Resp{
		Code: 0,
		Msg:  "",
		Data: levelList,
	})
}

func AddCoin(ctx *gin.Context) {
	var params forms.AddCoinReq
	ctx.ShouldBindJSON(&params)

	err := gm_services.AddCoin(ctx, params)
	if err != nil {
		ctx.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}
	ctx.JSON(200, forms.Resp{})
}

// 删除玩家游戏数据
func DeletePlayer(ctx *gin.Context) {
	var (
		req forms.DeleteUserPlayerReq
		err error
	)
	if err = ctx.ShouldBind(&req); err != nil {
		ctx.JSON(http.StatusOK, ErrorResponse(err))
		return
	}
	err = gm_services.DeleteUserAccount(ctx, req.UserId)
	if err != nil {
		ctx.JSON(http.StatusOK, ErrorResponse(err))
		return
	}

	ctx.JSON(http.StatusOK, forms.Resp{})
}

// 删除玩家账号
func DeleteAccount(ctx *gin.Context) {
	var (
		req forms.DeleteUserAccountReq
		err error
	)
	if err = ctx.ShouldBind(&req); err != nil {
		ctx.JSON(http.StatusOK, ErrorResponse(err))
		return
	}
	err = gm_services.DeleteAccount(ctx, req.AccId)
	if err != nil {
		ctx.JSON(http.StatusOK, ErrorResponse(err))
		return
	}

	ctx.JSON(http.StatusOK, forms.Resp{})
}

func OpenAccount(ctx *gin.Context) {
	var (
		req forms.OpenAccountReq
		err error
	)
	if err = ctx.ShouldBind(&req); err != nil {
		ctx.JSON(http.StatusOK, ErrorResponse(err))
		return
	}
	err = gm_services.OpenAccount(req.UserId)
	if err != nil {
		ctx.JSON(http.StatusOK, ErrorResponse(err))
		return
	}

	ctx.JSON(http.StatusOK, forms.Resp{})
}

func LevelProgress(c *gin.Context) {
	var params = forms.LevelProgressReq{}
	if err := c.ShouldBind(&params); err != nil {
		c.JSON(http.StatusOK, ErrorResponse(err))
		return
	}
	data, total := gm_services.QueryPlayerChapter(params.PlayerId)

	var models forms.ListRes
	models.List = data
	if total <= 0 {
		total = 1
	}
	models.PageCount = 1
	c.JSON(200, serializer.Suc(models))
}

// 游戏玩家数据报警列表
func AlarmGameDataList(c *gin.Context) {
	var req forms.AlarmGameDataListReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, ErrorResponse(err))
		return
	}
	if err := forms.ParseParams(&req); err != nil {
		c.JSON(http.StatusOK, ErrorResponse(err))
		return
	}
	result := gm_services.AlarmGameDataList(c, req)
	c.JSON(http.StatusOK, result)
}

func AlarmAttrList(c *gin.Context) {
	var req forms.AlarmAttrReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, ErrorResponse(err))
		return
	}
	if err := forms.ParseParams(&req); err != nil {
		c.JSON(http.StatusOK, ErrorResponse(err))
		return
	}
	result := gm_services.AlarmAttrList(c, req)
	c.JSON(http.StatusOK, result)
}

func AlarmCheatingList(c *gin.Context) {
	var req forms.AlarmCheatingReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, ErrorResponse(err))
		return
	}
	if err := forms.ParseParams(&req); err != nil {
		c.JSON(http.StatusOK, ErrorResponse(err))
		return
	}
	result := gm_services.AlarmCheatingList(c, req)
	c.JSON(http.StatusOK, result)
}

func AddGift(c *gin.Context) {
	var params forms.AddGiftReq
	c.ShouldBind(&params)

	err := gm_services.AddGift(c, params)
	if err != nil {
		c.JSON(200, forms.Resp{Code: 1, Msg: err.Error()})
		return
	}
	c.JSON(200, forms.Resp{})
}
