package param

import (
	"errors"
	"fengkuangGameServerJob/pkg/errcode"
	"fengkuangGameServerJob/pkg/setting"
	"fengkuangGameServerJob/pkg/util"
	"fengkuangGameServerJob/service"
	"strings"
)

var (
	playerService = service.NewPlayerService()
	platforms     = map[int]struct{}{
		0: {},
		1: {},
	}
)

// LoginParam 玩家请求登录的param
type LoginParam struct {
	AppId        string `form:"appid" uri:"appid"`
	OpenId       string `form:"openid" uri:"openid"`
	ServerId     int    `form:"server_id" uri:"server_id"`
	Platform     int    `form:"platform" uri:"platform"`                 //0开发环境 1微信包
	Version      string `form:"ver" uri:"ver"`                           //版本号
	PlatformType string `form:"userPlatformType" uri:"userPlatformType"` //放买量类型 在新用户的时候传 tx或者oe,其他情况就是undefined
}

// Validate 参数校验
func (l *LoginParam) Validate() (code int, err error) {
	l.AppId = strings.TrimSpace(l.AppId)
	l.OpenId = strings.TrimSpace(l.OpenId)
	l.Version = strings.TrimSpace(l.Version)
	//1 基本格式校验
	//1.1 基础格式校验
	_, correctPlatform := platforms[l.Platform]
	if util.IsAppId(l.AppId) == false || util.IsOpenId(l.OpenId) == false || l.ServerId < 0 || correctPlatform == false {
		return errcode.InvalidParams, errors.New("参数错误")
	}
	if l.Version == "" {
		return errcode.InvalidParams, errors.New("参数错误")
	}
	//1.2 gin是发布环境的话platform不能为0
	if setting.Settings.Server.RunMode != "debug" && l.Platform == 0 {
		return errcode.InvalidPlatform, errors.New("生产环境下platform不能为0")
	}
	//1.3 appid一定要校验(主要区分用户所属发行方及哪个游戏包)
	secret := l.GetAppSecretByAppid()
	if secret == "" {
		return errcode.InvalidAppid, errors.New("appid信息错误")
	}
	//1.4 查看当前渠道用户的状态是否被禁用
	checked := l.CheckUser()
	if checked == false {
		return errcode.LoginForbidden, errors.New("用户非正常状态,禁止登录")
	}
	//2 openid是否真实有效校验(测试环境下不进行校验)
	if setting.Settings.Server.RunMode != "debug" {
		isOpenId, err := l.ValidateOpenId(secret)
		if err != nil || isOpenId == false {
			return errcode.InvalidOpenid, err
		}
	}
	return 0, nil
}

// IsNewValidate 判断是否是新用户的基础校验
func (l *LoginParam) IsNewValidate() (code int, err error) {
	l.AppId = strings.TrimSpace(l.AppId)
	l.OpenId = strings.TrimSpace(l.OpenId)
	if util.IsAppId(l.AppId) == false || util.IsOpenId(l.OpenId) == false {
		return errcode.InvalidParams, errors.New("参数错误")
	}
	return 0, nil
}

// GetAppSecretByAppid 通过appid获取密钥
func (l *LoginParam) GetAppSecretByAppid() string {
	return playerService.GetAppSecret(l.AppId)
}

// ValidateOpenId 请求sdk接口校验openid是否正确
func (l *LoginParam) ValidateOpenId(secret string) (bool, error) {
	return playerService.CheckOpenid(l.AppId, l.OpenId, secret)
}

// CheckUser 校验玩家的状态,是否禁止登录
func (l *LoginParam) CheckUser() bool {
	user := playerService.GetChannelUser(l.OpenId)
	if user.UserId > 0 && user.UserState != 1 {
		return false
	}
	return true
}
