package internal

import (
	"context"
	"github.com/gogf/gf/v2/util/guid"
	"yx-dataset-server/app/errors"
	"yx-dataset-server/app/model"
	"yx-dataset-server/app/schema"
)

// NewUserRole 创建UserRole
func NewUserRole(mUserRole model.IUserRole) *UserRole {
	return &UserRole{
		UserRoleModel: mUserRole,
	}
}

// UserRole 创建UserRole对象
type UserRole struct {
	UserRoleModel model.IUserRole
}

// Query 查询数据
func (a *UserRole) Query(ctx context.Context, params schema.UserRoleQueryParam, opts ...schema.UserRoleQueryOptions) (*schema.UserRoleQueryResult, error) {
	return a.UserRoleModel.Query(ctx, params, opts...)
}

// Get 查询指定数据
func (a *UserRole) Get(ctx context.Context, recordID string, opts ...schema.UserRoleQueryOptions) (*schema.UserRole, error) {
	item, err := a.UserRoleModel.Get(ctx, recordID, opts...)
	if err != nil {
		return nil, err
	} else if item == nil {
		return nil, errors.ErrNotFound
	}
	return item, nil
}

func (a *UserRole) getUpdate(ctx context.Context, recordID string) (*schema.UserRole, error) {
	return a.Get(ctx, recordID)
}

// Create 创建数据
func (a *UserRole) Create(ctx context.Context, item schema.UserRole) (*schema.UserRole, error) {
	item.RecordId = guid.S()
	err := a.UserRoleModel.Create(ctx, item)
	if err != nil {
		return nil, err
	}
	return a.getUpdate(ctx, item.RecordId)
}

// Update 更新数据
func (a *UserRole) Update(ctx context.Context, recordID string, item schema.UserRole) (*schema.UserRole, error) {
	oldItem, err := a.UserRoleModel.Get(ctx, recordID)
	if err != nil {
		return nil, err
	} else if oldItem == nil {
		return nil, errors.ErrNotFound
	}
	err = a.UserRoleModel.Update(ctx, recordID, item)
	if err != nil {
		return nil, err
	}
	return a.getUpdate(ctx, recordID)
}

// Delete 删除数据
func (a *UserRole) Delete(ctx context.Context, recordID string) error {
	oldItem, err := a.UserRoleModel.Get(ctx, recordID)
	if err != nil {
		return err
	} else if oldItem == nil {
		return errors.ErrNotFound
	}

	return a.UserRoleModel.Delete(ctx, recordID)
}

// UpdateStatus 更新状态
func (a *UserRole) UpdateStatus(ctx context.Context, recordID string, status int) error {
	oldItem, err := a.UserRoleModel.Get(ctx, recordID)
	if err != nil {
		return err
	} else if oldItem == nil {
		return errors.ErrNotFound
	}
	return a.UserRoleModel.UpdateStatus(ctx, recordID, status)
}
