package tags

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/service"
	"git.apinb.com/bsm-sdk/core/types"
	"git.apinb.com/bsm-sdk/core/utils"
	"git.apinb.com/bsm-sdk/core/vars"
)

// 创建标签
func Create(ctx context.Context, in *pb.TagsItem) (reply *pb.StatusReply, err error) {
	var cnt int64 = 0
	_, err = service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	if in.GetTitle() == "" || in.GetCoverPath() == "" || in.GetIntro() == "" {
		return nil, errcode.ErrInvalidArgument
	}
	if err := impl.DBService.Model(&models.CmsTags{}).Where("title = ?", in.Title).First(&models.CmsTags{}).Error; err == nil {
		return nil, errcode.ErrDB
	}
	if cnt > 0 {
		return nil, errcode.ErrAlreadyExists
	}
	var data = &models.CmsTags{
		Std_Identity: types.Std_Identity{Identity: utils.UUID()},
		Title:        in.Title,
		CoverPath:    in.CoverPath,
		Intro:        in.Intro,
	}
	if err := impl.DBService.Model(&models.CmsTags{}).Create(data).Error; err != nil {
		return nil, errcode.ErrDB
	}
	return &pb.StatusReply{
		Code:    0,
		Message: vars.OK,
		Details: data.Identity,
		Timeseq: time.Now().Unix(),
	}, nil

}
