package middleware

import (
	"github.com/casbin/casbin/v2/util"
	"github.com/gin-gonic/gin"
	"gogs.baozhida.cn/zoie/OAuth-core/api"
	mycasbin "gogs.baozhida.cn/zoie/OAuth-core/pkg/casbin"
	"gogs.baozhida.cn/zoie/OAuth-core/pkg/jwtauth"
	"gogs.baozhida.cn/zoie/OAuth-core/pkg/response"
	"gogs.baozhida.cn/zoie/OAuth-core/sdk"
	"gogs.baozhida.cn/zoie/OAuth-core/sdk/config"
	"net/http"
)

// AuthCheckRole 权限检查中间件
func AuthCheckRole() gin.HandlerFunc {
	return func(c *gin.Context) {
		log := api.GetRequestLogger(c)
		data, _ := c.Get(jwtauth.JwtPayloadKey)
		v := data.(jwtauth.MapClaims)
		e := sdk.Runtime.GetCasbinKey(config.ApplicationConfig.Host)
		var res, casbinExclude bool
		var err error
		// 检查权限
		rolekey, _ := v["roleKey"].(string)
		identity, _ := v["identity"]
		var userId float64
		if identity != nil {
			if f, ok := identity.(float64); ok {
				userId = f
			}
		}
		if rolekey == "admin" || userId == 1 {
			res = true
			c.Next()
			return
		}

		for _, i := range CasbinExclude {
			if util.KeyMatch2(c.Request.URL.Path, i.Url) && c.Request.Method == i.Method {
				casbinExclude = true
				break
			}

		}
		if casbinExclude {
			log.Infof("Casbin exclusion, no validation method:%s path:%s", c.Request.Method, c.Request.URL.Path)
			c.Next()
			return
		}
		enforceSub := rolekey
		if postCode, ok := v["postCode"]; ok && postCode != nil && postCode.(string) != "" {
			enforceSub = postCode.(string)
		}
		res, err = mycasbin.EnforceRoute(enforceSub, "", c.Request, e)
		if err != nil {
			log.Errorf("AuthCheckRole error: %s method:%s path:%s", err, c.Request.Method, c.Request.URL.Path)
			response.Error(c, 500, err, err.Error())
			return
		}

		if res {
			log.Infof("isTrue: %v role: %s method: %s path: %s", res, v["roleKey"], c.Request.Method, c.Request.URL.Path)
			c.Next()
			return
		} else {
			log.Warnf("isFalse: %v role: %s method: %s path: %s message: %s", res, v["roleKey"], c.Request.Method, c.Request.URL.Path, "当前request无权限，请管理员确认！")
			c.JSON(http.StatusOK, gin.H{
				"code": 403,
				"msg":  "对不起，您没有该接口访问权限，请联系管理员",
			})
			c.Abort()
			return
		}

	}
}
