<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;

class Lu
{

    public static $request;

    public static function ssl()
    {
        if (isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))) {
            return true;
        } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
            return true;
        }
        return false;
    }


    public static function CheckTableName()
    {
        $table_name = 'zz_request_log_' . date('ym');
        $table_count = DB::select('select count(1) as c from information_schema.TABLES where table_schema = ? and table_name = ?', [env('DB_DATABASE'), $table_name])[0];
        if ($table_count->c === 0) {
            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->timestamps();
            });
        }
        self::$request = new \App\Models\RequestLog;
        self::$request->setTable($table_name);
    }

    public static function RequestLog()
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'OPTIONS' && env('REQUEST_LOG')) {
            self::CheckTableName();
            $post_data = request()->post();
            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"}';
            $get_data = $_GET;
            $header_data = request()->header();
            foreach ($header_data as $key => $header_datum) {
                $str_len = mb_strlen(json_encode($header_datum, JSON_UNESCAPED_UNICODE));
                $str_size = $str_len / 1024;
                if ($str_size > 10) {
                    $header_data["$key"] = 'Row size too large';
                }
            }
            $header_data = json_encode($header_data, JSON_UNESCAPED_UNICODE);
            $str_len = mb_strlen($header_data);
            $str_size = $str_len / 1024;
            if ($str_size > 40) $header_data = '{"data":"Row size too large"}';
            $get_data = json_encode($get_data, JSON_UNESCAPED_UNICODE);
            self::$request->request_ip = self::ip();
            self::$request->post_data = $post_data == '[]' ? '{}' : $post_data;
            self::$request->get_data = $get_data == '[]' ? '{}' : $get_data;
            self::$request->header_data = $header_data == '[]' ? '{}' : $header_data;
            self::$request->request_url = explode('?', $_SERVER['REQUEST_URI'])[0];
            self::$request->save();
        }
    }

    // region 获取 IP
    public static function ip()
    {
        //strcasecmp 比较两个字符，不区分大小写。返回0，>0，<0。
        if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $ip = getenv('REMOTE_ADDR');
        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        $res = preg_match('/[\d\.]{7,15}/', $ip, $matches) ? $matches [0] : '';
        return $res;
    }
    // endregion
    // region 去除空格
    public static function ge($str)
    {
        return preg_replace("/\s+/", ' ', $str);
    }
    // endregion
    // region 获取完整路径
    public static function fp($path)
    {
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        return $http_type . $_SERVER['HTTP_HOST'] . $path;
    }
    // endregion

    // region 10位时间戳 格式化
    public static function date($time = false, $format = "Y-m-d H:i:s")
    {
        if (!$time) $time = time();
        return date($format, $time);
    }
    // endregion
    // region 毫秒时间戳
    public static function time()
    {
        return floor(microtime(true) * 1000);
    }
    // endregion
    // region exit
    public static function exit($data = [])
    {
        $res = $data;
        if ($_SERVER['REQUEST_METHOD'] !== 'OPTIONS' && env('REQUEST_LOG')) {
            foreach ($data as $key => $datum) {
                $str_len = mb_strlen(json_encode($datum, JSON_UNESCAPED_UNICODE));
                $str_size = $str_len / 1024;
                if ($str_size > 10) {
                    $data["$key"] = 'Row size too large';
                }
            }
            $data_str = json_encode($data, JSON_UNESCAPED_UNICODE);
            $str_len = strlen($data_str);
            $str_size = $str_len / 1024;
            if ($str_size > 40) $data_str = '{"data":"Row size too large"}';
            self::$request->response_data = $data_str;
            self::$request->save();
        }
        return $res;
    }
    // endregion
    // region echo
    public static function echo($message = '', $code = 200, $data = [])
    {
        $return = [];
        $return['code'] = intval($code);
        if ($message) $return['message'] = $message;
        if ($data) $return['data'] = $data;
        return self::exit($return);
    }

    // endregion
    public static function post($url, $data, $type = 'json')
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POST, true);
        if ($type === 'data') {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        }
        if ($type === 'json') {
            $data_string = json_encode($data, JSON_UNESCAPED_UNICODE);
            curl_setopt($curl, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data_string)
            ]);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
        }
        $r = curl_exec($curl);
        curl_close($curl);
        return $r;
    }
}
