package api

import (
	"fmt"
	"gadmin/config"
	"gadmin/internal/admin/forms"
	"gadmin/internal/admin/service"
	"gadmin/utility/serializer"
	"gadmin/utility/token"
	"github.com/gin-gonic/gin"
	jsoniter "github.com/json-iterator/go"
)

// ServiceList 获取系统列表
func ServiceList(c *gin.Context) {
	services, err := service.Service.ServiceList(c)
	if err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}
	c.JSON(200, serializer.Suc(services, "获取成功"))
}

// ServiceSelect 选择系统
func ServiceSelect(c *gin.Context) {
	req := new(forms.ServiceSelectReq)
	if err := c.ShouldBind(req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	if res, ok := c.Get("user"); !ok {
		c.JSON(200, ErrorResponse(fmt.Errorf("获取用户信息失败")))
		return
	} else {
		user := res.(*token.UserClaims)
		user.SystemId = req.SystemId
		userStr, err := jsoniter.MarshalToString(user)
		if err != nil {
			c.JSON(200, ErrorResponse(err))
			return
		}

		config.TokenRedis.Set(config.GetTokenKey(user.AccessToken), userStr, config.TokenExpireTime)
		c.JSON(200, serializer.Suc("ok"))
	}

	//if t, err := token.SetSystemId(c, req.SystemId); err != nil {
	//	fmt.Println(err)
	//	c.JSON(400, ErrorResponse(err))
	//	return
	//} else {
	//	c.JSON(200, serializer.Suc(map[string]string{"token": t}))
	//}
}
