package services

import (
	"eta/eta_mobile/models/company"
	"eta/eta_mobile/models/system"
	"fmt"
)

// CheckAdminIsSameBigGroup 判断是否两个系统用户是否同一个大组内
func CheckAdminIsSameBigGroup(adminInfo1, adminInfo2 *system.Admin) (isSame bool, err error) {
	// 如果销售和创建人是同一个小组
	if adminInfo1.GroupId == adminInfo2.GroupId {
		isSame = true
		return
	}
	var admin1BigGroupId, admin2BigGroupId int

	//获取第一个系统用户的大组id
	{
		//获取该账号的大组id
		pid, tmpErr := company.GetParentIdFromGroup(adminInfo1.GroupId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		if pid != nil && *pid > 0 {
			//该账号放在了三级分组下
			admin1BigGroupId = *pid
		} else {
			//该账号放在了二级分组下
			admin1BigGroupId = adminInfo1.GroupId
		}
	}

	//获取第二个系统用户的大组id
	{
		//获取该账号的大组id
		pid, tmpErr := company.GetParentIdFromGroup(adminInfo2.GroupId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		if pid != nil && *pid > 0 {
			//该账号放在了三级分组下
			admin2BigGroupId = *pid
		} else {
			//该账号放在了二级分组下
			admin2BigGroupId = adminInfo2.GroupId
		}
	}

	if admin1BigGroupId == admin2BigGroupId {
		isSame = true
		return
	}
	return
}

func BuildGroupTree(rootNode *system.GroupNode, groupList []*system.SysFullGroup, depth, current int) {
	if current >= depth {
		return
	}
	for _, group := range groupList {
		if group.ParentId == rootNode.GroupId {
			childNode := &system.GroupNode{
				GroupId:   group.GroupId,
				GroupName: group.GroupName,
			}
			BuildGroupTree(childNode, groupList, depth, current+1)
			rootNode.Child = append(rootNode.Child, childNode)
		}
	}
}

func GetGroupName(nodes []*system.GroupNode, groupId int) (find bool, groupName string) {
	for _, child := range nodes {
		if child.GroupId == groupId {
			return true, child.GroupName
		}
		if len(child.Child) > 0 {
			find, subGroupName := GetGroupName(child.Child, groupId)
			if find {
				groupName = fmt.Sprintf("%s/%s", child.GroupName, subGroupName)
				return true, groupName
			}
		}
	}
	return false, ""
}
