package router

import (
	"ARKItems/configs"
	"ARKItems/entity/ark"
	"ARKItems/util"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
)

var ARKConfig ark.Config

// ARKShopItems 商城物品列表
var ARKShopItems map[string]ark.ShopItem
var ARKShopDines map[string]ark.ShopDino
var ARKShopBeacons map[string]ark.ShopBeacon
var ARKShopExperiences map[string]ark.ShopExperience
var ARKShopUnlockengram map[string]ark.ShopUnlockengram
var ARKShopCommands map[string]ark.ShopCommand

func init() {
	//加载配置文件
	ARKConfig, ARKShopItems, ARKShopDines, ARKShopBeacons, ARKShopExperiences, ARKShopUnlockengram, ARKShopCommands =
		util.LoadArkShopConfig(configs.ARKJsonFilePath)
}

func LoadRouter(router *gin.Engine) {
	router.POST("/login", Login)
	router.GET("/replay", Replay)
	router.Use(Calibration())
	group := router.Group("/ark")
	ARKConfigRouter(group)
	ArkItemRouter(group)
	ARKFileRouter(group)
}

func Replay(c *gin.Context) {
	configs.LoadServerConfiguration()
	//加载配置文件
	ARKConfig, ARKShopItems, ARKShopDines, ARKShopBeacons, ARKShopExperiences, ARKShopUnlockengram, ARKShopCommands =
		util.LoadArkShopConfig(configs.ARKJsonFilePath)
}

// Calibration 登录校验
func Calibration() gin.HandlerFunc {
	return func(c *gin.Context) {
		header := c.GetHeader("auth-sign")
		if header == "" {
			c.JSON(200, CreateResultError(565, "用户未登录"))
			c.Abort()
		}
		token, err := util.ParseToken(header)
		if err != nil {
			c.JSON(200, CreateResultError(565, "token解析失败"))
			c.Abort()
			return
		}

		if !util.JudgmentUserInfo(token) {
			c.JSON(200, CreateResultError(565, "token过期，或无效"))
			c.Abort()
			return
		}
	}
}

func Login(c *gin.Context) {
	param := util.GetJsonAnyParam(c)
	username, _ := param("username")
	password, _ := param("password")
	if username == configs.Manager.Username && password == configs.Manager.Password {
		token, err := util.GenerateToken(cast.ToString(username))
		if err != nil {
			c.JSON(200, CreateResultError(500, "token生成失败"))
			return
		}
		c.JSON(200, CreateResultData(gin.H{
			"token": token,
		}))
		return
	}
	c.JSON(200, CreateResultError(500, "用户名或密码错误"))
}

//===============================================================

func CreateResult() gin.H {
	return gin.H{
		"code": 200,
		"msg":  "success",
	}
}
func CreateResultData(Data any) gin.H {
	return gin.H{
		"code": 200,
		"msg":  "success",
		"data": Data,
	}
}

func CreateResultError(errCode int, errMsg string) gin.H {
	return gin.H{
		"code": errCode,
		"msg":  errMsg,
	}
}
