package logic

import (
	"context"

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

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

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

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

// 百科列表
func (l *GetWikiListLogic) GetWikiList(in *plant.WikiListReq) (*plant.WikiListResp, error) {
	db := l.svcCtx.DB.Model(&plantModel.Wiki{})
	if in.Name != "" {
		db = db.Where("name like ?", "%"+in.Name+"%")
	}
	if in.IsHot > 0 {
		db = db.Where("is_hot = ?", in.IsHot)
	}

	var total int64
	db.Count(&total)

	pageSize := int(in.PageSize)
	if pageSize <= 0 {
		pageSize = 20
	}
	offset := (int(in.Current) - 1) * pageSize
	if offset < 0 {
		offset = 0
	}

	var list []plantModel.Wiki
	if err := db.Limit(pageSize).Offset(offset).Order("created_at desc").Find(&list).Error; err != nil {
		return nil, err
	}

	var result []*plant.WikiInfo
	for _, item := range list {
		result = append(result, wikiInfoFromModel(l.svcCtx.DB, item))
	}

	return &plant.WikiListResp{List: result, Total: total}, nil
}
