<?php

namespace app\service;

use app\model\SysOperateRecord;
use think\Service;

/**
 * 安全服务
 */
class SecurityService extends Service
{
    protected array $securityLogRecords = [];

    public function register(): void
    {
        /**
         * 添加安全日志记录事件
         */
        $this->app->event->listen("sys:securityLogRecord", function ($trigger) {

            [[$location, $event], $message, $data] = $trigger;
            $model = new SysOperateRecord();
            $model->setOption('convertNameToCamel', false);
            $model->location = $location;
            $model->event = $event;
            $model->description = $message;
            $model->create_time = date('Y-m-d H:i:s');
            $model->data = json_encode($data, JSON_UNESCAPED_UNICODE);
            $this->securityLogRecords[] = $model->toArray();
        });

        $this->app->event->listen("HttpEnd", function () {
            $auth = $this->app->request->getAuth();
            $context_id = $this->app->request->contextId;
            $operate_user_id = null;
            if ($auth) {
                $operate_user_id = $auth->userId;
            }
            /**
             * 保存接口操作记录到日志表
             */
            (new SysOperateRecord)->insertAll(array_map(function ($item) use ($operate_user_id, $context_id) {
                $item['operate_user_id'] = $operate_user_id;
                $item['context_id'] = $context_id;
                return $item;
            }, $this->securityLogRecords));
        });
    }
}