// 自动生成模板SysDictionary
package dao

import (
	"gorm.io/gorm"
	"server/global"
)

// SysDictionary 如果含有time.Time 请自行import time包
type SysDictionary struct {
	global.GVA_MODEL
	Name                 string                `json:"name" form:"name" gorm:"column:name;comment:字典名（中）"`   // 字典名（中）
	Type                 string                `json:"type" form:"type" gorm:"column:type;comment:字典名（英）"`   // 字典名（英）
	Status               *bool                 `json:"status" form:"status" gorm:"column:status;comment:状态"` // 状态
	Desc                 string                `json:"desc" form:"desc" gorm:"column:desc;comment:描述"`       // 描述
	SysDictionaryDetails []SysDictionaryDetail `json:"sysDictionaryDetails" form:"sysDictionaryDetails"`
}

func (SysDictionary) TableName() string {
	return "sys_dictionaries"
}

// TODO:字典查询

// QueryDictionaryByType 查询字典 按类型
func QueryDictionaryByType(t string) (sysDictionary SysDictionary, err error) {
	err = global.GVA_DB.First(&SysDictionary{}, "type = ?", t).Error
	return sysDictionary, err
}

// QueryDictionaryAndDetailsById 查询字典和详情 按字典id
func QueryDictionaryAndDetailsById(id uint) (sysDictionary SysDictionary, err error) {
	err = global.GVA_DB.Where("id =?", id).Preload("SysDictionaryDetails").First(&sysDictionary).Error
	return sysDictionary, err
}

// GetSysDictionary 根据id或者type获取字典单条数据
func GetSysDictionary(Type string, Id uint, flag bool) (sysDictionary SysDictionary, err error) {
	err = global.GVA_DB.Where("(type = ? OR id = ?) and status = ?", Type, Id, flag).Preload("SysDictionaryDetails", func(db *gorm.DB) *gorm.DB {
		return db.Where("status = ?", true).Order("sort")
	}).First(&sysDictionary).Error
	return
}

// GetSysDictionaryInfoList 分页获取字典列表
func GetSysDictionaryInfoList() (sysDictionaries []SysDictionary, err error) {
	err = global.GVA_DB.Find(&sysDictionaries).Error
	return
}

// TODO:字典新增

// CreateDictionary 创建字典
func (sd SysDictionary) CreateDictionary() error {
	return global.GVA_DB.Create(&sd).Error
}

// TODO:字典修改

// UpdateDictionary 修改字典
func (sd SysDictionary) UpdateDictionary() error {
	return global.GVA_DB.Model(&SysDictionary{}).Updates(&sd).Error
}

// TODO:字典删除

// DeleteDictionary 删除字典
func (sd SysDictionary) DeleteDictionary() error {
	return global.GVA_DB.Delete(&sd).Error
}
