package dao

import "server/global"

type Department struct {
	Id          int       `gorm:"primarykey" from:"id" json:"ID"`
	Name        string    `json:"name" from:"name" gorm:"comment:部门名称"`
	Desc        string    `json:"desc" from:"desc" gorm:"comment:部门描述"`
	PrincipalId int       `json:"principalId" from:"principal_id" gorm:"comment:负责人id"`
	Principal   SysUser   `json:"principal" from:"principal" gorm:"foreignKey:PrincipalId;references:id;"`
	Users       []SysUser `json:"users" gorm:"-"`
	IsStart     bool      `json:"isStart" from:"is_start" gorm:"comment:是否启用"`
}

func (Department) TableName() string {
	return "department"
}

// TODO:部门查询

// QueryAllDep 查询所有部门
func QueryAllDep() (deps []Department, err error) {
	err = global.GVA_DB.Model(&Department{}).Preload("Principal").Find(&deps).Error
	return deps, err
}

// QueryDepByStart 查询启用部门
func QueryDepByStart() (deps []Department, err error) {
	err = global.GVA_DB.Model(&Department{}).Where("is_start = ?", true).Find(&deps).Error
	return deps, err
}

// QueryUsersByDepId 查询部门下的用户
func QueryUsersByDepId(depId int) (users []SysUser, err error) {
	err = global.GVA_DB.Model(&SysUser{}).Where("department_id =?", depId).Find(&users).Error
	return users, err
}

func QueryDepById(id int) (dep Department, err error) {
	err = global.GVA_DB.Model(&Department{}).Where("id = ?", id).Preload("Principal").First(&dep).Error
	return dep, err
}

// TODO:部门新增

// CreateDep 创建部门
func (d Department) CreateDep() error {
	return global.GVA_DB.Create(&d).Error
}

// TODO:部门修改

// UpdateDep 修改部门
func (d Department) UpdateDep() error {
	return global.GVA_DB.Model(&d).Where("id = ?", d.Id).Updates(&d).Error
}

// UpdateDepStatus 修改部门状态
func UpdateDepStatus(depId int, isStart bool) error {
	return global.GVA_DB.Model(&Department{}).Where("id = ?", depId).Update("is_start", isStart).Error
}

// TODO:部门删除

// DeleteDep 删除部门
func DeleteDep(depId int) error {
	return global.GVA_DB.Where("id = ?", depId).Delete(&Department{}).Error
}
