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

// 文章列表
func Fetch(ctx context.Context, in *pb.PagesListRequest) (reply *pb.PagesListReply, err error) {
	if in.GetPage() < 1 {
		in.Page = 1
	}
	if in.GetSize() < 10 {
		in.Size = 10
	}
	if in.GetSize() > 50 {
		in.Size = 50
	}
	list, cnt, err := PagesList(in.Page, in.Size, in.Keyword, int64(in.Type))
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}
	var res = pb.PagesListReply{
		Count: cnt,
		Data:  make([]*pb.PagesItem, 0),
	}
	for _, val := range list {
		var (
			accessoryData = make([]*pb.AccessoryItem, 0)
			accessories   = make([]string, 0)

			TagsData          = make([]*pb.TagsItem, 0)
			tagsIdentityArray = make([]string, 0)
		)
		for _, accessory := range val.Accessories {
			accessoryData = append(accessoryData, &pb.AccessoryItem{
				Identity:  accessory.Identity,
				Title:     accessory.Title,
				FilePath:  accessory.FilePath,
				CreatedAt: accessory.CreatedAt.Format(time.DateTime),
			})
			accessories = append(accessories, accessory.Identity)
		}

		for _, tags := range val.Tags {
			TagsData = append(TagsData, &pb.TagsItem{
				Id:        int64(tags.Tags.ID),
				Identity:  tags.TagsIdentity,
				Title:     tags.Tags.Title,
				Intro:     tags.Tags.Intro,
				CoverPath: tags.Tags.CoverPath,
				CreatedAt: tags.Tags.CreatedAt.Format(time.DateTime),
			})
			tagsIdentityArray = append(tagsIdentityArray, tags.TagsIdentity)
		}

		res.Data = append(res.Data, &pb.PagesItem{
			Identity:               val.Identity,
			Title:                  val.Title,
			CoverPath:              val.CoverPath,
			Content:                val.Content,
			Hits:                   val.Hits,
			HasAccessory:           val.HasAccessory,
			CreatedAt:              val.CreatedAt.Format(time.DateTime),
			UpdatedAt:              val.UpdatedAt.Format(time.DateTime),
			Description:            val.Description,
			PostType:               val.Type,
			Key:                    val.Key,
			AccessoryData:          accessoryData,
			AccessoryIdentityArray: accessories,
			TagsData:               TagsData,
			TagsIdentityArray:      tagsIdentityArray,
		})
	}

	return &res, nil
}

func PagesList(page, size int64, keyword string, userType int64) (list []*models.CmsPages, cnt int64, err error) {

	tx := impl.DBService.Model(&models.CmsPages{})

	if keyword != "" {
		tx = tx.Where("Cms_pages.title like ?", "%"+keyword+"%")
	}

	if userType != 0 {
		tx = tx.Where("Cms_pages.type = ?", userType)
	}

	if err = tx.Count(&cnt).Order("Cms_pages.created_at desc").Limit(int(size)).Offset(int((page - 1) * size)).Error; err != nil {
		return nil, 0, errcode.ErrDB
	}
	err = tx.Preload("Accessories").Preload("Tags.Tags").Find(&list).Error
	return
}
