<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        AuthorizationException::class,
        HttpException::class,
        ModelNotFoundException::class,
        ValidationException::class,
        ApiException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        $appEnv = env('APP_ENV', 'production');
        if ($this->shouldReport($e) && env('APP_ENV') == 'production') {
            $date        = date('Y-m-d H:i:s');
            $file        = $e->getFile();
            $line        = $e->getLine();
            $message     = $e->getMessage();
            $trace       = $e->getTraceAsString();
            $traceArr    = explode('#', $trace);
            $traceSimple = $trace;
            if (is_array($traceArr)) {
                $traceSub    = array_slice($traceArr, 0, 3);
                $traceSimple = implode('#', $traceSub);
            }

            $msg = <<<EOF
项目：quick_app [$appEnv]
报错时间：$date
报错文件：$file
报错行数：line $line
报错信息：$message
报错跟踪：
$traceSimple
EOF;
            sendNotice($msg);
        }

        parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    /*
    public function render($request, Exception $e)
    {
        return parent::render($request, $e);
    }
    */

    public function render($request, Exception $e)
    {
        if ($e instanceof ApiException) {
            $data = [
                'code' => $e->getCode(),
                'msg'  => $e->getMessage(),
                'data' => []
            ];

            return response()->json($data);
        }
        if($e instanceof ValidationException) {
            return response()->json([
                'code' =>  -1,
                'msg' => array_first(array_flatten($e->errors()))
            ]);
        }

        return parent::render($request, $e);
    }
}
