<?php

namespace app\model;


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

/**
 * @property int $menu_id
 * @property int $parent_id
 * @property string $title
 * @property string $path
 * @property string $component
 * @property int $menu_type
 * @property int $sort_number
 * @property string $authority
 * @property string $icon
 * @property int $hide
 * @property string $meta
 * @property int $deleted
 * @property string $create_time
 * @property string $update_time
 * @property string $delete_time
 */
class SysMenu extends BaseModel
{
    use SoftDelete;


    protected $name = "sys_menu";
    protected $pk = "menu_id";

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

    // 事件定义
    public static function onBeforeRestore(Model|SysMenu $model)
    {
        $model->set('deleted', 0);
        return true;
    }

    public static function onBeforeDelete(Model|SysMenu $model): bool
    {
        $model->set('deleted', 1);
        return true;
    }

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

    public static function onAfterDelete(Model|SysMenu $model): void
    {
        security_log_record([SysMenu::class, 'onAfterDelete'], "菜单{$model->title}被删除", $model);
    }

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

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

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