package banner

import (
	"context"
	"math"

	"sundynix-micro-go/app/plant/api/internal/svc"
	"sundynix-micro-go/app/plant/api/internal/types"
	plantModel "sundynix-micro-go/app/plant/model"

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

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

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

func (l *GetBannerListLogic) GetBannerList(req *types.BannerListReq) (interface{}, error) {
	db := l.svcCtx.DB.Model(&plantModel.Banner{})
	if req.Title != "" {
		db = db.Where("title LIKE ?", "%"+req.Title+"%")
	}
	if req.IsActive > 0 {
		db = db.Where("is_active = ?", req.IsActive)
	}

	var total int64
	db.Count(&total)

	pageSize := req.PageSize
	if pageSize <= 0 {
		pageSize = 10
	}
	current := req.Current
	if current <= 0 {
		current = 1
	}
	offset := (current - 1) * pageSize

	var list []plantModel.Banner
	db.Order("sort asc, created_at desc").Limit(pageSize).Offset(offset).Find(&list)

	type BannerItem struct {
		Id        string `json:"id"`
		Title     string `json:"title"`
		ImageId   string `json:"imageId"`
		Sort      int    `json:"sort"`
		IsActive  int    `json:"isActive"`
		TargetUrl string `json:"targetUrl"`
		CreatedAt string `json:"createdAt"`
	}
	var result []BannerItem
	for _, item := range list {
		result = append(result, BannerItem{
			Id:        item.ID,
			Title:     item.Title,
			ImageId:   item.ImageID,
			Sort:      item.Sort,
			IsActive:  item.IsActive,
			TargetUrl: item.TargetURL,
			CreatedAt: item.CreatedAt.Format("2006-01-02 15:04:05"),
		})
	}

	return map[string]interface{}{
		"list":      result,
		"total":     total,
		"page":      current,
		"pageSize":  pageSize,
		"totalPage": math.Ceil(float64(total) / float64(pageSize)),
	}, nil
}
