package dto

import (
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/service_gateway/allied_creation_user"
)

type OrgItem struct {
	OrgId         string `json:"orgId"`
	OrgName       string `json:"orgName"`
	ParentId      string `json:"parentId"`
	IsOrg         int    `json:"isOrg"`
	OrgCode       string `json:"orgCode"`
	ParentDepName string `json:"parentDepName"`
	OrgStatus     int    `json:"orgStatus"`
}

type DepartmentUsersDto struct {
	Departments []*Department `json:"departments,omitempty"`
	Users       []interface{} `json:"users,omitempty"`
}

type Department struct {
	DepartmentID   int64  `json:"departmentId,string"`
	DepartmentName string `json:"departmentName"`
	Users          []User `json:"users"`
}

type User struct {
	UserID   int                    `json:"userId,string"`
	UserCode string                 `json:"userCode"`
	UserInfo map[string]interface{} `json:"userInfo"`
}

func (dto *DepartmentUsersDto) LoadDto(dataType int, subDepartment *allied_creation_user.DataOrgGetSubDepartment, userSearch *allied_creation_user.DataUserSearch) error {
	if dataType == 1 {
		for i := range userSearch.Users {
			user := userSearch.Users[i]
			dto.Users = append(dto.Users, map[string]interface{}{
				"userId":     user.UserId,
				"userInfo":   user.UserInfo,
				"department": user.Department,
			})
		}
		return nil
	}
	var mapDepartment = make(map[int64]*Department)
	mapDepartment[-1] = &Department{
		DepartmentID:   -1,
		DepartmentName: "共创部门",
		Users:          make([]User, 0),
	}
	dto.Departments = append(dto.Departments, mapDepartment[-1])
	for i := range subDepartment.Orgs {
		org := subDepartment.Orgs[i]
		dep := &Department{
			DepartmentID:   int64(org.OrgID),
			DepartmentName: org.OrgName,
			Users:          make([]User, 0),
		}
		dto.Departments = append(dto.Departments, dep)
		mapDepartment[dep.DepartmentID] = dep
	}

	for i := range userSearch.Users {
		user := userSearch.Users[i]
		u := User{
			UserID:   user.UserId,
			UserCode: user.UserCode,
			UserInfo: map[string]interface{}{
				"userName": user.UserInfo.UserName,
				"phone":    user.UserInfo.Phone,
			},
		}
		if (user.UserType & domain.UserTypeCooperation) > 0 {
			mapDepartment[-1].Users = append(mapDepartment[-1].Users, u)
			continue
		}
		if v, ok := mapDepartment[int64(user.Department.DepartmentId)]; ok {
			v.Users = append(v.Users, u)
		}
	}
	return nil
}