package member

import (
	"context"
	"time"

	"bsm/full/module/social/group/internal/impl"
	"bsm/full/module/social/group/internal/models"
	pb "bsm/full/module/social/group/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"git.apinb.com/bsm-sdk/core/service"
	"git.apinb.com/bsm-sdk/core/utils"
)

// 申请加群
func DoJoin(ctx context.Context, in *pb.DoJoinRequest) (reply *pb.DataStatusReply, err error) {
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}
	//生成唯一标识
	identity := utils.UUID()

	//判断是否需要加群验证
	if models.GetGroupEnableAnyJoin(auth.ID, in.Identity) {
		// 直接加入群成员
		apply := &models.GroupMember{
			GroupID:       uint(in.Id),
			GroupIdentity: in.Identity,
			Role:          ROLE_MEMBER,
		}
		apply.Identity = utils.UUID()
		apply.PassportID = auth.ID
		apply.PassportIdentity = auth.Identity

		err = impl.DBService.Create(&apply).Error
	} else {
		// 写入加群申请表
		apply := &models.GroupApply{
			FromID:        uint(auth.ID),
			FromIdentity:  auth.Identity,
			GroupID:       uint(in.Id),
			GroupIdentity: in.Identity,
			Message:       in.Message,
		}
		apply.Identity = utils.UUID()

		err = impl.DBService.Create(&apply).Error
	}

	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	return &pb.DataStatusReply{
		Data:    identity,
		Timeseq: time.Now().UnixMilli(),
	}, nil

}
