<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\repository\admin;

use app\model\AdminRole;
use app\model\AdminRoleUser;
use app\repository\BaseRepository;
use think\Collection;


/**
 * Role Repository
 * @package app\repository\admin
 */
class RoleRepository extends BaseRepository
{

    /**
     * 获取所有启用角色的列表
     * @return Collection
     */
    public function activeList(): Collection
    {
        return AdminRole::where('status', 1)->order('id', 'desc')->select();
    }


    /**
     * 按ID查找角色
     * @param int $id
     * @return AdminRole|null
     */
    public function findById(int $id): ?AdminRole
    {
        $role = AdminRole::find($id);
        return $role instanceof AdminRole ? $role : null;
    }


    /**
     * 分页查询角色
     * @param array $filters
     * @param int $limit
     * @return mixed
     */
    public function paginate(array $filters, int $limit)
    {
        $query = AdminRole::order('id', 'desc');

        $keyword = trim((string)($filters['keyword'] ?? ''));
        if ($keyword !== '') {
            $query->where('name|code', 'like', "%{$keyword}%");
        }
        if (is_numeric($filters['status'] ?? null)) {
            $query->where('status', (int)$filters['status']);
        }

        return $query->paginate($limit);
    }


    /**
     * 按编码查找角色
     * @param string $code
     * @return AdminRole|null
     */
    public function findByCode(string $code): ?AdminRole
    {
        $role = AdminRole::where('code', $code)->find();
        return $role instanceof AdminRole ? $role : null;
    }


    /**
     * 保存角色
     * @param AdminRole $role
     * @return void
     */
    public function save(AdminRole $role): void
    {
        $role->save();
    }


    /**
     * 删除角色
     * @param AdminRole $role
     * @return void
     */
    public function delete(AdminRole $role): void
    {
        $role->delete();
    }


    /**
     * 判断角色是否被用户使用
     * @param int $roleId
     * @return bool
     */
    public function inUse(int $roleId): bool
    {
        return AdminRoleUser::where('role_id', $roleId)->count() > 0;
    }
}