<?php

namespace app\model;


use app\BaseModel;
use think\Model;
use think\model\Collection;
use think\model\concern\SoftDelete;
use think\model\relation\BelongsToMany;

/**
 * 系统角色模型
 * @property int $role_id
 * @property string $role_name
 * @property string $role_code
 * @property string $comments
 * @property int $deleted
 * @property string $create_time
 * @property string $update_time
 * @property string $delete_time
 * @property SysUser[]|Collection $users      角色存在多个用户
 * @property SysMenu[]|Collection $menus      角色存在多个菜单
 */
class SysRole extends BaseModel
{
    use SoftDelete;

    protected $name = "sys_role";
    protected $pk = "role_id";


    // 关联定义
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(SysRole::class, SysUserRole::class, 'role_id', 'user_id');
    }

    public function menus(): BelongsToMany
    {
        return $this->belongsToMany(SysMenu::class, SysRoleMenu::class, 'menu_id', 'role_id');
    }

    // 搜索定义
    public function searchRoleNameAttr($query, $value): void
    {
        $value != '' && $query->where('role_name', 'like', '%' . $value . '%');
    }

    public function searchRoleCodeAttr($query, $value): void
    {
        $value != '' && $query->where('role_code', 'like', '%' . $value . '%');
    }

    public function searchCommentsAttr($query, $value): void
    {
        $value != '' && $query->where('comments', 'like', '%' . $value . '%');
    }

    // 事件定义

    public static function onAfterInsert(Model|SysRole $model): void
    {
        security_log_record([SysRole::class, 'onAfterInsert'], "添加了新角色", $model);
    }

    public static function onAfterDelete(SysRole $model): void
    {
        security_log_record([SysRole::class, 'onAfterDelete'], "角色{$model->role_name}被删除", $model);
    }
}