互动
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.1 KiB

5 years ago
  1. package calorie_service
  2. import (
  3. "errors"
  4. "github.com/ouxuanserver/osmanthuswine/src/core"
  5. "hudongzhuanjia/models"
  6. "time"
  7. )
  8. func GetCurrentCalorie(aid, uid, rid int64) (map[string]interface{}, error) {
  9. calorie := new(models.Calorie)
  10. exist, err := calorie.GetCurrent(aid)
  11. if err != nil {
  12. return nil, err
  13. }
  14. if !exist {
  15. return nil, errors.New("轮次尚未开启")
  16. }
  17. calorieUser := new(models.CalorieUser)
  18. exist, err = calorieUser.GetByCalorieIdAndUserId(calorie.Id, uid, rid)
  19. if err != nil {
  20. return nil, err
  21. }
  22. if !exist { // 不存在,代表最后一名
  23. calorieUser.ActivityId = aid
  24. calorieUser.RehearsalId = rid
  25. calorieUser.UserId = uid
  26. calorieUser.CalorieId = calorie.Id
  27. calorieUser.Score = 0
  28. calorieUser.IsDelete = false
  29. calorieUser.JoinTime = time.Now().UnixNano()
  30. calorieUser.CreatedAt = time.Now()
  31. calorieUser.UpdatedAt = time.Now()
  32. if _, err = core.GetXormAuto().InsertOne(calorieUser); err != nil {
  33. return nil, err
  34. }
  35. rank, err := core.GetXormAuto().Where("is_delete=0 and calorie_id=? and rehearsal_id=?",
  36. calorie.Id, rid).Count(new(models.CalorieUser))
  37. if err != nil {
  38. return nil, err
  39. }
  40. return map[string]interface{}{
  41. "rank": rank,
  42. "score": calorieUser.Score,
  43. "calorie_id": calorie.Id,
  44. }, nil
  45. } else { // 存在
  46. // 计算总数
  47. count, err := core.GetXormAuto().Where("is_delete=0 and calorie_id=? and rehearsal_id=?", calorie.Id, rid).Count(new(models.CalorieUser))
  48. if err != nil {
  49. return nil, err
  50. }
  51. // 计算分数 和 用户偏移量
  52. users := make([]*models.CalorieUser, 0)
  53. err = core.GetXormAuto().Where("is_delete=0 and calorie_id=? and rehearsal_id=? and score<=?",
  54. calorie.Id, rid, calorieUser.Score).Desc("score").Asc("join_time").Find(&users) // desc score asc updated_at
  55. if err != nil {
  56. return nil, err
  57. }
  58. var rank int
  59. for index, u := range users {
  60. if u.Id == calorieUser.Id {
  61. rank = int(count) - len(users) + index + 1 // 总数
  62. break
  63. }
  64. }
  65. return map[string]interface{}{
  66. "rank": rank,
  67. "score": calorieUser.Score,
  68. "calorie_id": calorie.Id,
  69. }, nil
  70. }
  71. }