<?php

declare(strict_types=1);

namespace app\common\traits;

use app\common\model\Token;
use think\helper\Arr;

trait Auth
{
    /**
     * 请求
     *
     * @var \app\Request
     * @date 2022-05-14
     * @example
     * @author admin
     * @since 1.0.0
     */
    private $request = null;

    /**
     * 忽略登录
     *
     * @var array
     * @date 2022-05-14
     * @example
     * @author admin
     * @since 1.0.0
     */
    private $ignoreLogin = [];

    /**
     * 是否忽略登录
     *
     * @return boolean
     */
    private function isIgnoreLogin(): bool
    {
        $request = $this->request;
        $gc = $request->controller();
        $ga = $request->action();
        $ignoreLogin = Arr::get($this->ignoreLogin, $gc, []);
        if (!is_array($ignoreLogin)) {
            $ignoreLogin = [];
        }
        foreach ($ignoreLogin as $action) {
            if ($action == '*' || $action == $ga) {
                return true;
            }
        }
        return false;
    }

    /**
     * 验证用户权限
     *
     * @return boolean
     * @date 2022-05-14
     * @example
     * @author admin
     * @since 1.0.0
     */
    private function validateUser(): bool
    {
        return $this->validateMenuApi(
            Token::getCurrentUser()->getUserMenu()
        );
    }

    /**
     * 验证菜单接口
     *
     * @return boolean
     * @date 2022-05-14
     * @example
     * @author admin
     * @since 1.0.0
     */
    private function validateMenuApi(array $menus): bool
    {
        $apis = [];
        foreach ($menus as $menu) {
            $apis = array_merge($apis, explode(',', $menu['menu_api_url'] ?? ''));
        }
        return $this->validateApi($apis);
    }

    /**
     * 验证接口
     *
     * @param array $apis
     * @return boolean
     * @date 2022-05-14
     * @example
     * @author admin
     * @since 1.0.0
     */
    private function validateApi(array $apis): bool
    {
        $request = $this->request;
        $apis = array_values(array_filter(array_unique($apis)));
        $api = join('/', [
            $request->controller(),
            $request->action()
        ]);
        return in_array($api, $apis);
    }
}
