rank.go 2.28 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
package cp_m

import (
	"git.hilo.cn/hilo-common/domain"
	"git.hilo.cn/hilo-common/resource/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"time"
)

type CpDayRank struct {
	Date        string
	CpId        mysql.ID
	UserId1     mysql.ID
	UserId2     mysql.ID
	Score       mysql.Num
	CreatedTime time.Time `gorm:"->"`
	UpdatedTime time.Time `gorm:"->"`
}

// 增加cp排行榜-天
func AddCpDayRank(model *domain.Model, cpRelation CpRelation, score mysql.Num) (err error) {
	date := time.Now().Format("2006-01-02")
	rank := &CpDayRank{
		Date:    date,
		CpId:    cpRelation.Id,
		UserId1: cpRelation.UserId1,
		UserId2: cpRelation.UserId2,
		Score:   score,
	}
	if err = model.DB().Model(CpDayRank{}).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "date"}, {Name: "cp_id"}},
		DoUpdates: clause.Assignments(map[string]interface{}{
			"score": gorm.Expr("score + ?", rank.Score)})}).Create(rank).Error; err != nil {
		model.Log.Errorf("AddCpDayRank fail:%v", err)
		return err
	}
	return nil
}

// 分页获取cp排行榜
func PageCpDayRank(model *domain.Model, beginDate, endDate string, offset, limit int) []CpDayRank {
	var ranks []CpDayRank
	if err := model.DB().Table("cp_day_rank r").Joins("INNER JOIN cp_relation c ON c.id = r.cp_id").
chenweijian's avatar
chenweijian committed
44 45 46
		Where("r.date BETWEEN ? AND ?", beginDate, endDate).
		Where("cp_id not in (1581, 12651, 5171, 9191, 39131, 28801, 181, 35221)").
		Group("cp_id").Select("cp_id,r.user_id1,r.user_id2,SUM(r.score) score").
hujiebin's avatar
hujiebin committed
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
		Order("score DESC").Offset(offset).Limit(limit).Find(&ranks).Error; err != nil {
		model.Log.Errorf("PageCpDayRank fail:%v", err)
	}
	return ranks
}

// 获取指定cp排行榜
func GetCpDayRank(model *domain.Model, beginDate, endDate string, cpId mysql.ID) CpDayRank {
	var rank CpDayRank
	if err := model.DB().Table("cp_day_rank").
		Where("date BETWEEN ? AND ?", beginDate, endDate).Where("cp_id = ?", cpId).Select("cp_id,user_id1,user_id2,SUM(score) score").
		First(&rank).Error; err != nil {
		model.Log.Errorf("GetCpDayRank fail:%v", err)
	}
	return rank
}
hujiebin's avatar
hujiebin committed
63 64 65 66 67 68 69 70 71

// 获取Cp历史分数
func SumCpPoints(model *domain.Model, cpId mysql.ID) mysql.Num {
	var score CpDayRank
	if err := model.DB().Model(CpDayRank{}).Where("cp_id = ?", cpId).Select("SUM(score) score").Scan(&score).Error; err != nil {
		model.Log.Errorf("SumCpPoints fail:%v", err)
	}
	return score.Score
}