package post

import (
	"context"

	"bsm/full/module/base/cms/internal/impl"
	"bsm/full/module/base/cms/internal/models"
	pb "bsm/full/module/base/cms/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
)

// 搜索文章
func Search(ctx context.Context, in *pb.SearchRequest) (reply *pb.PostListReply, err error) {
	if in.GetKeyword() == "" {
		return nil, errcode.ErrInvalidArgument
	}

	var (
		cnt      int64 = 0
		pageNo   int64 = in.GetPageNo()
		pageSize int64 = in.GetPageSize()
		offset   int64 = (pageNo - 1) * pageSize
	)

	// vlidate request page_no,page_size.
	if pageNo < 1 {
		pageNo = 1
		offset = 0
	}
	if pageSize < 50 {
		pageSize = 50
		offset = (pageNo - 1) * pageSize
	}

	var data []*models.CmsPost
	tx := impl.DBService.Model(&models.CmsPost{}).Where("title like ? or Cms like ?", "%"+in.Keyword+"%", "%"+in.Keyword+"%")
	if err := tx.Count(&cnt).Offset(int(offset)).Limit(int(pageSize)).Find(&data).Error; err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	replyData := make([]*pb.PostItem, len(data))
	for _, val := range data {
		replyData = append(replyData, &pb.PostItem{
			Identity:       val.Identity,
			OwnerId:        int64(val.OwnerID),
			OwnerIdentity:  val.OwnerIdentity,
			Title:          val.Title,
			CoverPath:      val.CoverPath,
			Author:         val.Author,
			AuthorIdentity: val.AuthorIdentity,
			Content:        val.Content,
			TargetUrl:      val.TargetUrl,
			SourceUrl:      val.SourceUrl,
			Hits:           val.Hits,
			HasAccessory:   val.HasAccessory,
			CreatedAt:      val.CreatedAt.String(),
			UpdatedAt:      val.UpdatedAt.String(),
			Description:    val.Description,
			LikeHits:       val.LikeHits,
			UnlikeHits:     val.UnlikeHits,
			CommentHits:    val.CommentHits,
			PostType:       val.Types,
			Key:            val.Hash,
			Hash:           val.Hash,
		})
	}

	return &pb.PostListReply{
		Count: cnt,
		Data:  replyData,
	}, nil
}
