<?php

namespace app;

use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Response;
use Throwable;
use think\facade\Env;
use think\facade\Config;
use think\facade\Log;
use think\facade\Cache;
use app\Constant;
use app\exceptions\ParamsValidateException;
use app\exceptions\NotLoginException;
use app\exceptions\NoAccessException;

/**
 * 应用异常处理类
 */
class ExceptionHandle extends Handle
{
    /**
     * 不需要记录信息（日志）的异常类列表
     * @var array
     */
    protected $ignoreReport = [
        HttpException::class,
        HttpResponseException::class,
        ModelNotFoundException::class,
        DataNotFoundException::class,
        ValidateException::class,
    ];

    /**
     * 记录异常信息（包括日志或者其它方式记录）
     *
     * @access public
     * @param  Throwable $exception
     * @return void
     */
    public function report(Throwable $exception): void
    {
        // 使用内置的方式记录异常日志
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @access public
     * @param \think\Request   $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response
    {
        // 添加自定义异常处理机制
        $trace_id = 'error-trace-id-' . time() . '-' . rand(1000, 9999);

        $handle_flag = false;
        if ($e instanceof HttpException && $e->getStatusCode() === 404) {
            //$resp = Response::create(json_encode(ajaxFail($e->getMessage(), -1003, null, true)));
            $resp = ajaxFail($e->getMessage(), -1003);
            $handle_flag = true;
            $e = [];
        }
        if ($e instanceof ParamsValidateException) {
            $resp = ajaxFail('参数' . $e->getMessage(), -1002);
            $handle_flag = true;
            if (Config::get('app.APP_DEBUG')) {
                $e = '参数' . $e->getMessage() . ' request_uri:' . $_SERVER['REQUEST_URI'];
            }else{
              $e = [];
            }
        }
        if ($e instanceof NotLoginException) {
            $resp = ajaxFail("未登录或登录超时", -1000);
            $handle_flag = true;
            $e = [];
        }
        if ($e instanceof NoAccessException) {
            $resp = ajaxFail("权限不足,拒绝操作", -1003);
            $handle_flag = true;
            $e = [];
        }
        if ($e != []) {
            $txt = sprintf("异常信息(" . $trace_id . "): %s \r\n", $e);
            Log::write($txt, 'ERROR');
        }

        if ($handle_flag) {
            $resp->contentType('application/json');
            return $resp;
        }
        if (!Config::get('app.APP_DEBUG')) {
            $resp = ajaxFail("系统异常", -1001, $trace_id);
            $resp->contentType('application/json');
            return $resp;
        }

        // 其他错误交给系统处理
        return parent::render($request, $e);
    }
}
