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

// 修改文章
func Modify(ctx context.Context, in *pb.PagesItem) (reply *pb.StatusReply, err error) {
	// parse authorization meta.
	_, err = service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	// TODO: valid code
	if in.GetSiteIdentity() == "" || in.GetIdentity() == "" {
		return nil, errcode.ErrInvalidArgument
	}
	var data = &models.CmsPages{
		SiteIdentity:           in.SiteIdentity,
		Title:                  in.Title,
		Key:                    in.Key,
		Description:            in.Description,
		CoverPath:              in.CoverPath,
		Content:                in.Content,
		HasAccessory:           in.HasAccessory,
		AccessoryIdentityArray: in.AccessoryIdentityArray,
		TagsIdentityArray:      in.TagsIdentityArray,
	}
	err = ModifyPages(in.Identity, data, in.AccessoryData, in.TagsIdentityArray)
	if err != nil {
		return nil, errcode.ErrDB
	}
	// TODO: add your logic code & delete this line.

	return &pb.StatusReply{
		Code:    0,
		Message: vars.OK,
		Timeseq: time.Now().UnixMilli(),
	}, nil

}

func ModifyPages(identity string, pages *models.CmsPages, accessory []*pb.AccessoryItem, tags []string) (err error) {
	var (
		accessoryPath = make([]models.CmsAccessory, 0)
		tagsData      = make([]models.CmsRelateTags, 0)
	)

	for _, val := range tags {
		tagsData = append(tagsData, models.CmsRelateTags{
			Identity:      utils.ULID(),
			PagesIdentity: identity,
			TagsIdentity:  val,
		})
	}
	for _, v := range accessory {
		accessoryPath = append(accessoryPath, models.CmsAccessory{
			Std_Identity:  types.Std_Identity{Identity: utils.UUID()},
			PagesId:       pages.ID,
			PagesIdentity: identity,
			FilePath:      v.FilePath,
		})
	}
	return impl.DBService.Transaction(func(tx *gorm.DB) error {
		if err = tx.Where("identity = ?", identity).Updates(pages).Error; err != nil {
			return err
		}
		// 删除旧的附件、分类和标签关联
		if err := tx.Where("pages_identity = ?", identity).Delete(&models.CmsAccessory{}).Error; err != nil {
			return err
		}

		if err := tx.Where("pages_identity = ?", identity).Delete(&models.CmsRelateTags{}).Error; err != nil {
			return err
		}
		// 创建新的标签关联
		if len(tags) != 0 {
			if err := tx.Create(&tagsData).Error; err != nil {
				return err
			}
		}
		// 创建新的附件关联
		if len(accessory) != 0 {
			if err := tx.Create(&accessoryPath).Error; err != nil {
				return err
			}
		}
		return nil
	})
}
