package api

import (
	"gadmin/config"
	"gadmin/internal/admin/forms"
	"gadmin/internal/admin/service"
	"gadmin/internal/gorm/query"
	"gadmin/utility/serializer"
	"gadmin/utility/token"
	"github.com/gin-gonic/gin"
)

func UserLogin(c *gin.Context) {
	ip := c.ClientIP()
	var req forms.UserLoginReq
	if err := c.ShouldBind(&req); err == nil {
		res := service.User.Login(req, ip)
		c.JSON(200, res)
	} else {
		c.JSON(200, ErrorResponse(err))
	}
}

func UserMe(c *gin.Context) {
	var (
		user = token.CurrentUser(c)
	)
	permissions := make([]forms.UserLoginPermissions, 0)
	permissions = append(permissions, forms.UserLoginPermissions{
		Label: "控制台",
		Value: "value",
	})
	//获取用户角色权限
	roleInfo, err := service.AdminRole.GetRole(c, forms.AdminRoleReq{ID: user.RoleId})
	if err != nil || roleInfo == nil {
		c.JSON(200, ErrorResponse(err))
		return
	}
	if roleInfo.Key == "super" {
		for k, _ := range config.AuthMenuMap {
			permissions = append(permissions, forms.UserLoginPermissions{
				Label: config.AuthNameMap[k],
				Value: config.AuthMenuMap[k],
			})
		}
	} else {
		rpdb := query.Use(config.AdminDB).AdminRolePermission
		rolePermission := make([]int, 0)
		err = rpdb.Where(rpdb.SystemID.Eq(user.SystemId)).Pluck(rpdb.PermissionID, &rolePermission)
		//err = json.Unmarshal([]byte(roleInfo.Permissions), &rolePermission)
		if err != nil {
			c.JSON(200, ErrorResponse(err))
			return
		}
		for _, v := range rolePermission {
			if _, ok := config.AuthMenuMap[v]; ok {
				permissions = append(permissions, forms.UserLoginPermissions{
					Label: config.AuthNameMap[v],
					Value: config.AuthMenuMap[v],
				})
			}
		}
	}

	//将权限赋值给permission

	info := forms.UserMeReq{
		ID:          user.ID,
		UserName:    user.UserName,
		RoleId:      user.RoleId,
		Avatar:      user.Avatar,
		Nickname:    user.Nickname,
		Permissions: permissions,
		IsSuper:     user.UserName == "admin",
	}

	c.JSON(200, serializer.Suc(info, "获取成功"))
}

func AdminUserList(c *gin.Context) {
	var req forms.AdminUserListReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}
	if err := forms.ParseParams(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	c.JSON(200, service.User.List(c, req))
}

func AdminUserEdit(c *gin.Context) {
	var req forms.AdminUserEditReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}
	if err := forms.ParseParams(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	c.JSON(200, service.User.Edit(c, req))
}

func RolePermission(c *gin.Context) {
	is, err := service.User.GetUserRolePermission(c)
	if err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}
	c.JSON(200, serializer.Suc(is, "获取成功"))
}
