package user

import (
	"github.com/linmadan/egglib-go/core/application"
	"github.com/linmadan/egglib-go/utils/tool_funs"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/factory"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/user/query"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/domain"
)

type UserService struct{}

func (us *UserService) ListUsers(listUserQuery *query.ListUserQuery) (interface{}, error) {
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
	}()
	userRepo := factory.CreateUserRepository(map[string]interface{}{"transactionContext": transactionContext})
	count, list, err := userRepo.Find(map[string]interface{}{
		"companyId": listUserQuery.CompanyId,
		"name":      listUserQuery.Name,
		"status":    domain.UserStatusEnable,
	})
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	if err := transactionContext.CommitTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	return tool_funs.SimpleWrapGridMap(int64(count), list), nil
}

func (us *UserService) ListByDepartment(in *query.ListByDepartmentQuery) (interface{}, error) {
	transactionContext, err := factory.ValidateStartTransaction(in)
	if err != nil {
		return nil, err
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()

	userRepo := factory.CreateUserRepository(map[string]interface{}{"transactionContext": transactionContext})
	inMap := tool_funs.SimpleStructToMap(in)
	if in.DepartmentId == 0 {
		delete(inMap, "departmentId") // 删除部门ID字段
	}
	count, list, err := userRepo.Find(inMap)
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	if err := transactionContext.CommitTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	return tool_funs.SimpleWrapGridMap(int64(count), list), nil
}