<?php
/**
 * 操作日志
 *
 * @author zhangdongying
 * @date   2023-02-28
 */
declare(strict_types=1);

namespace Meibuyu\Common\GlobalLog\Service;

use Psr\Container\ContainerInterface;

class OperateLogService
{
    /**
     * 队列服务
     */
    protected $queueService;

    /**
     * 操作日志队列名称
     *
     * @var string
     */
    protected $queue = 'QUEUE:GLOBAL_OPERATE_LOG';

    /**
     * 初始化
     *
     * @param ContainerInterface $container 容器实例
     * @throws \Throwable
     */
    public function  __construct(ContainerInterface $container)
    {
        $this->queueService = $container->get(RedisQueueService::class);
    }

    /**
     * 设置队列名称
     *
     * @param string $name 队列名称
     * @return OperateLogService
     */
    public function setQueueName(string $name): OperateLogService
    {
        $this->queue = $name;
        return $this;
    }

    /**
     * 生成唯一ID
     *
     * @return string
     */
    public static function generateUniqueId(): string
    {
        return sha1(uniqid('', true) . mt_rand(10000, 99999));
    }

    /**
     * 添加操作日志
     *
     * @param string $requestId 请求ID
     * @param string $appName 项目名称
     * @param int $operatorId 操作人ID
     * @param string $operatorName 操作人名称
     * @param string $clientIp 客户端IP
     * @param string $url 请求链接
     * @param string $tableName 表名
     * @param string $recordId 记录ID
     * @param string $operateType 操作类型
     * @param string $param 参数
     * @param string $before 修改之前数据
     * @param string $after 修改之后数据
     * @param string $remark 备注
     * @return bool
     * @throws \Exception
     */
    public function addOperateLog(
        string $requestId,
        string $appName,
        int $operatorId,
        string $operatorName,
        string $clientIp,
        string $url,
        string $tableName,
        string $recordId,
        string $operateType,
        string $param,
        string $before,
        string $after,
        string $remark
    ): bool
    {
        $data = [
            'log_sn'        => self::generateUniqueId(),
            'request_id'    => $requestId,
            'app_name'      => $appName,
            'operator_id'   => $operatorId,
            'operator_name' => $operatorName,
            'client_ip'     => $clientIp,
            'url'           => $url,
            'table_name'    => $tableName,
            'record_id'     => $recordId,
            'operate_type'  => $operateType,
            'param'         => $param,
            'before'        => $before,
            'after'         => $after,
            'remark'        => $remark,
            'created_at'    => date('Y-m-d H:i:s'),
        ];

        return (bool)$this->queueService->push($this->queue, json_encode($data));
    }
}