package pages

import (
	"context"
	"time"

	"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"
	"gorm.io/gorm"
)

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

	data, err := GetPages("Cms_pages.identity", in.Identity)
	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
}

func GetPages(key, val string) (*models.CmsPages, error) {
	var pages = models.CmsPages{}
	//// 使用事务确保操作
	// 查询帖子并更新点击量
	err := impl.DBService.Model(&models.CmsPages{}).Debug().Preload("Accessories").Preload("Tags.Tags").
		Where(key+" = ?", val).First(&pages).Error
	if err != nil {
		return nil, err
	}
	if err := impl.DBService.Model(&models.CmsPages{}).Where("key = ?", val).
		UpdateColumn("hits", gorm.Expr("hits + 1")).Error; err != nil {
		return nil, err
	}
	return &pages, err
}
