package system

import (
	"eta/eta_api/global"
	"eta/eta_api/utils"
	"time"
)

type SysTeamAddReq struct {
	GroupId      int    `description:"大组id"`
	DepartmentId int    `description:"部门id"`
	TeamName     string `description:"分组名称,多个用英文逗号隔开"`
}

type SysTeam struct {
	GroupId      int       `orm:"column(group_id);pk" gorm:"primaryKey" description:"分组ID"`
	ParentId     int       `description:"父级Id"`
	DepartmentId int       `description:"部门id"`
	GroupName    string    `description:"分组名称"`
	CreateTime   time.Time `description:"创建时间"`
}

func GetSysTeamCount(groupId int, teamName string) (count int, err error) {
	sql := `SELECT COUNT(1) AS count FROM sys_group WHERE parent_id=? AND group_name=? `
	o := global.DbMap[utils.DbNameMaster]
	err = o.Raw(sql, groupId, teamName).Scan(&count).Error
	return
}

type SysTeamEditReq struct {
	TeamId   int    `description:"分组ID"`
	TeamName string `description:"分组名称"`
}

func GetSysTeamByName(teamName string) (item *SysGroup, err error) {
	sql := `SELECT * FROM sys_group WHERE group_name=? `
	o := global.DbMap[utils.DbNameMaster]
	err = o.Raw(sql, teamName).First(&item).Error
	return
}

func ModifySysTeam(teamName string, teamId int) (err error) {
	o := global.DbMap[utils.DbNameMaster]
	to := o.Begin()
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	sql := `UPDATE sys_group SET group_name=? WHERE group_id=? `
	err = to.Exec(sql, teamName, teamId).Error
	sql = `UPDATE admin SET group_name=? WHERE group_id=? `
	sql = utils.ReplaceDriverKeywords("", sql)
	err = to.Exec(sql, teamName, teamId).Error
	return
}

type SysTeamDeleteReq struct {
	TeamId int `description:"小组ID"`
}

type SysTeamList struct {
	GroupId    int       `orm:"column(group_id);pk" gorm:"primaryKey" json:"DepartmentId" description:"小组ID"`
	ParentId   int       `json:"GroupId" description:"小组Id"`
	GroupName  string    `json:"DepartmentName" description:"分组名称"`
	CreateTime time.Time `description:"创建时间"`
}

func GetSysTeamByDepartmentId(groupId int) (items []*SysTeamList, err error) {
	sql := `SELECT * FROM sys_group WHERE parent_id=? ORDER BY sort ASC, create_time ASC`
	o := global.DbMap[utils.DbNameMaster]
	err = o.Raw(sql, groupId).Find(&items).Error
	return
}

func ClearSysUserTeam(groupId int) (err error) {
	sql := `UPDATE admin SET group_id=0,group_name='' WHERE group_id=? `
	sql = utils.ReplaceDriverKeywords("", sql)
	o := global.DbMap[utils.DbNameMaster]
	err = o.Exec(sql, groupId).Error
	return
}