package model

import (
	"context"
	"gorm.io/gorm"
	"yx-dataset-server/app/errors"
	"yx-dataset-server/app/model/entity"
	"yx-dataset-server/app/schema"
)

// NewRole 创建Role存储实例
func NewRole(db *gorm.DB) *Role {
	return &Role{db}
}

// Role Role存储
type Role struct {
	db *gorm.DB
}

func (a *Role) getQueryOption(opts ...schema.RoleQueryOptions) schema.RoleQueryOptions {
	var opt schema.RoleQueryOptions
	if len(opts) > 0 {
		opt = opts[0]
	}
	return opt
}

// Query 查询数据
func (a *Role) Query(ctx context.Context, params schema.RoleQueryParam, opts ...schema.RoleQueryOptions) (*schema.RoleQueryResult, error) {
	db := entity.GetRoleDB(ctx, a.db)
	if v := params.Code; v != "" {
		db = db.Where("code=?", v)
	}
	if v := params.LikeCode; v != "" {
		db = db.Where("code LIKE ?", "%"+v+"%")
	}
	if v := params.LikeName; v != "" {
		db = db.Where("name LIKE ?", "%"+v+"%")
	}
	if v := params.Status; v > 0 {
		db = db.Where("status=?", v)
	}
	if v := params.RecordIDs; len(v) > 0 {
		db = db.Where("record_id in (?)", v)
	}
	db = db.Order("id DESC")

	opt := a.getQueryOption(opts...)
	var list entity.Roles
	pr, err := WrapPageQuery(ctx, db, opt.PageParam, &list)
	if err != nil {
		return nil, errors.ErrDBServerInternalError
	}
	qr := &schema.RoleQueryResult{
		PageResult: pr,
		Data:       list.ToSchemaRoles(),
	}

	return qr, nil
}

// Get 查询指定数据
func (a *Role) Get(ctx context.Context, recordID string, opts ...schema.RoleQueryOptions) (*schema.Role, error) {
	db := entity.GetRoleDB(ctx, a.db).Where("record_id=?", recordID)
	var item entity.Role
	ok, err := FindOne(ctx, db, &item)
	if err != nil {
		return nil, errors.ErrDBServerInternalError
	} else if !ok {
		return nil, nil
	}

	return item.ToSchemaRole(), nil
}

// Create 创建数据
func (a *Role) Create(ctx context.Context, item schema.Role) error {
	Role := entity.SchemaRole(item).ToRole()
	result := entity.GetRoleDB(ctx, a.db).Create(Role)
	if err := result.Error; err != nil {
		return errors.ErrDBServerInternalError
	}
	return nil
}

// Update 更新数据
func (a *Role) Update(ctx context.Context, recordID string, item schema.Role) error {
	Role := entity.SchemaRole(item).ToRole()
	result := entity.GetRoleDB(ctx, a.db).Where("record_id=?", recordID).Omit("record_id", "creator").Updates(Role)
	if err := result.Error; err != nil {
		return errors.ErrDBServerInternalError
	}
	return nil
}

// Delete 删除数据
func (a *Role) Delete(ctx context.Context, recordID string) error {
	result := entity.GetRoleDB(ctx, a.db).Where("record_id=?", recordID).Delete(entity.Role{})
	if err := result.Error; err != nil {
		return errors.ErrDBServerInternalError
	}
	return nil
}
