package calorie_service import ( "errors" "github.com/ouxuanserver/osmanthuswine/src/core" "hudongzhuanjia/models" "time" ) func GetCurrentCalorie(aid, uid, rid int64) (map[string]interface{}, error) { calorie := new(models.Calorie) exist, err := calorie.GetCurrent(aid) if err != nil { return nil, err } if !exist { return nil, errors.New("轮次尚未开启") } calorieUser := new(models.CalorieUser) exist, err = calorieUser.GetByCalorieIdAndUserId(calorie.Id, uid, rid) if err != nil { return nil, err } if !exist { // 不存在,代表最后一名 calorieUser.ActivityId = aid calorieUser.RehearsalId = rid calorieUser.UserId = uid calorieUser.CalorieId = calorie.Id calorieUser.Score = 0 calorieUser.IsDelete = false calorieUser.JoinTime = time.Now().UnixNano() calorieUser.CreatedAt = time.Now() calorieUser.UpdatedAt = time.Now() if _, err = core.GetXormAuto().InsertOne(calorieUser); err != nil { return nil, err } rank, err := core.GetXormAuto().Where("is_delete=0 and calorie_id=? and rehearsal_id=?", calorie.Id, rid).Count(new(models.CalorieUser)) if err != nil { return nil, err } return map[string]interface{}{ "rank": rank, "score": calorieUser.Score, "calorie_id": calorie.Id, }, nil } else { // 存在 // 计算总数 count, err := core.GetXormAuto().Where("is_delete=0 and calorie_id=? and rehearsal_id=?", calorie.Id, rid).Count(new(models.CalorieUser)) if err != nil { return nil, err } // 计算分数 和 用户偏移量 users := make([]*models.CalorieUser, 0) err = core.GetXormAuto().Where("is_delete=0 and calorie_id=? and rehearsal_id=? and score<=?", calorie.Id, rid, calorieUser.Score).Desc("score").Asc("join_time").Find(&users) // desc score asc updated_at if err != nil { return nil, err } var rank int for index, u := range users { if u.Id == calorieUser.Id { rank = int(count) - len(users) + index + 1 // 总数 break } } return map[string]interface{}{ "rank": rank, "score": calorieUser.Score, "calorie_id": calorie.Id, }, nil } } type CalorieCountResult struct { Id int64 `json:"id"` ActivityId int64 `json:"activity_id"` CalorieId int64 `json:"calorie_id"` UserId int64 `json:"user_id"` Avatar string `json:"avatar"` Nickname string `json:"nickname"` Score int64 `json:"score"` } func RankCalorieUser(calorieId, rehearsalId interface{}, limit int) ([]*CalorieCountResult, error) { // 统计排名 result := make([]*CalorieCountResult, 0) err := core.GetXormAuto().Table(new(models.CalorieUser)).Alias("c"). Select("c.id, c.activity_id, c.calorie_id, c.user_id, u.avatar, u.nickname, c.score, c.join_time"). Join("LEFT", new(models.User).Alias("u"), "c.user_id=u.id and u.is_delete=0"). Where("c.is_delete=0 and c.calorie_id=? and c.rehearsal_id=?", calorieId, rehearsalId). Limit(limit).Desc("c.score").Asc("c.join_time").Find(&result) return result, err }