<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use mysql_xdevapi\Exception;

class LogService
{

    public function RequestLog($arr,$id){  //记录请求日志
        self::CheckTableName();
        $table_name='zz_request_log_' . date('ym');
        $response_data =isset($arr['response_data'])?self::JsonEncode($arr['response_data']):'';
        $header_data = self::JsonEncode($arr['request_header']);
        $post_data = self::JsonEncode($arr['post_data']);
        $get_data = json_encode($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([
                '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 function GetLogTableName(){
        $result=[];
        //获取日志表名称
        $tables = DB::select("SHOW TABLES LIKE '%" . 'zz_request_log_' . "%'");
        $tableNames = [];

        foreach($tables as $table) {
            foreach($table as $tableName) {
                $tableNames[] = $tableName;
            }
        }
        $result['table_list']=$tableNames;
        return \Yz::Return(true,'获取成功',$result);
    }

    public function GetList($arr){  //获取日志列表
        $result=[];
        $table_name=$arr['searchInfo']['table_name'];
        $page = $arr['page'];
        $pagesize = $arr['pagesize'];
        if(isset($table_name)){
            //获取接口列表
            $apilist=DB::table($table_name)
                ->select('request_url')
                ->groupBy('request_url')
                ->get();
            $result['api_list']=$apilist;

            $list=DB::table($table_name);
            if(isset($arr['searchInfo']['request_url'])) $list=$list->where('request_url',$arr['searchInfo']['request_url']);
            if(isset($arr['searchInfo']['ziduan']) and isset($arr['searchInfo']['ziduan_value'])) $list=$list->where($arr['searchInfo']['ziduan'],'like','%'.$arr['searchInfo']['ziduan_value'].'%' );
            $count=$list->count();
            $list=$list->orderBy('id', 'desc')->skip(($page-1)*$pagesize)->take($pagesize)->get();

            $result['list']=$list;
            $result['count']=$count;
            return \Yz::Return(true,'获取成功',$result);
        }else{
            return \Yz::echoError1("请选择表名");
        }


    }

    public static function CheckTableName(){   // 查看日志表是否存在，每月一个表，如果没有就创建
        $table_name='zz_request_log_' . date('ym');
        if(Schema::hasTable($table_name)){

        }else{
            Schema::create($table_name, function (Blueprint $table) {
                $table->id();
                $table->string('request_ip', 15);
                $table->text('post_data');
                $table->text('get_data');
                $table->text('header_data');
                $table->text('response_data')->nullable();
                $table->string('request_url', 300);
                $table->string('create_time', 30);
                $table->string('update_time', 30);
                $table->timestamps();
            });
        }
    }
    public static function JsonEncode($data){  //格式化数据，转json
        $post_data =$data;
        foreach ($post_data as $key => $post_datum) {
            $str_len = mb_strlen(json_encode($post_datum, JSON_UNESCAPED_UNICODE));
            $str_size = $str_len / 1024;
            if ($str_size > 10) {
                $post_data->$key= 'Row size too large';
            }
        }
        $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;
    }
}
