<?php

namespace App\Http\Middleware;

use Closure;
use App\Http\models\users;
use Illuminate\Support\Facades\Log;
use App\User;
class CheckApiKey
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try {
            $url=$request->url;
            $param = $request->except(['url','client_info_json','source','aes','upload','fail_recall_of_reason']);
            
            Log::channel('api')->info('API_PARAM:'.json_encode($param));
            Log::channel('api')->info('API_SERVER_PARAM:'.substr(md5(json_encode($param)),1,8));
            Log::channel('api')->info('API_CLIENT_PARAM:'.$url);
            
            $md_url = substr(md5(json_encode($param)),1,8);
            
            if(strcmp($url,$md_url)){
                if($_SERVER['REQUEST_SCHEME'] == 'http'){
                    return response()->json(array('code'=> 10001,'msg'=>'验证url失败'));
                }
            }

            $api_key=$request->api_key;
            $user_sn=$request->user_sn;
            
            $user = Users::where('user_sn',$param['user_sn'])->first();

            if(empty($user->parent_sn)){
                $the_expired = $user->expired;
            }else{
                $puser = Users::where('user_name',$user->parent_sn)->select('expired')->first();
                $the_expired = $puser->expired;
            }

            $todayDate = strtotime(date('y-m-d 00:00:00',time()));
            $expiredDate =strtotime($the_expired. ' 00:00:00');
        
            if(empty($the_expired) || $expiredDate - $todayDate <= 0){
                 return response()->json(array('code'=> 20008,'msg'=>'您的账号已过期，请联系管理员处理'));
            }
  
            $request->attributes->add(['user'=>$user]);//添加参数
        }catch (\Exception $e){
            Log::info($e->getFile().'-'.$e->getLine().'-'.$e->getMessage());
            return response()->json(array('code'=> 500,'msg'=>$e->getMessage().'-'.$e->getLine()));
        }   
        return $next($request);
    }
}
