package ldap_lib

import (
	"encoding/json"
	"fmt"
	"fusenapi/model/gmodel"
	"net/http"
	"time"

	"github.com/patrickmn/go-cache"
	"github.com/zeromicro/go-zero/core/logx"
)

type LdapVerifyType string

const (
	API_PATH  LdapVerifyType = "api_path"
	MENU_PATH LdapVerifyType = "menu_path"
)

type LdapOptions struct {
	Type  LdapVerifyType
	Value string
}

// 验证权限
func (l *Ldap) VerifyAuthority(r *http.Request, options ...LdapOptions) bool {
	return true
	token := r.Header.Get("Ldap-Authorization")
	info, err := l.ParseJwtToken(token, l.jwtSecret)
	if err != nil {
		logx.Error("解析token失败", err, "----token:", token)
		return false
	}
	//查询ldap
	userInfo, err := l.GetLdapUserInfo(info.UserDN)
	if err != nil {
		logx.Error("获取ldap用户信息失败", err, "----user_dn:", info.UserDN)
	}
	if userInfo.Status != 1 {
		return false
	}
	if len(options) == 0 {
		return true
	}
	return true
}

// 验证权限组
func (l *Ldap) VerifyAuthorityGroup(r *http.Request, options ...LdapOptions) bool {
	token := r.Header.Get("Ldap-Authorization")
	info, err := l.ParseJwtToken(token, l.jwtSecret)
	if err != nil {
		logx.Error("解析token失败", err, "----token:", token)
		return false
	}
	//查询ldap
	userInfo, err := l.GetLdapUserInfo(info.UserDN)
	if err != nil {
		logx.Error("获取ldap用户信息失败", err, "----user_dn:", info.UserDN)
	}
	if userInfo.GroupId != 0 {
		return false
	}
	var groupId = userInfo.GroupId
	var apiId int64 = 0
	var apiMaps = make(map[int64]string, 100)

	// var err error
	// var groupId = 6

	// 当前API路由
	path := r.URL.Path

	// 缓存组件--go get github.com/patrickmn/go-cache
	c := cache.New(5*time.Minute, 10*time.Minute)

	var pathKey = fmt.Sprintf("LdapApi_%v_%v", path, r.Method)
	apiIdObj, found := c.Get(pathKey)
	if found {
		apiId = apiIdObj.(int64)
	} else {
		// 缓存--5分钟
		var infoLdapApis gmodel.LdapApis
		resLdapApis := l.MysqlConn.Model(gmodel.LdapApis{}).Where("path = ? AND method = ?", path, r.Method).Take(&infoLdapApis)
		if resLdapApis.Error != nil {
			err = resLdapApis.Error
			logx.Error("获取ldap用户信息权限组失败", err)
			return false
		}
		apiId = infoLdapApis.Id
		c.Set(pathKey, apiId, 5*time.Minute)
	}

	var groupKey = fmt.Sprintf("LdapGroup_%v", groupId)
	groupObj, groupFound := c.Get(groupKey)
	if groupFound {
		apiMaps = groupObj.(map[int64]string)
	} else {
		// 缓存--5分钟
		var infoLdapGroup gmodel.LdapGroup
		resLdapGroup := l.MysqlConn.Model(gmodel.LdapGroup{}).Where("id = ?", groupId).Take(&infoLdapGroup)
		if resLdapGroup.Error != nil {
			err = resLdapGroup.Error
			logx.Error("获取ldap用户信息权限组失败", err)
			return false
		}

		var metadata []*GroupAuthMetadata
		if infoLdapGroup.Metadata != nil {
			err := json.Unmarshal(*infoLdapGroup.Metadata, &metadata)
			if err != nil {
				logx.Error("系统出错", err)
				return false
			}
			getAllApis(metadata, &apiMaps)
			c.Set(groupKey, apiMaps, 5*time.Minute)
		}
	}

	if _, ok := apiMaps[apiId]; ok {
		return true
	} else {
		return false
	}
}

func getAllApis(metadata []*GroupAuthMetadata, apiMaps *map[int64]string) {
	apiMapsData := *apiMaps
	for _, v := range metadata {
		if v.Type == "api" {
			apiMapsData[v.Id] = v.Name
		} else if v.Type == "group" {
			getAllApis(v.Metadata, apiMaps)
		} else {
			continue
		}
	}
}

type GroupAuthMetadata struct {
	Id       int64                `json:"id"`
	Name     string               `json:"name"`
	Type     string               `json:"type"`
	Metadata []*GroupAuthMetadata `json:"metadata"`
}