package data

import (
	"eta/eta_api/models/data_manage"
	"eta/eta_api/models/system"
	"fmt"
)

func GetManualSysUser(keyWord string) (list []*data_manage.ManualSysUser, err error) {
	//departmentId := 1
	list = make([]*data_manage.ManualSysUser, 0)
	departmentItems, err := system.GetSysDepartmentAll()
	if err != nil {
		return list, err
	}
	for _, dv := range departmentItems {
		department := new(data_manage.ManualSysUser)
		department.ItemId = dv.DepartmentId * 10000
		department.ItemName = dv.DepartmentName

		fmt.Println(department.ItemId, department.ItemName)
		//GetSysuserList

		var condition string
		var pars []interface{}

		if keyWord != "" {
			condition += ` AND (real_name LIKE '%` + keyWord + `%' OR admin_name LIKE '%` + keyWord + `%' OR mobile LIKE '%` + keyWord + `%' )  `
		}
		sysUsers, err := system.GetSysUserItems(condition, pars)
		if err != nil {
			return list, err
		}

		groups, err := system.GetSysGroupByDepartmentId(dv.DepartmentId)
		if err != nil {
			return list, err
		}
		dg := make([]*data_manage.ManualSysUser, 0)
		for _, v := range groups {
			group := new(data_manage.ManualSysUser)
			group.ItemId = v.DepartmentId * 100000
			group.ItemName = v.GroupName

			for _, sv := range sysUsers {
				user := new(data_manage.ManualSysUser)
				user.ItemId = sv.AdminId
				user.ItemName = sv.RealName
				if sv.GroupId == v.GroupId {
					group.Children = append(group.Children, user)
				}
			}
			if len(group.Children) > 0 {
				dg = append(dg, group)
			}
		}

		if len(groups) <= 0 {
			group := new(data_manage.ManualSysUser)
			group.ItemId = dv.DepartmentId * 100000
			group.ItemName = "无分组"

			for _, sv := range sysUsers {
				user := new(data_manage.ManualSysUser)
				user.ItemId = sv.AdminId
				user.ItemName = sv.RealName
				if sv.DepartmentId == dv.DepartmentId && sv.GroupId == 0 {
					group.Children = append(group.Children, user)
				}
			}
			if len(group.Children) > 0 {
				dg = append(dg, group)
			}
		}

		if len(dg) > 0 {
			department.Children = dg
			list = append(list, department)
		}
	}
	return
}
