package v1

import (
	"cmdb-backend/models"
	"cmdb-backend/pkg/utils"
	"net/http"
	"sort"
	"strings"

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

func GetUserInfo(c *gin.Context) {
	session := sessions.Default(c)
	userId := session.Get("user_id")
	nameCn := session.Get("name")
	email := session.Get("email")
	role := session.Get("role")
	name := strings.Split(email.(string), "@")[0]

	// 检查当前用户是否是超级用户
	user := models.GetUserByUserName(name)
	isSuperuser := user.IsSuperuser == 1

	// 获取所有超级用户列表
	superuserNames := models.GetSuperuserList()

	data := map[string]interface{}{
		"backend": "admin",
		"user": map[string]interface{}{
			"name":         name,
			"name_cn":      nameCn,
			"email":        email,
			"role":         role,
			"user_id":      userId,
			"is_superuser": isSuperuser,
		},
		"superusers": superuserNames,
	}

	c.JSON(http.StatusOK, utils.AmisResponse{
		Data: map[string]interface{}{
			"amis": data,
		},
	})
}

func GetUserList(c *gin.Context) {
	resp := utils.SelectResponse{
		Options: []utils.SelectOption{},
	}
	options := map[string]utils.SelectOption{}

	userList := models.GetUserList()
	for _, user := range userList {
		options[user.UserName] = utils.SelectOption{
			Label: user.UserNameCn,
			Value: user.UserName,
		}
	}

	for _, option := range options {
		resp.Options = append(resp.Options, option)
	}
	sort.Sort(resp.Options)

	c.JSON(http.StatusOK, utils.AmisResponse{
		Data: resp,
	})
}

func GetSuperuserList(c *gin.Context) {
	superuserNames := models.GetSuperuserList()
	c.JSON(http.StatusOK, utils.AmisResponse{
		Data: map[string]interface{}{
			"superusers": superuserNames,
		},
	})
}
