91 lines
2.2 KiB
Go
91 lines
2.2 KiB
Go
package logic
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"fusenapi/constants"
|
|
"fusenapi/model"
|
|
"fusenapi/product/internal/svc"
|
|
"fusenapi/product/internal/types"
|
|
"fusenapi/utils/auth"
|
|
"fusenapi/utils/image"
|
|
"github.com/zeromicro/go-zero/core/stores/sqlx"
|
|
"math/rand"
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
)
|
|
|
|
type GetSuccessRecommandLogic struct {
|
|
logx.Logger
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
}
|
|
|
|
func NewGetSuccessRecommandLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetSuccessRecommandLogic {
|
|
return &GetSuccessRecommandLogic{
|
|
Logger: logx.WithContext(ctx),
|
|
ctx: ctx,
|
|
svcCtx: svcCtx,
|
|
}
|
|
}
|
|
|
|
func (l *GetSuccessRecommandLogic) GetSuccessRecommand(req *types.GetSuccessRecommandReq, loginInfo auth.UserInfo) (resp *types.Response) {
|
|
resp = &types.Response{}
|
|
//校验前台登录情况
|
|
if loginInfo.UserId == 0 {
|
|
resp.Set(constants.CODE_UNAUTH, "please sign in")
|
|
return
|
|
}
|
|
//获取用户信息
|
|
userModel := model.NewFsUserModel(l.svcCtx.MysqlConn)
|
|
userInfo, err := userModel.FindOne(l.ctx, loginInfo.UserId)
|
|
if err != nil && errors.Is(err, sqlx.ErrNotFound) {
|
|
logx.Error(err)
|
|
resp.Set(constants.CODE_SERVICE_ERR, "failed to get user info")
|
|
return
|
|
}
|
|
if userInfo == nil {
|
|
resp.Set(constants.CODE_UNAUTH, "failed to get user info")
|
|
return
|
|
}
|
|
if req.Num == 0 {
|
|
req.Num = 8
|
|
}
|
|
if req.Size > 0 {
|
|
req.Size = image.GetCurrentSize(req.Size)
|
|
}
|
|
//获取所有产品的ids
|
|
productModel := model.NewFsProductModel(l.svcCtx.MysqlConn)
|
|
productList, err := productModel.GetAllProductList(l.ctx, 0, 1, "sort-asc")
|
|
if err != nil {
|
|
logx.Error(err)
|
|
resp.Set(constants.CODE_SERVICE_ERR, "failed to get product list")
|
|
return
|
|
}
|
|
//没有推荐产品就返回
|
|
if len(productList) == 0 {
|
|
resp.Set(constants.CODE_OK, "success")
|
|
return
|
|
}
|
|
productIds := make([]string, 0, len(productList))
|
|
for _, v := range productList {
|
|
productIds = append(productIds, fmt.Sprintf("%d", v.Id))
|
|
}
|
|
//随机取8个
|
|
if len(productIds) > int(req.Num) {
|
|
//打乱顺序
|
|
indexArr := rand.Perm(len(productIds))
|
|
tmpProductIds := make([]string, 0, int(req.Num))
|
|
for k, v := range indexArr {
|
|
if k == 8 {
|
|
break
|
|
}
|
|
tmpProductIds = append(tmpProductIds, productIds[v])
|
|
}
|
|
productIds = tmpProductIds
|
|
}
|
|
|
|
return resp
|
|
}
|