package v1

import (
	"context"
	"designs/app/common/request"
	"designs/app/common/response"
	"designs/common"
	"designs/config"
	"designs/global"
	"designs/utils"
	"errors"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

type GameConfig struct {
	Gid       string `form:"gid" json:"gid" binding:"required"`             //游戏id
	GameName  string `form:"gameName" json:"gameName" binding:"required"`   //游戏名称
	WxAppid   string `form:"wxAppid" json:"wxAppid" binding:"required"`     //微信appid
	WxSecret  string `form:"wxSecret" json:"wxSecret" binding:"required"`   //微信secret
	TtAppid   string `form:"ttAppid" json:"ttAppid" binding:"required"`     //抖音appid
	TtSecret  string `form:"ttSecret" json:"ttSecret" binding:"required"`   //抖音secret
	AppSecret string `form:"appSecret" json:"appSecret" binding:"required"` //游戏配置密钥
}

type GetGameCfg struct {
	AppSecret string `form:"appSecret" json:"appSecret" binding:"required"` //游戏配置密钥
}

/* code 结构体 */
type CodeData struct {
	Code string `form:"code" json:"code" binding:"required"`
	Gid  string `form:"gid" json:"gid" binding:"required"`
	Pf   string `form:"pf" json:"pf" binding:"required"`
}

/* 保存数据结构体 */
type SaveData struct {
	Extend string `form:"extend" json:"extend" binding:"required"`
	Data   string `form:"data" json:"data" binding:"required"`
	Secret string `form:"secret" json:"secret" binding:""`
}

/* 获取结构体 */
type GetSaveData struct {
	Extend string `form:"extend" json:"extend" binding:"required"`
}

/*
*登陆
 */
func Login(c *gin.Context) {
	//http://127.0.0.1:8787/v1/user/login
	// 使用 ShouldBind 方法自动绑定：
	form := request.Check(c, &struct {
		UserName string `form:"userName" json:"userName" binding:"required"`
		Password string `form:"password" json:"password" binding:"required"`
	}{})

	//验证
	adminUser := config.Get("app.admin_user")
	adminSecret := config.Get("app.admin_secret")

	if form.UserName != adminUser || form.Password != adminSecret {
		response.Fail(c, 1000, errors.New("账号密码错误"))
	}

	//获取token
	token, err := common.GetJwtToken(form.UserName, 0)
	//刷新refreshtoken
	refresh, _ := common.GetJwtToken(form.UserName, 1)
	if err != nil {
		response.Fail(c, 1003, err.Error())
		return
	}

	//回传
	response.Success(c, gin.H{
		"token":        token,
		"refreshToken": refresh,
		"loginTime":    time.Now().Unix(),
		"ip":           c.ClientIP(),
	})
}

/* 刷新token */
func RefreshToken(c *gin.Context) {
	userName := c.GetString("userName")

	//获取token
	token, err0 := common.GetJwtToken(userName, 0)
	if err0 != nil {
		global.App.Log.Info("RefreshToken err")
		response.Fail(c, 1003, "RefreshToken err")
		return
	}

	data := map[string]interface{}{
		"token": token,
	}
	//返回数据
	response.Success(c, gin.H{
		"data": data,
	})

}

/* 获取时间 */
func GetSysTime(c *gin.Context) {
	time := time.Now().Unix()
	common.RetJson(0, "获取系统时间", time, c)
}

type User struct {
	UserId   string `json:"userId"`
	Gid      string `json:"gid"`
	Pf       string `json:"pf"`
	NickName string `json:"nickName"`
	Head     string `json:"head"`
	OpenId   string `json:"openId"`
	InBlack  bool   `json:"inBlack"`
	Option   string `json:"option"`
}

func UserList(c *gin.Context) {
	form := request.Check(c, &struct {
		Offset int `form:"offset" json:"offset" binding:""`
		Limit  int `form:"limit" json:"limit" binding:"required"`
	}{})

	//读取表
	userTotalKey := config.Get("app.user_total")
	data, err := global.App.Redis.ZRevRangeWithScores(context.Background(), userTotalKey, int64(form.Offset), int64(form.Offset+form.Limit)).Result()
	if err != nil {
		response.Fail(c, 1001, err.Error())
		return
	}

	//读取黑名单
	blackListKey := config.Get("app.black_list_table")
	black, err := global.App.Redis.ZRange(context.Background(), blackListKey, 0, -1).Result()
	if err != nil {
		response.Fail(c, 1003, "读取黑名单列表失败"+err.Error())
		return
	}

	var res []User
	for _, val := range data {
		userKey := val.Member.(string)
		userData, err := global.App.Redis.HGetAll(context.Background(), userKey).Result()
		if err != nil {
			global.App.Log.Error("GetUserData err")
			response.Fail(c, 1003, "GetUserData err"+err.Error())
			return
		}

		//查看是否在黑名单
		var inBlack bool
		if utils.InArray(userKey, black) {
			inBlack = true
		}

		userMsg := strings.Split(userKey, ":")
		openId := userMsg[len(userMsg)-1]
		gid := userMsg[0]
		pf := userMsg[1]

		//查看是否加了权限
		optionKey := config.Get("app.option_key") + gid + ":" + pf + ":" + openId
		option, err := global.App.Redis.HGetAll(context.Background(), optionKey).Result()
		if err != nil {
			response.Fail(c, 1003, err.Error())
			return
		}

		res = append(res, User{
			UserId:   userData["userId"],
			Gid:      userData["gid"],
			Pf:       userData["pf"],
			NickName: userData["nickName"],
			Head:     userData["head"],
			OpenId:   openId,
			InBlack:  inBlack,
			Option:   option["option"],
		})
	}

	response.Success(c, gin.H{
		"data": res,
	})
}
