<?php

namespace app\common\model\Menu;

use app\BaseModel;
use think\Exception;
use think\facade\Config;
use think\model\concern\SoftDelete;
use think\model\relation\BelongsToMany;
use think\model\relation\HasMany;
use think\model\relation\HasOne;

class Menu extends BaseModel
{
    use SoftDelete;
    // 删除字段
    protected $deleteTime = 'menu_delete_time';
    // 设置主键名
    protected $pk = 'menu_guid';
    // 设置废弃字段
    protected $disuse = [];
    // 设置字段信息
    protected $schema = [
        'menu_id'          => 'int',
        'menu_parent_guid'        => 'string',
        'menu_name'        => 'string',
        'menu_url'        => 'string',
        'menu_index'        => 'int',
        'menu_order'        => 'int',
        'menu_status'      => 'int',
        'menu_show'      => 'int',
        'menu_create_time' => 'datetime',
        'menu_create_user_guid' => 'string',
        'menu_update_time' => 'datetime',
        'menu_update_user_guid' => 'string',
        'menu_delete_time' => 'datetime',
        'menu_delete_user_guid' => 'string',
        'menu_guid' => 'string',
    ];
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'datetime';
    // 创建时间
    protected $createTime = 'menu_create_time';
    // 修改时间
    protected $updateTime = 'menu_update_time';
    /**
     * 状态 启用
     */
    const STATUS_ENABLE = 1;
    /**
     * 状态 禁用
     */
    const STATUS_DISABLE = 2;
    // 状态查询范围
    public function scopeStatus($query, $status = self::STATUS_ENABLE)
    {
        $query->where('menu_status', $status);
    }

    /**
     * 新增前
     *
     * @date 2022-02-22
     * @example
     * @author admin
     * @since 1.0.0
     */
    public static function onBeforeInsert(self $model): void
    {
        $model->menu_status = self::STATUS_ENABLE;
        $model->completeCreateField();
    }

    /**
     * 更新前
     *
     * @date 2022-02-28
     * @example
     * @author admin
     * @since 1.0.0
     */
    public static function onBeforeUpdate(self $model): void
    {
        $model->completeUpdateField();
    }

    /**
     * 删除前
     *
     * @date 2022-02-28
     * @example
     * @author admin
     * @since 1.0.0
     */
    public static function onBeforeDelete(self $model): void
    {
        $model->completeDeleteField();
    }

    /**
     * 获取状态
     *
     * @date 2022-02-22
     * @example
     * @author admin
     * @since 1.0.0
     */
    public function getMenuStatusTextAttr(): string
    {
        return [
            self::STATUS_ENABLE => '启用',
            self::STATUS_DISABLE => '停用'
        ][$this->menu_status];
    }

    /**
     * 菜单接口
     *
     * @date 2022-03-07
     * @example
     * @author admin
     * @since 1.0.0
     */
    public function apis(): HasMany
    {
        return $this->hasMany(MenuApi::class, 'menu_guid');
    }
}
