package follow

import (
	"context"
	"strings"

	"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/relation/internal/impl"
	common "bsm/full/module/social/relation/internal/logic/common"
	"bsm/full/module/social/relation/internal/models"
	pb "bsm/full/module/social/relation/pb"
)

// 获取关注列表
func Fetch(ctx context.Context, in *pb.FetchRequest) (reply *pb.FetchRelationItemReply, err error) {
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}
	var (
		total  int64
		column string
		ids    []uint
		model  = impl.DBService.Model(&models.RelationFollow{})
		cards  []*pb.RelationItem
	)

	switch strings.ToUpper(in.Params["direction"]) {
	case "MY": // 我关注的
		column = "to_identity"
		model.Where("from_identity=?", auth.Identity)
	case "WHO": // 关注我的
		column = "from_identity"
		model.Where("to_identity=?", auth.Identity)
	default:
		return &pb.FetchRelationItemReply{}, nil
	}

	//处理分页
	if in.PageNo <= 1 {
		in.PageNo = 1
	}
	if in.PageSize <= 1 {
		in.PageSize = 20
	}

	err = model.Count(&total).Order("id desc").Offset(int(in.PageNo-1)*int(in.PageSize)).Limit(int(in.PageSize)).Pluck(column, &ids).Error
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	//根据ids取得用户信息卡片
	cards, err = common.GetrelationInfoDetailCardById(ids)
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	return &pb.FetchRelationItemReply{
		Total: total,
		Data:  cards,
	}, nil
}
