mini_user_follower_logic.go 2.8 KB
package user

import (
	"context"
	"github.com/samber/lo"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/interanl/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/pkg/contextdata"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/pkg/xerr"
	"strings"

	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/api/internal/svc"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type MiniUserFollowerLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMiniUserFollowerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MiniUserFollowerLogic {
	return &MiniUserFollowerLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MiniUserFollowerLogic) MiniUserFollower(req *types.MiniUserFollowedSearchRequest) (resp *types.MiniUserFollowedSearchResponse, err error) {
	var (
		conn      = l.svcCtx.DefaultDBConn()
		user      *domain.User
		userToken = contextdata.GetUserTokenFromCtx(l.ctx)
	)
	if user, err = l.svcCtx.UserRepository.FindOne(l.ctx, conn, userToken.UserId); err != nil {
		return nil, xerr.NewErrMsgErr("用户不存在", err)
	}
	resp = &types.MiniUserFollowedSearchResponse{
		Total: 0,
		List:  make([]*types.UserFollowItem, 0),
	}
	resp.Total, resp.List = follower(l.ctx, l.svcCtx, user, req.Page, req.Size, req.Name)
	return
}

func follower(ctx context.Context, svcCtx *svc.ServiceContext, user *domain.User, page, size int, name string) (total int64, list []*types.UserFollowItem) {
	var (
		users         = user.Follower
		offset, limit = domain.OffsetLimit(page, size)
		conn          = svcCtx.DefaultDBConn()
		companyMap    = make(map[int64]*domain.Company)
	)
	total = int64(len(users))
	users = lo.Slice(users, offset, offset+limit)
	list = make([]*types.UserFollowItem, 0)
	for {
		if offset > len(user.Follower) {
			break
		}
		users = lo.Slice(users, offset, offset+limit)
		lo.ForEach(users, func(item int64, index int) {
			if foundUser, _ := svcCtx.UserRepository.FindOne(ctx, conn, item); foundUser != nil {
				if len(name) > 0 && !strings.Contains(foundUser.Name, name) {
					return
				}
				var companyName = ""
				if company, _ := domain.LazyLoad(companyMap, ctx, conn, foundUser.CompanyId, svcCtx.CompanyRepository.FindOne); company != nil {
					companyName = company.Name
				}
				list = append(list, &types.UserFollowItem{
					Id:             foundUser.Id,
					Name:           foundUser.Name,
					CompanyName:    companyName,
					Avatar:         foundUser.Avatar,
					Position:       foundUser.Position,
					Followed:       true,
					MutualFollowed: user.IsFriend(item),
				})
			}
		})
		if len(list) >= limit {
			break
		}
		page += 1
		offset, limit = domain.OffsetLimit(page, size)
	}
	return
}