<?php
// +----------------------------------------------------------------------
// | 麦沃德科技赋能开发者，助力中小企业发展 
// +----------------------------------------------------------------------
// | Copyright (c) 2017～2024  www.wdadmin.cn    All rights reserved.
// +----------------------------------------------------------------------
// | Wdadmin系统产品软件并不是自由软件，不加密，并不代表开源，未经许可不可自由转售和商用
// +----------------------------------------------------------------------
// | Author: MY WORLD Team <bd@maiwd.cn>   www.wdadmin.cn
// +----------------------------------------------------------------------
namespace app\adminapi\listener;

class OperationLog
{
    public function handle($response)
    {
        $request = request();

        //需要登录的接口，无效访问时不记录
        if (empty($request->adminInfo) || empty($request->controllerObject)) {
            return;
        }

        //获取操作注解
        $docBlock = '';
        try {
            $re = new \ReflectionClass($request->controllerObject);
            $action = $request->action();
            if ($re->hasMethod($action)) {
                $doc = $re->getMethod($action)->getDocComment();
                if (empty($doc)) {
                    $docBlock = '未配置注解';
                } else {
                    preg_match('/\s(\w+)/u', $doc, $values);
                    $docBlock = $values[0] ?? '未配置注解';
                }
            } else {
                $docBlock = '未知操作';
            }
        } catch (\Throwable $e) {
            $docBlock = $docBlock ?: '无法获取操作名称';
        }

        // 如果是系统日志相关操作，直接跳过不记录
        if (stripos($docBlock, '系统日志') !== false || stripos($docBlock, '操作日志') !== false) {
            return;
        }

        $params = $request->param();

        //过滤密码参数
        if (isset($params['password'])) {
            $params['password'] = "******";
        }

        //记录日志
        $systemLogModel = new \app\adminapi\model\OperationLog();

        return $systemLogModel->save([
            'admin_id' => $request->adminInfo['id'] ?? 0,
            'admin_name' => $request->adminInfo['name'] ?? '',
            'action' => $docBlock,
            'account' => $request->adminInfo['account'] ?? '',
            'url' => $request->url(true),
            'type' => $request->isGet() ? 'GET' : 'POST',
            'params' => json_encode($params, true),
            'ip' => $request->ip(),
            'result' => $response->getContent(),
        ]);;
    }

}