package pages

import (
	"context"
	"time"

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

// 获取文章详情 By Key
func GetByKey(ctx context.Context, in *pb.GetPagesByKeyRequest) (reply *pb.PagesItem, err error) {
	if in.GetKey() == "" {
		return nil, errcode.ErrInvalidArgument
	}

	data, err := GetPages("key", in.Key)
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	var res = &pb.PagesItem{}
	if data != nil {
		res.Identity = data.Identity
		res.Title = data.Title
		res.CoverPath = data.CoverPath
		res.Content = data.Content
		res.Hits = data.Hits
		res.HasAccessory = data.HasAccessory
		res.CreatedAt = data.CreatedAt.String()
		res.UpdatedAt = data.UpdatedAt.String()
		res.Description = data.Description
		res.PostType = data.Type
	}
	for _, val := range data.Accessories {
		res.AccessoryData = append(res.AccessoryData, &pb.AccessoryItem{
			Identity:  val.Identity,
			Title:     val.Title,
			FilePath:  val.FilePath,
			CreatedAt: val.CreatedAt.Format(time.DateTime),
		})
	}
	for _, val := range data.Accessories {
		res.AccessoryIdentityArray = append(res.AccessoryIdentityArray, val.Identity)
	}

	for _, val := range data.Tags {
		res.TagsData = append(res.TagsData, &pb.TagsItem{
			Id:        int64(val.ID),
			Identity:  val.Tags.Identity,
			Title:     val.Tags.Title,
			Intro:     val.Tags.Intro,
			CoverPath: val.Tags.CoverPath,
			CreatedAt: val.Tags.CreatedAt.Format(time.DateTime),
		})
	}
	for _, val := range data.Tags {
		res.TagsIdentityArray = append(res.TagsIdentityArray, val.Identity)
	}
	return res, nil
}
