package service

import (
	"encoding/json"
	"errors"
	"gadmin/config"
	"gadmin/internal/admin/forms"
	"gadmin/internal/gorm/model"
	"gadmin/internal/gorm/query"
	"gadmin/utility/token"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"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) {
	cUser, ok := c.Get("user")
	if !ok {
		return nil, errors.New("获取用户信息失败")
	}
	claims := cUser.(*token.UserClaims)
	roleId := claims.RoleId

	var (
		q  = query.Use(config.AdminDB).AdminRole
		sq = query.Use(config.AdminDB).AdminSystem
	)
	systemModels := make([]*model.AdminSystem, 0)
	if config.IsSuperRole(roleId) {
		models, err := sq.Find()
		if err != nil {
			logrus.Error(err)
			return nil, err
		}
		systemModels = models
	} else {
		systems := ""
		if err := q.Where(q.ID.Eq(roleId)).Pluck(q.Systems, &systems); err != nil {
			return nil, err
		}
		if systems == "" {
			return []*forms.Service{}, nil
		}
		systemIds := make([]int32, 0)
		if err := json.Unmarshal([]byte(systems), &systemIds); err != nil {
			return nil, err
		}

		models, err := sq.Where(sq.ID.In(systemIds...)).Order(sq.ID).Find()
		if err != nil {
			logrus.Error(err)
			return nil, err
		}
		systemModels = models
	}

	var services []*forms.Service
	for _, v := range systemModels {
		services = append(services, &forms.Service{
			Id:   v.ID,
			Name: v.Name,
			Path: v.URL + "?access-token={access-token}",
		})
	}
	return services, nil
}
