package post

import (
	"context"
	"time"

	"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"
)

// 获取文章详情 By Identity
func GetByIdentity(ctx context.Context, in *pb.GetPostRequest) (reply *pb.PostItem, err error) {
	if in.GetIdentity() == "" {
		return nil, errcode.ErrInvalidArgument
	}

	data, err := models.GetPost("identity", in.Identity)
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	var res = &pb.PostItem{}
	if data != nil {
		res.Identity = data.Identity
		res.OwnerId = int64(data.OwnerID)
		res.OwnerIdentity = data.OwnerIdentity
		res.Title = data.Title
		res.CoverPath = data.CoverPath
		res.Author = data.Author
		res.AuthorIdentity = data.AuthorIdentity
		res.Content = data.Content
		res.TargetUrl = data.TargetUrl
		res.SourceUrl = data.SourceUrl
		res.Hits = data.Hits
		res.HasAccessory = data.HasAccessory
		res.CreatedAt = data.CreatedAt.String()
		res.UpdatedAt = data.UpdatedAt.String()
		res.Description = data.Description
		res.LikeHits = data.LikeHits
		res.UnlikeHits = data.UnlikeHits
		res.CommentHits = data.CommentHits
		res.PostType = data.Types
		res.Key = data.Hash
		res.Hash = data.Hash
		res.Lang = data.Lang
		res.SourceOrigin = data.SourceOrigin
		res.Rights = data.Rights
		res.ExtendUrl = data.ExtendUrl
		res.ExtendData = data.ExtendData
		res.ExtendImg = data.ExtendImg
		res.ExtendDesc = data.ExtendDesc
		res.Published = data.Published.Format(time.DateTime)
	}
	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.Tags.Identity)
	}
	return res, nil
}
