package client

import (
	"hudongzhuanjia/controllers"
	"hudongzhuanjia/models"
	"hudongzhuanjia/utils/code"
	"hudongzhuanjia/utils/define"
)

type CalorieCtl struct {
	controllers.AuthorCtl
}

// h5 1/s
func (t *CalorieCtl) Shake() {
	calorieId := t.MustGetInt64("calorie_id")
	score := t.DefaultInt("score", 0)
	uid := t.MustGetUID()

	calorie := new(models.Calorie)
	exist, err := models.Get(calorie, calorieId)
	t.CheckErr(err)
	t.Assert(exist, code.MSG_CALORIE_NOT_EXIST, "卡路里不存在")

	activity := new(models.Activity)
	exist, err = models.Get(activity, calorie.ActivityId)
	t.CheckErr(err)
	t.Assert(exist, code.MSG_ACTIVITY_NOT_EXIST, "互动不存在")
	t.CheckRunning(activity.Status)

	calorieUser := new(models.CalorieUser)
	exist, err = calorieUser.GetByCalorieIdAndUserId(calorieId, uid, activity.RehearsalId)
	t.CheckErr(err)
	t.Assert(exist, code.MSG_DATA_NOT_EXIST, "您尚未参与卡路里活动")

	// 增加score
	if calorie.Status == define.StatusRunning && score > 0 {
		_, err = calorieUser.IncrScore(score)
		t.CheckErr(err)
		calorieUser.Score += int64(score) // 增加
	}

	count, err := calorieUser.CountByCalorieId(calorie.Id, activity.RehearsalId)
	t.CheckErr(err)

	users, err := models.GetCalorieUsersByCalorieIdAndScore(calorie.Id, activity.RehearsalId, calorieUser.Score)
	t.CheckErr(err)

	var rank int
	for index, user := range users {
		if user.Id == calorieUser.Id {
			rank = int(count) - len(users) + index + 1
			break
		}
	}

	t.JSON(map[string]interface{}{
		"rank":  rank,
		"score": calorieUser.Score, // 分数
	})
}