<?php

namespace App\Http\Middleware;

use App\Model\LogModel;
use App\Model\UserModel;
use Closure;
use Carbon\Carbon;
use App\Exceptions\ControllerException;
//use Illuminate\Support\Facades\DB;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Support\Facades\DB;

class Apprialisal
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //DB::connection()->disableQueryLog();
        $headers = $request->header();
        if ($request->path() == 'api/v1/users' && request()->method() == 'POST') {
            return $next($request);
        }
        if (!isset($headers['authorization']) || empty($headers['authorization'][0])) {
            return error("请求异常:Authorization不存在",1013);
        }

        $token = substr($headers['authorization'][0],7);
        try {
            decrypt($token);
        } catch (DecryptException $e) {
            return error('token非法');
        }

        $user = DB::connection('mongodb')->collection("users")->where("token",$token)->first();
        if (empty($user)){
            return error("请求异常:Authorization不存在",1014);
        }


        try{
            $idArr = ($user['_id'])->jsonSerialize();
            if (!isset($user['mis_uid'])){
                LogModel::addlog(['获取用户数据异常'=>$request->all()]);
                return error("获取用户数据异常，请重新登录再试！",1015);
            }
        }catch (\Exception $e){
            LogModel::addlog(['获取用户数据异常'=>$request->all()]);
            return error("获取用户数据异常，请重新登录再试！",1015);
        }


        $request->replace(array_merge($request->all(), [
            'access_token' => $token,
            'token_username' => $user['name'],
            'token_user_id' => $idArr['$oid'],
            'mis_uid'    => $user["mis_uid"]
        ]));

        return $next($request);
    }
}
