package middleware

import (
	"github.com/gin-gonic/gin"
	"hongze/hongze_yb/controller/response"
	"hongze/hongze_yb/models/tables/wx_user"
	"hongze/hongze_yb/services/company"
	"hongze/hongze_yb/services/user"
	"hongze/hongze_yb/utils"
	"strconv"
)

// CheckCygxAuth 如果带thirdCode就可以看，如果有权限也给其他权限
func CheckCygxAuth() gin.HandlerFunc {

	return func(c *gin.Context) {

		userInfo := user.GetInfoByClaims(c)

		thirdCodeEncrypt := c.Request.Header.Get("thirdCode")


		if thirdCodeEncrypt != "" {
			thirdCode := utils.DesBase64Decrypt([]byte(thirdCodeEncrypt))
			userId, err := strconv.Atoi(string(thirdCode))
			if err != nil {
				response.FailMsg("参数错误", "参数错误", c)
				c.Abort()
				return
			}
			_, err = wx_user.GetByUserId(userId)
			if err != nil {
				response.FailMsg("获取用户信息失败", "获取用户信息失败", c)
				c.Abort()
				return
			}
		} else {
			ok, checkInfo, _, err := company.CheckBaseFiccPermission(userInfo.CompanyID, int(userInfo.UserID))
			if err != nil {
				response.FailMsg("用户权限验证失败", "CheckBaseAuth-用户权限验证失败"+err.Error(), c)
				c.Abort()
				return
			}
			if !ok {
				response.AuthError(checkInfo, "暂无权限", c)
				c.Abort()
				return
			}
		}

		c.Next()
	}
}
