group_im.go 1.49 KB
Newer Older
chenweijian's avatar
chenweijian 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 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
package group_m

import (
	"git.hilo.cn/hilo-common/domain"
	"hilo-group/_const/enum/group_e"
	"hilo-group/myerr"
	"math/rand"
	"time"
)

type GroupIm struct {
	Id       uint64
	Provider group_e.GroupProvider
	Prob     int
	StartIdx int `gorm:"-"'`
	EndIdx   int `gorm:"-"`
}

type GroupImLog struct {
	ImGroupId string
	Provider  group_e.GroupProvider
}

func GetGroupImConf(model *domain.Model) ([]*GroupIm, error) {
	rows := make([]*GroupIm, 0)
	if err := model.Db.Table("group_im").Find(&rows).Error; err != nil {
		return nil, myerr.WrapErr(err)
	}
	return rows, nil
}

func GetRandomImProvider(model *domain.Model) group_e.GroupProvider {
	var res group_e.GroupProvider
	confList, err := GetGroupImConf(model)
	if err != nil {
		model.Log.Errorf("GetRandomImProvider err:%v", err)
		return res
	}
	conf := GetRandomGroupImConf(confList)
	return conf.Provider
}

func GetRandomGroupImConf(confList []*GroupIm) *GroupIm {
	var res *GroupIm
	var max int
	for i, v := range confList {
		if v.Prob > 0 {
			confList[i].StartIdx = max
			max += v.Prob
			confList[i].EndIdx = max
		}
	}
	rand.Seed(time.Now().UnixNano())
	randNum := rand.Intn(max)
	for _, v := range confList {
		if v.StartIdx <= randNum && randNum < v.EndIdx {
			res = v
		}
	}
	return res
}

func CreateGroupImLog(model *domain.Model, imGroupId string, provider group_e.GroupProvider) error {
	if err := model.Db.Model(GroupImLog{}).Create(GroupImLog{ImGroupId: imGroupId, Provider: provider}).Error; err != nil {
		return myerr.WrapErr(err)
	}
	return nil
}