<?php

namespace App\Http\Middleware;

use Closure;
use DB;
use App\Models\AdminToken;
//use Illuminate\Support\Facades\Redis;
use App\Services\RedisService;
class RequestPcMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $que = $request->route()->getAction();//获取请求的路由
        $action =explode('@',$que['uses'])[1];//方法
        $controller = trim($que['prefix'],'/');
        //$action =explode('@',$que['uses'])[0];//控制器
        //dd($que);
        if ($controller != 'api/user' && $action != 'phoneCode' && $controller != 'user' && $controller != 'api/service/Pay/wxpay'){
            try{
                $api_token = $request->input('token');
            }catch(\Exception $e){
                return response()->json(['Data'=>'','ErrorCode'=>1001,'ErrorMessage'=>'token缺少必要授权参数，请联系管理员']);
            }
            if (!$request->filled('Pri_id') || !$request->filled('Login_id') || !$request->filled('token')){
                return response()->json(['Data'=>'','ErrorCode'=>1001,'ErrorMessage'=>'缺少必要参数1，请联系管理员']);
            }
            //验证系统占用字段
            if ($request->has('session_token')){
                return response()->json(['Data'=>'','ErrorCode'=>1001,'ErrorMessage'=>'该请求存在限制字段']);
            }
            $requestdata = $request->all();
            $action_time = date("Y-m-d H:i:s",strtotime("-9 hour",time()));
            $Login_id = 'Login'.$request->input('Login_id');
            //if(RedisService::redisHas($request->input('Login_id'))){
	           	$tokeninfo = RedisService::redisGet($Login_id);
	           	if($tokeninfo){
		           	$at_permissions = $tokeninfo['at_permissions'];
		           	$function_id = $at_permissions['function_id'];
		           	if($tokeninfo['at_token'] != $request->input('token') || $action_time > $tokeninfo['at_time']){
			           	return response()->json(['Data'=>'','ErrorCode'=>1001,'ErrorMessage'=>'授权已过期，请重新登录r']);
		           	}else{
			           	//if(!in_array($request->input('Pri_id'),$function_id)){
				           //	return response()->json(['Data'=>'','ErrorCode'=>20000,'ErrorMessage'=>'您无该模块访问权限']);
			           	//}else{
				           	$tokeninfo['at_time'] = date('Y-m-d H:i:s');
				           	RedisService::redisSet($Login_id, $tokeninfo);
				           	$mid_params['session_token'] = $at_permissions['admindata'];
			                $request->attributes->add($mid_params);//添加参数
			                return $next($request);
		                //}
	                }
           		}else{
	           		//获取mysql授权
	           		$mid_params=self::tokenMysql($requestdata,$action_time);
	           		if($mid_params){
		           		$request->attributes->add($mid_params);//添加参数
						return $next($request);
			        }else{
						return response()->json(['Data'=>'','ErrorCode'=>1001,'ErrorMessage'=>'授权已过期，请重新登录s']);
				    };
           		}
        }else{
            return $next($request);
        }


    }
    public function tokenMysql ( $requestdata , $action_time ){
    	$tokeninfo = AdminToken::where('at_token',$requestdata['token'])->where('at_time','>',$action_time)->first();
        if ($tokeninfo){
            $at_permissions = $tokeninfo['at_permissions'];
            AdminToken::where('at_token',$requestdata['token'])->update(['at_time'=>date('Y-m-d H:i:s')]);
            $at_permissions = json_decode($at_permissions,true);
			$tokeninfo['at_time'] = date('Y-m-d H:i:s');
			$tokeninfo['at_perm'] = json_decode($tokeninfo['at_perm']);
        	$tokeninfo['at_button'] = json_decode($tokeninfo['at_button']);
        	$tokeninfo['at_permissions'] = json_decode($tokeninfo['at_permissions']);
            $mid_params['session_token'] = $at_permissions['admindata'];
            $Login_id = 'Login'.$tokeninfo['at_adminid'];
        	RedisService::redisSet( $Login_id , json_encode($tokeninfo));
            return $mid_params;
        }else{
            return false;
        }
    }
}
