package member

import (
	"context"

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

// 申请加群列表
func JoinFetch(ctx context.Context, in *pb.Empty) (reply *pb.JoinFetchReply, err error) {
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	fetch := make([]*pb.ApplyJoinGroupItem, 0)
	group_ids := models.GetMasterGroup(auth.ID)
	if len(group_ids) > 0 {
		err = impl.DBService.Model(&models.GroupApply{}).Where("group_id in ", group_ids).Find(&fetch).Error
		if err != nil {
			printer.Error(err.Error())
			return nil, errcode.ErrDB
		}
		var card = &pb.PassportInfoDetailCard{}
		for idx, item := range fetch {
			err = impl.DBService.Table("passport_extend").Select(filed).Where("passport_identity = ?", item.From.Identity).First(card).Error
			if err != nil {
				printer.Error(err.Error())
				return nil, errcode.ErrDB
			}
			fetch[idx].From = card
		}
	}

	return &pb.JoinFetchReply{
		Total:  int32(len(fetch)),
		Applys: fetch,
	}, nil
}
