package system

import (
	"github.com/beego/beego/v2/client/orm"
	"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" 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 := orm.NewOrm()
	err = o.Raw(sql, groupId, teamName).QueryRow(&count)
	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 := orm.NewOrm()
	err = o.Raw(sql, teamName).QueryRow(&item)
	return
}

func ModifySysTeam(teamName string, teamId int) (err error) {
	o := orm.NewOrm()
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	sql := `UPDATE sys_group SET group_name=? WHERE group_id=? `
	_, err = to.Raw(sql, teamName, teamId).Exec()
	sql = `UPDATE admin SET group_name=? WHERE group_id=? `
	_, err = to.Raw(sql, teamName, teamId).Exec()
	return
}

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

type SysTeamList struct {
	GroupId    int       `orm:"column(group_id);pk" 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 := orm.NewOrm()
	_, err = o.Raw(sql, groupId).QueryRows(&items)
	return
}

func ClearSysUserTeam(groupId int) (err error) {
	sql := `UPDATE admin SET group_id=0,group_name='' WHERE group_id=? `
	o := orm.NewOrm()
	_, err = o.Raw(sql, groupId).Exec()
	return
}
