<?php

namespace App\Http\Middleware;

use App\Services\LogService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class XmlLog
{
    /**
     * 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)
    {
        date_default_timezone_set('PRC');

       // dd($request->getContent());
        $actions=[
            "接收申请单"=>'T0002',
            "申请单状态变更"=>'T0003',
            "检查完成通知"=>'MES0006'
        ];
        Log::info($request->getContent());

        $insertid=0;
        $data=[
            'mark'=>null,
            'ip'=>"",
            'request_header'=>$request->header(),
            'post_data'=>$request->getContent(),
            'get_data'=>[],
            'request_url'=>$request->getPathInfo()
        ];
        preg_match('/<action>(.*?)<\/action>/', $request->getContent(), $matches);
        if (!empty($matches)) {
            $data['mark']=   array_search($matches[1], $actions);
        }

        $insertid= self::RequestLog($data,$insertid);

        $response= $next($request);
        self::RequestLog(['response_data'=>self::JsonEncode($response->getContent())],$insertid);
        return $response;
    }
    public function RequestLog($arr,$id)
    {  //记录请求日志
        date_default_timezone_set('PRC');
        LogService::CheckTableName();
        $table_name = 'zz_request_log_' . date('ym');
        $response_data = isset($arr['response_data']) ? self::JsonEncode($arr['response_data']) : '';
        $header_data = isset($arr['request_header']) ?self::JsonEncode($arr['request_header']):'';
        $post_data = isset($arr['post_data'])?self::JsonEncode($arr['post_data']):'';
        $get_data = isset($arr['get_data'])?self::JsonEncode($arr['get_data'], JSON_UNESCAPED_UNICODE):'';
        $milliseconds = round(microtime(true) * 1000);
        $date = date("Y-m-d H:i:s", $milliseconds / 1000);
        $formatted_date = sprintf("%s.%03d", $date, $milliseconds % 1000);

        //   $i=DB::insert("insert into ".$table_name." (request_ip, response_data,header_data,post_data,get_data,request_url,create_time,update_time)
        //  values (?,?,?,?,?,?,?,?)",[$arr['ip'],$response_data,$header_data,$post_data,$get_data,$arr['request_url'],$formatted_date,$formatted_date]);
        // var_dump($i);
        if ($id > 0) {
            return DB::table($table_name)->where('id', $id)->update([
                'response_data' => $response_data,
            ]);
        } else {
            return DB::table($table_name)->insertGetId([
                'mark'=>$arr['mark'],
                'request_ip' => $arr['ip'],
                'response_data' => $response_data,
                'header_data' => $header_data,
                'post_data' => $post_data,
                'get_data' => $get_data,
                'request_url' => $arr['request_url'],
                'create_time' => $formatted_date,
                'update_time' => $formatted_date
            ]);
        }
    }
    public static function JsonEncode($data){  //格式化数据，转json
        $post_data =$data;
        $post_data = json_encode($post_data, JSON_UNESCAPED_UNICODE);
        $str_len = mb_strlen($post_data);
        $str_size = $str_len / 1024;
        if ($str_size > 40) $post_data = '{"data":"Row size too large"}';
        return $post_data;
    }
}
