package member

import (
	"context"
	"strings"
	"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 JoinDoHandle(ctx context.Context, in *pb.GroupOPRequest) (reply *pb.DataStatusReply, err error) {
	_, err = service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}
	var identity string
	switch strings.ToUpper(in.Direction) {
	case "PASS":
		var apply models.GroupApply
		if err = impl.DBService.Where("identity=?", in.Identity).First(&apply).Error; err != nil {
			printer.Error(err.Error())
			return nil, errcode.ErrDB
		}

		// 直接加入群成员
		identity = utils.UUID()
		member := &models.GroupMember{
			GroupID:       apply.GroupID,
			GroupIdentity: apply.GroupIdentity,
			Role:          0,
		}
		member.Identity = utils.UUID()
		member.PassportID = apply.FromID
		member.PassportIdentity = apply.FromIdentity

		if err = impl.DBService.Create(&member).Error; err != nil {
			printer.Error(err.Error())
			return nil, errcode.ErrDB
		}

		//更新申请表处理结果
		impl.DBService.Model(&models.GroupApply{}).Where("identity=?", in.Identity).UpdateColumn("status", 1)

		//更新群组表数据统计
		models.UpsetGroupMemberTotal(apply.GroupIdentity, "+")
	case "REJECT":
		//更新申请表处理结果
		impl.DBService.Model(&models.GroupApply{}).Where("identity=?", in.Identity).UpdateColumn("status", -1)
	}

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

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

}
