medal.go 2.17 KB
Newer Older
chenweijian's avatar
chenweijian committed
1 2 3
package user_m

import (
hujiebin's avatar
hujiebin committed
4 5
	"git.hilo.cn/hilo-common/domain"
	"git.hilo.cn/hilo-common/resource/mysql"
chenweijian's avatar
chenweijian committed
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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
	"hilo-user/domain/model/common"
	"hilo-user/domain/model/res_m"
	"time"
)

//用户道具
type UserMedal struct {
	mysql.Entity
	*domain.Model `gorm:"-"`
	UserId        mysql.ID
	MedalId       uint32
	//MedalType     res_m2.ResMedalType
	//Scope         res_m2.ResMedalScope
	EndTime *time.Time
}

func GetUserMedalMerge(logger *logrus.Entry, db *gorm.DB, userId mysql.ID) ([]uint32, error) {
	// 缓存拿
	res, _ := common.GetUserMedalMergeCache(userId)
	if res != nil {
		return res, nil
	}

	// 数据库加载
	result, err := GetUserMedal(db, userId)
	if err != nil {
		return nil, err
	}
	logger.Infof("GetUserMedalMerge, user %d, %+v", userId, result)

	medalTypes, medalList, err := res_m.GetUserMedalLevelMap(db)
	if err != nil {
		return nil, err
	}
	logger.Infof("GetUserMedalLevelMap, user %d, medalMap %+v", medalTypes)
	logger.Infof("GetUserMedalLevelMap, user %d, medalList %+v", medalList)

	maxGrades := make(map[uint8]int, 0)
	maxMedalIds := make(map[uint8]uint32, 0)
	for _, m := range result {
		mt := medalTypes[uint64(m)]
		if mt > 0 {
			if r, ok := medalList[mt]; ok {
				for i, j := range r {
					if j == uint64(m) {
						if i+1 > maxGrades[mt] {
							maxGrades[mt] = i + 1
							maxMedalIds[mt] = m
							logger.Infof("maxGrade of %d set to %d, due to %d", mt, i+1, m)
						}
						break
					}
				}
			}
		}
	}
	logger.Infof("maxGrade %+v", maxGrades)
	logger.Infof("maxMedalIds %+v", maxMedalIds)

	mIds := result
	result = make([]uint32, 0)
	for _, m := range mIds {
		mt := medalTypes[uint64(m)]
		if mt == 0 || maxMedalIds[mt] == m {
			result = append(result, m)
		}
	}

	// 写入缓存
	common.SetUserMedalMergeCache(userId, result)
	return result, nil
}

func GetUserMedal(db *gorm.DB, userId mysql.ID) ([]uint32, error) {
	rows := make([]UserMedal, 0)
	if err := db.Model(&UserMedal{}).Where("user_id = ? AND (end_time >= NOW() or end_time is null)", userId).Find(&rows).Error; err != nil {
		return nil, err
	}
	result := make([]uint32, 0)
	for _, i := range rows {
		result = append(result, i.MedalId)
	}
	return result, nil
}