<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Services\LogService;

class Log
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $insert_id=0;
        $insert_id=self::requestLog($request,$insert_id);  //记录请求时日志，不含返回信息
        $response = $next($request);

        $content = $response->getContent();
        $data = json_decode($content, true); // 解码响应内容为关联数组

        // 在关联数组中添加 code 字段
       // $data['code'] = 200;
        $data['code'] = $response->getStatusCode();

        $modifiedContent = json_encode($data); // 编码修改后的关联数组为 JSON 字符串
        $response->setContent($modifiedContent);
        if(env('REQUEST_LOG') and    $response->getStatusCode()==200){   //如果返回状态为200进行log

            $ip=self::getTrustedProxiesIp();  //真实ip
            $request_header=$request->header(); //请求头
            //  dd($response);
            $response_data = $response->getData();  //返回data,json格式
            $post_data=$request->post(); //post请求数据
            $get_data=$request->query(); //get请求
            $request_url=$request->getPathInfo();//访问的接口地址
            $log=app()->make(LogService::class);
            $log->RequestLog([
                'ip'=>$ip,
                'response_data'=>$response_data,
                'request_header'=>$request_header,
                'post_data'=>$post_data,
                'get_data'=>$get_data,
                'request_url'=>$request_url,
            ],$insert_id);
        }


        return $response;
    }
    public static function getTrustedProxiesIp(){ //获取用户真实ip
        \request()->setTrustedProxies(\request()->getClientIps(),Request::HEADER_X_FORWARDED_FOR);
        return \request()->getClientIp();
    }

    public static function requestLog($request,$insert_id){  //记录请求时日志，不含返回信息
        if(env('REQUEST_LOG') ){   //如果返回状态为200进行log
            $ip=self::getTrustedProxiesIp();  //真实ip
            $request_header=$request->header(); //请求头
            $post_data=$request->post(); //post请求数据
            $get_data=$request->query(); //get请求
            $request_url=$request->getPathInfo();//访问的接口地址
            $log=app()->make(LogService::class);
            return   $log->RequestLog([
                'ip'=>$ip,
                'request_header'=>$request_header,
                'post_data'=>$post_data,
                'get_data'=>$get_data,
                'request_url'=>$request_url,
            ],$insert_id);
        }

    }
}
