<?php
declare (strict_types=1);

namespace app\admin\middleware;

use Closure;
use app\Request;
use think\exception\HttpResponseException;
use think\facade\Db;
use think\Response;

/**
 * 全局权限校验
 * Class WriteLog
 * @package app\middleware
 */
class Auth
{
    protected static int $CODE_SUCCESS = 0; //成功
    protected static int $CODE_ERR = 999; //成功

    /**
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next): mixed
    {
        /*if ($request->admin->is_pass != 1 && $request->admin->is_root != 1 || $request->admin->valid != 1 && $request->admin->is_root != 1) {
            $res = returnFormatError('无权限', 401);
            throw new HttpResponseException(Response::create($res, "json"));
        }*/
       /* $isPass = false;
        $role_id = $request->admin->role_id;
        $test = Db::table('role')->where('id', $role_id)->find();
        $codes = explode(',', $test['codes']);
        $list = config('permission_action');
        $ctrl = $request->controller();
        $fun = $request->action();
//        dump($ctrl.'_'.$fun);
        foreach ($list as $k => $v) {
            if ($ctrl . '_' . $fun == $k) {
//                dump('a=>'.$v);
                foreach ($codes as $kk => $vv) {
                    if ($v == $vv) {
//                        dump('b=>'.$vv);
                        $isPass = true;
                        break;
                    }
                }
            }
        }
        // || $fun=='import' || $fun=='export' || $fun=='pass' || $fun=='rePass'
        if ($request->admin->is_root == 1 || $fun == 'init' || $fun == 'initDetail') {
            $isPass = true;
        }
        // 添加中间件执行代码
        $admin = $request->admin;
        if (!$isPass) {
            $res = returnFormatError('无权限', 555);
            throw new HttpResponseException(Response::create($res, "json"));
        }*/
        return $next($request);
    }


    /**
     * 返回TOKEN错误代码内容
     * @param $code
     * @return string
     */
    private static function getError($code): string
    {
        $errArr = self::getErrorArr();
        if (!key_exists($code, $errArr)) {
            return "未知错误";
        }
        return $errArr[$code];
    }

    /**
     * 获取TOKEN错误码数组
     * @return array
     */
    private static function getErrorArr(): array
    {
        return [
            self::$CODE_SUCCESS => "成功",
            self::$CODE_ERR => "系统异常",
        ];
    }

}