<?php
// app/middleware/RequestLog.php
namespace app\middleware;

use app\model\SystemRequestLog;
use think\facade\Request;

class RequestLog
{
    public function handle($request, \Closure $next)
    {
        $startTime = microtime(true);
        
        $response = $next($request);
        
        // 排除特定路由
        if (in_array($request->pathinfo(), ['/favicon.ico'])) {
            return $response;
        }
        
        try {
            $log = [
                'method'        => $request->method(),
                'url'           => $request->url(),
                'params'        => $this->filterParams($request->param()),
                'ip'            => $request->ip(),
                'user_agent'    => $request->header() ? $request->header('user-agent') : '无',
                'user_id'       => $request->userId ?? 0, // 需要根据你的认证系统调整
                'response_code' => $response->getCode(),
                'response_time' => round(microtime(true) - $startTime, 3),
            ];
            
            SystemRequestLog::create($log);
        } catch (\Exception $e) {
            // 记录失败不影响主流程
            \think\facade\Log::error('请求日志记录失败:'.$e->getMessage());
        }
        
        return $response;
    }
    
    protected function filterParams($params)
    {
        // 过滤敏感字段
        $sensitiveFields = ['password', 'pwd', 'token', 'access_token'];
        foreach ($sensitiveFields as $field) {
            if (isset($params[$field])) {
                $params[$field] = '******';
            }
        }
        return $params;
    }
}