package service

import (
	"entrance-grpc/iam"
	"errors"
	"gadmin/config"
	"gadmin/internal/admin/forms"
	"gadmin/utility/token"
	"github.com/gin-gonic/gin"
	"time"

	"github.com/patrickmn/go-cache"
)

var Service = &sService{
	SystemCache: cache.New(5*time.Minute, 10*time.Minute),
}

type sService struct {
	SystemCache *cache.Cache
}

func (s *sService) ServiceList(c *gin.Context) ([]*forms.Service, error) {
	claims := token.CurrentUser(c)
	if claims == nil {
		return nil, errors.New("获取用户信息失败")
	}
	roleId := claims.RoleID

	res, err := config.GetIamClient().GetRoleSystems(c, &iam.GetRoleSystemsReq{
		RoleID: roleId,
	})
	if err != nil || res.Code != 0 {
		return nil, err
	}

	var services []*forms.Service
	for _, v := range res.Data {
		isSelected := false
		if v.ID == config.SystemId {
			isSelected = true
		}
		services = append(services, &forms.Service{
			Id:         int32(v.ID),
			Name:       v.Name,
			Path:       v.Url + "?access-token={access-token}",
			IsSelected: isSelected,
		})
	}
	return services, nil
}
