package groupPower_m

import (
	"git.hilo.cn/hilo-common/domain"
	"git.hilo.cn/hilo-common/resource/mysql"
	"git.hilo.cn/hilo-common/utils"
)

type GroupPowerInfo struct {
	mysql.Entity
	GroupUid    string
	Name        string
	Nameplate   string
	Declaration string
	Icon        string
	Status      int
}

func (GroupPowerInfo) TableName() string {
	return "group_power"
}

// 批量获取家族信息
func MGetGroupPowerInfoMap(model *domain.Model, groupPowerIds []mysql.ID) (map[mysql.ID]GroupPowerInfo, error) {
	var rows []GroupPowerInfo
	res := make(map[mysql.ID]GroupPowerInfo)
	if err := model.DB().Model(GroupPowerInfo{}).Where("id in ?", groupPowerIds).Find(&rows).Error; err != nil {
		model.Log.Errorf("MGetGroupPowerInfo fail:%v", err)
		return res, err
	}
	for i, v := range rows {
		rows[i].Icon = utils.MakeFullUrl(rows[i].Icon) // 拼接url
		res[v.ID] = rows[i]
	}
	return res, nil
}

// 批量获取家族成员
func MGetGroupPowerUsers(model *domain.Model, groupPowerIds []mysql.ID) (map[mysql.ID][]*GroupPowerUser, error) {
	var users []*GroupPowerUser
	res := make(map[mysql.ID][]*GroupPowerUser)
	if err := model.DB().Model(GroupPowerUser{}).Where("group_power_id in ?", groupPowerIds).Find(&users).Error; err != nil {
		model.Log.Errorf("MGetGroupPowerUsers fail:%v", err)
		return res, err
	}
	for i, v := range users {
		res[v.GroupPowerId] = append(res[v.GroupPowerId], users[i])
	}
	return res, nil
}

// 获取家族成员
func GetGroupPowerUser(model *domain.Model, groupPowerId mysql.ID) ([]*GroupPowerUser, error) {
	m, err := MGetGroupPowerUsers(model, []mysql.ID{groupPowerId})
	if err != nil {
		return nil, err
	}
	return m[groupPowerId], nil
}

// 分批获取所有家族成员
func BatchGetAllGroupPowerUsers(model *domain.Model, lastId mysql.ID, limit int) ([]mysql.ID, mysql.ID, error) {
	var res []GroupPowerUser
	var userIds []mysql.ID
	var nextLastId mysql.ID
	if err := model.DB().Model(GroupPowerUser{}).
		Where("id > ?", lastId).Order("id asc").Limit(limit).Find(&res).Error; err != nil {
		model.Log.Errorf("BatchGetAllGroupPowerUsers fail:%v", err)
		return userIds, 0, err
	}
	for _, v := range res {
		userIds = append(userIds, v.UserId)
		nextLastId = v.ID
	}
	return userIds, nextLastId, nil
}