package member

import (
	"context"
	"time"

	"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/vars"
	"bsm/full/module/social/group/internal/impl"
	"bsm/full/module/social/group/internal/models"
	pb "bsm/full/module/social/group/pb"
)

// 退群
func DoQuit(ctx context.Context, in *pb.GroupOPRequest) (reply *pb.StatusReply, err error) {
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}
	// 判断是不是创建者
	var creator_id uint
	if err = impl.DBService.Model(&models.GroupBasic{}).Select("creator_id").Where("identity=?", in.GroupIdentity).Scan(&creator_id).Error; err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	if auth.ID == creator_id {
		return nil, errcode.ErrPermissionDenied
	}

	err = impl.DBService.Model(&models.GroupMember{}).Delete("group_identity=? and passport_id=?", in.GroupIdentity, auth.ID).Error
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	} else {
		//更新群组表数据统计
		models.UpsetGroupMemberTotal(in.GroupIdentity, "-")

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

}
