|
|
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 } }
|