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

use app\model\User;
use app\model\UserLevel;
use app\repository\BaseRepository;


/**
 * User Level Repository
 * @package app\repository\user
 */
class UserLevelRepository extends BaseRepository
{

    /**
     * 获取所有等级列表
     * @return array
     */
    public function all(): array
    {
        return UserLevel::order('sort', 'asc')->order('id', 'asc')->select()->toArray();
    }


    /**
     * 获取全部启用的等级
     * @return array
     */
    public function allEnabled(): array
    {
        return UserLevel::where('status', 1)
            ->order('sort', 'asc')
            ->order('id', 'asc')
            ->select()
            ->toArray();
    }


    /**
     * 按主键查找等级
     * @param int $id
     * @return UserLevel|null
     */
    public function findById(int $id): ?UserLevel
    {
        $level = UserLevel::find($id);
        return $level instanceof UserLevel ? $level : null;
    }


    /**
     * 判断等级编码是否已存在
     * @param string $code      等级编码
     * @param int    $excludeId 排除的等级ID
     * @return bool
     */
    public function existsByCode(string $code, int $excludeId = 0): bool
    {
        $query = UserLevel::where('code', $code);
        if ($excludeId > 0) {
            $query->where('id', '<>', $excludeId);
        }
        return $query->find() instanceof UserLevel;
    }


    /**
     * 判断等级下是否有用户
     * @param int $id 等级ID
     * @return bool
     */
    public function hasUsers(int $id): bool
    {
        return User::where('level_id', $id)->count() > 0;
    }
}