package middleware

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

// Permission 验证权限
func Permission() gin.HandlerFunc {
	return func(c *gin.Context) {
		cUser, ok := c.Get("user")
		if !ok {
			c.JSON(200, serializer.Err(consts.CodeNoPermission, "登陆失效", nil))
			c.Abort()
			return
		}
		user := cUser.(*token.UserClaims)
		q := query.Use(config.AdminDB).AdminUser

		c.Set("admin_id", user.ID)

		models, err := q.WithContext(c).Where(q.ID.Eq(user.ID)).First()
		if err != nil {
			c.JSON(200, serializer.Err(consts.CodeNoPermission, err.Error(), err))
			c.Abort()
			return
		}

		if models == nil {
			c.JSON(200, serializer.Err(consts.CodeNoPermission, "用户不存在", nil))
			c.Abort()
			return
		}

		if models.Status != 1 {
			c.JSON(200, serializer.Err(consts.CodeCheckLogin, "账号已被禁用", nil))
			c.Abort()
			return
		}
		systemId := user.SystemId
		/*if systemId <= 0 {
			c.JSON(200, serializer.Err(consts.CodeNoPermission, "登陆失效", nil))
			c.Abort()
		}*/

		if models.UserName != "mojun" {
			if err := config.ValidityAuth(int64(models.RoleID), c.Request.Method, c.Request.URL.Path, systemId); err != nil {
				c.JSON(200, serializer.Err(consts.CodeNoPermission, err.Error(), err))
				c.Abort()
				return
			}
		}

		c.Next()
		return
	}
}
