<?php

namespace App\Http\Response;

use App\Jobs\AddErrorLog;
use App\Jobs\SendEasySms;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Route;
trait CatchError
{
    public function getError($exception, $send_mail=true)
    {
        $error = $exception->getMessage();
        if(method_exists($exception, 'getStatusCode')){
            $status = $exception->getStatusCode();
        }else{
            $status = get_class($exception);
        }
        $route = Request()->getMethod().':'.Request()->getRequestUri();
        if(Route::getFacadeRoot()->current()){
            $action = $status.':'.Route::getCurrentRoute()->getActionName();
        }else{
            $action = $status.':非法路由访问错误';
        }
        if (method_exists($exception, 'getPrevious')) {
            $err = $exception->getPrevious();
            if (!empty($err)) {
                $error = $err->getMessage();
            }
        }
        $files = explode('/', $exception->getFile());
        $file = $files[count($files)-1];
        $host = request()->gethost();
        $params = json_encode(request()->all(),JSON_UNESCAPED_UNICODE);
        $maxLength = 500;
        if (strlen($params) > $maxLength) {
            $params = substr($params, 0, $maxLength);
        }
        $client = Request()->header('client-os')?:'other';
        $server_ip = $_SERVER['SERVER_ADDR']??($_SERVER['REMOTE_ADDR']??'');
//        $server_ip = isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:'';
        $message = '服务器异常，前端：'.$client.'，ip：'.$server_ip.'，域名：'.$host.'，位置：'.$route.'，操作：'.$action.'，控制器：'.$file.'， Line:'.$exception->getLine().'，参数：'.$params.'，用户id:'.(auth()->id()?:'无').'，报错内容：'.$error.'，错误码:'.$exception->getCode().'【友福同享】';
        Log::info("错误信息");
        Log::info($message);
        AddErrorLog::dispatch($message)->onQueue('health');
//        SendEasySms::dispatch('15872844805', ['message'=>$message])->onQueue('send.code.sms');
//        Redis::connection('love')->lpush('error_message', $message);
        return $message;
    }
}
