package system

import (
	"server/global"
	"time"
)

type SysAuthority struct {
	CreatedAt       time.Time       // 创建时间
	UpdatedAt       time.Time       // 更新时间
	DeletedAt       *time.Time      `sql:"index"`
	AuthorityId     uint            `json:"authorityId" gorm:"not null;unique;primary_key;comment:角色ID;size:90"` // 角色ID
	AuthorityName   string          `json:"authorityName" gorm:"comment:角色名"`                                    // 角色名
	ParentId        *uint           `json:"parentId" gorm:"comment:父角色ID"`                                       // 父角色ID
	DataAuthorityId []*SysAuthority `json:"dataAuthorityId" gorm:"many2many:sys_data_authority_id;"`
	Children        []SysAuthority  `json:"children" gorm:"-"`
	SysBaseMenus    []SysBaseMenu   `json:"menus" gorm:"many2many:sys_authority_menus;"`
	Users           []SysUser       `json:"-" gorm:"many2many:sys_user_authority;"`
	DefaultRouter   string          `json:"defaultRouter" gorm:"comment:默认菜单;default:dashboard"` // 默认菜单(默认dashboard)
}

func (SysAuthority) TableName() string {
	return "sys_authorities"
}

// TODO:角色查询

// QueryAuthorityById 查询角色 按id
func QueryAuthorityById(authorityId uint) (sysAuthority SysAuthority, err error) {
	err = global.GVA_DB.Where("authority_id = ?", authorityId).First(&sysAuthority).Error
	return
}

// GetAuthorityInfoList 分页获取角色列表
func GetAuthorityInfoList(limit, offset int) (sysAuthority []SysAuthority, total int64, err error) {
	db := global.GVA_DB.Model(&SysAuthority{})
	if err = db.Where("parent_id = ?", "0").Count(&total).Error; total == 0 || err != nil {
		return
	}
	var authority []SysAuthority
	err = db.Limit(limit).Offset(offset).Preload("DataAuthorityId").Where("parent_id = ?", "0").Find(&authority).Error

	return authority, total, err
}

// GetAuthorityInfo 获取所有角色信息
func (sa SysAuthority) GetAuthorityInfo() (sysAuthority SysAuthority, err error) {
	err = global.GVA_DB.Preload("DataAuthorityId").Where("authority_id = ?", sa.AuthorityId).First(&sysAuthority).Error
	return sysAuthority, err
}

// TODO:角色新增
// TODO:角色修改

// UpdateAuthority 修改角色
func (sa SysAuthority) UpdateAuthority() error {
	return global.GVA_DB.Model(&SysAuthority{}).Updates(&sa).Error
}

// TODO:角色删除
