package res_m

import (
	"git.hilo.cn/hilo-common/resource/mysql"
	"gorm.io/gorm"
	"hilo-group/_const/enum/group_e"
)

type ResGroupTheme struct {
	mysql.Entity
	Name   string
	Url    string
	Weight int
	Status uint8
}

// 查询所有的主题
func GroupThemeGetAll(db *gorm.DB) ([]ResGroupTheme, error) {
	rows := make([]ResGroupTheme, 0)
	err := db.Model(&ResGroupTheme{}).Find(&rows).Error
	if err != nil {
		return nil, err
	}
	return rows, nil
}

// 查询上架中的主题
func GroupThemeGetAllInUse(db *gorm.DB) ([]ResGroupTheme, error) {
	rows := make([]ResGroupTheme, 0)
	err := db.Where(&ResGroupTheme{Status: group_e.SWITCH_ON}).Order("weight DESC, id").Find(&rows).Error
	if err != nil {
		return nil, err
	}
	return rows, nil
}

func (gt *ResGroupTheme) Get(db *gorm.DB) error {
	return db.Model(&ResGroupTheme{}).Where(gt).First(gt).Error
}

func (gt *ResGroupTheme) Create(db *gorm.DB) error {
	return db.Model(&gt).Create(gt).Error
}

func (gt *ResGroupTheme) Save(db *gorm.DB) error {
	return db.Save(gt).Error
}

func (gt *ResGroupTheme) SaveWeight(db *gorm.DB) error {
	return db.Model(gt).Update("weight", gt.Weight).Error
}

func (gt *ResGroupTheme) SaveStatus(db *gorm.DB) error {
	return db.Model(gt).Update("status", gt.Status).Error
}

func (gt *ResGroupTheme) SelectWeightAbove(db *gorm.DB) ([]ResGroupTheme, error) {
	rows := make([]ResGroupTheme, 0)
	if err := db.Model(&ResGroupTheme{}).Where("weight >= ?", gt.Weight).Order("weight").Find(&rows).Error; err != nil {
		return nil, err
	}
	return rows, nil
}

func (gt *ResGroupTheme) IncreaseWeight(db *gorm.DB, ids []uint64) error {
	return db.Model(&ResGroupTheme{}).Where("id in ?", ids).Update("weight", gorm.Expr("weight + 1")).Error
}

func (gt *ResGroupTheme) Switch(db *gorm.DB, status uint8) error {
	return db.Where(gt).Update("status = ?", status).Error
}