<?php

namespace App\Http\Controllers\Core;

use Illuminate\Support\Facades\Config;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Controller;

/**
 * Class Auth
 * @package App\Http\Controllers\Core
 * @method static auth()
 */
class Auth extends Controller
{
    private static $instance = null;
    private $uid = null;


    public const ADMINS = [
        10001,
        10002,
        10007,
        91031,
        94302,
        98047,
        62726,
        103143,
        10771042,
        11386073,
        270382
    ];


    /**
     * @param $method
     * @param $params
     * @return mixed
     */
    public static function __callStatic($method, $params)
    {
        if (is_null(self::$instance)) {
            self::$instance = new Auth();
        }
        return call_user_func_array([self::$instance, "p{$method}"], $params);
    }

    /**
     * 用户认证
     * @return mixed
     * @throws JWTException
     */
    private function pauth()
    {
        if (is_null($this->uid)) {
            try {
                if (!$auth = JWTAuth::parseToken()->authenticate()) {
                    throw new JWTException("请先授权登陆", 401);
                }
            } catch (JWTException $e) {
                throw new JWTException("登陆已过期，请重新授权登陆", 401);
            }
            $debug_uid = Redis::hget("fpdx_admin_debug", $auth->uid);
            if (!empty($debug_uid)) {
                $uid = $debug_uid;
            } else {
                $uid = $auth->uid;
            }
            $this->uid = $uid;
            Config::set("uid", $this->uid);
            return $this->uid;
        }
        return $this->uid;
    }

    /**
     * @return mixed
     * @throws JWTException
     */
    public static function adminAuth()
    {
        try {
            if (!$auth = JWTAuth::parseToken()->authenticate()) {
                throw new JWTException("请先授权登陆", 401);
            }
        } catch (JWTException $e) {
            throw new JWTException("登陆已过期，请重新授权登陆", 401);
        }
        $uid = $auth->uid;
        if (in_array($uid, self::ADMINS)) {
            return $uid;
        } else {
            throw new JWTException("权限不足", 403);
        }
    }
}
