package service

import (
	"github.com/linmadan/egglib-go/core/application"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/background/user/command"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/background/user/dto"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/background/user/query"
	"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"
	"strconv"
)

// 返回公司用户信息列表
func (usersService *UserService) AdminUserList(companyUserListQuery *query.ListAdminUserQuery) (int64, interface{}, error) {
	creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
	result, err := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
		Offset:         (companyUserListQuery.PageNumber - 1) * companyUserListQuery.PageSize,
		Limit:          companyUserListQuery.PageSize,
		OrganizationId: 0,
		DepartmentId:   0,
		UserName:       companyUserListQuery.UserName,
		DepName:        companyUserListQuery.DepartmentName,
		Phone:          "",
		UserType:       domain.UserTypeOperationAdmin,
		PullRealTime:   true,
	})

	if err != nil {
		return 0, nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	//数据转换
	cnt := int64(result.Count)
	var (
		listData = make([]dto.AdminUserDto, 0)
		item     dto.AdminUserDto
	)
	for _, v := range result.Users {
		item = dto.NewAdminUserDto(v)
		listData = append(listData, item)
	}
	return cnt, listData, nil
}

// 启用禁用用户
func (usersService *UserService) EnableAdminUser(companyUserEnableCommand *command.EnableAdminUserCommand) (interface{}, error) {
	creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(
		companyUserEnableCommand.Operator)

	var userIds []int64 = []int64{companyUserEnableCommand.UserId}
	_, err := creationUserGateway.UserBatchEnable(allied_creation_user.ReqBatchEnableUser{
		UserIds:      userIds,
		EnableStatus: companyUserEnableCommand.EnableStatus,
	})
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	return companyUserEnableCommand, err
}

func (usersService *UserService) GetAdminUser(userId int) (interface{}, error) {
	creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(
		domain.Operator{})
	result, err := creationUserGateway.UserGet(allied_creation_user.ReqGetUser{
		UserId: userId,
	})
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	userInfo := dto.NewAdminUserDto(result.UserDetail)
	return userInfo, nil
}

func (usersService *UserService) CreateAdminUser(cmd *command.AdminUserAddCommand) (interface{}, error) {
	creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(
		cmd.Operator)
	userOrg := []int64{}
	userRole := []int64{}
	initPassword := domain.DefaultPassword

	result, err := creationUserGateway.AdminUserCreate(allied_creation_user.ReqCreateUser{
		CompanyId: cmd.Operator.CompanyId,
		// 用户类型  1:企业内部用户(内部添加) 2:共创用户   1024:企业注册用户(注册添加)
		UserType: domain.UserTypeOperationAdmin,
		UserCode: cmd.UsersCode,
		UserOrg:  userOrg,
		UserRole: userRole,
		// 启用状态(启用:1 禁用:2)
		EnableStatus:   1,
		UserName:       cmd.UsersName,
		Phone:          cmd.Phone,
		Password:       initPassword,
		DepartmentName: cmd.DepartmentName,
	})
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}

	data := struct {
		UserId string `json:"userId"`
		command.AdminUserAddCommand
	}{
		UserId:              strconv.Itoa(result.UserId),
		AdminUserAddCommand: *cmd,
	}
	return data, err
}

func (usersService *UserService) UpdateAdminUser(cmd *command.AdminUserEditCommand) (interface{}, error) {
	creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(
		cmd.Operator)
	user, err := creationUserGateway.AuthUserBaseInfo(allied_creation_user.ReqAuthUserBase{
		Account: cmd.Phone,
	})
	_, err = creationUserGateway.AdminUserUpdate(allied_creation_user.ReqUpdateUser{
		UserId: cmd.UserId,
		//CooperationCompany:  cmd.CooperationCompany,
		//CooperationDeadline: time.Unix(cmd.CooperationDeadline/1000, 0),
		Email: user.UserInfo.Email,
		//EnableStatus:        user.,
		UserCode: cmd.UsersCode,
		UserName: cmd.UsersName,
		Avatar:   user.UserInfo.Avatar,
		//OrgId:               cmd.Operator.OrgId,
		Phone:          cmd.Phone,
		DepartmentName: cmd.DepartmentName,
	})
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	return cmd, err
}

func (svr *UserService) GetAdminUserInfo(operator domain.Operator) (interface{}, error) {
	creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(
		operator)

	resultUser, err := creationUserGateway.AuthUserBaseInfo(allied_creation_user.ReqAuthUserBase{
		Account: operator.Phone,
	})
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}

	users, err := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
		UserBaseId: int64(resultUser.UserBaseID),
		UserType:   domain.UserTypeOperationAdmin,
	})
	if err != nil {
		return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
	}
	if len(users.Users) == 0 {
		return nil, application.ThrowError(application.BUSINESS_ERROR, "用户不存在")
	}
	var user = map[string]interface{}{
		"userId": users.Users[0].UserId,
		"userInfo": map[string]interface{}{
			"userName":   resultUser.UserInfo.UserName,
			"userPhone":  resultUser.UserInfo.Phone,
			"userAvatar": resultUser.UserInfo.Avatar,
			"email":      resultUser.UserInfo.Email,
		},
		"department": struct{}{},
		"company":    map[string]interface{}{},
		//"im":         resultUser.Im,
		"org": struct{}{},
	}
	return user, nil
}