package logic

import (
	"fusenapi/model/gmodel"
	"fusenapi/utils/auth"
	"fusenapi/utils/basic"
	"math"

	"context"

	"fusenapi/server/ldap-admin/internal/svc"
	"fusenapi/server/ldap-admin/internal/types"

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

type GetApisLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetApisLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetApisLogic {
	return &GetApisLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// 处理进入前逻辑w,r
// func (l *GetApisLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
// }

func (l *GetApisLogic) GetApis(req *types.GetApisReq, userinfo *auth.UserInfo) (resp *basic.Response) {
	// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
	// userinfo 传入值时, 一定不为null
	resList, resCount, err := l.svcCtx.AllModels.LdapApis.FindPage(l.ctx, gmodel.FindPageReq{
		Page:  req.CurrentPage,
		Limit: req.PerPage,
	})
	if err != nil {
		return resp.SetStatus(basic.CodeServiceErr)
	}
	var pageCount int = 1
	if resCount > int64(req.PerPage) {
		var float64Count = float64(resCount)
		var float64PerPage = float64(req.PerPage)
		pageCountFloat := math.Ceil(float64Count / float64PerPage)
		pageCount = int(pageCountFloat)
	}

	return resp.SetStatus(basic.CodeOK, map[string]interface{}{
		"list": resList,
		"meta": map[string]int{
			"total_count":  int(resCount),
			"page_count":   pageCount,
			"current_page": req.CurrentPage,
			"per_page":     req.PerPage,
		},
	})
}

// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
// func (l *GetApisLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
// // httpx.OkJsonCtx(r.Context(), w, resp)
// }