<?php

namespace App\Services\Report;

use App\Dao\Report\ReportDao;
use App\Jobs\ReportDy;
use Exception;

class ReportService
{
    private $connection = 'redis';
    private $reportDao;

    public function __construct(
        ReportDao $reportDao
    )
    {
        $this->reportDao = $reportDao;
    }

    /**
     * 注册上报
     *
     * @param $user
     * @param $params
     * @return void
     */
    public function reportRegister($user, $params)
    {
        $eventType = 'active_register';
        $clickId   = trim(getProp($params, 'clickid'));
        if (empty($clickId)) {
            return;
        }

        // 去重
        $reportLog = $this->reportDao->getReportLogByClickId($clickId, $eventType);
        if (getProp($reportLog, 'id')) {
            return;
        }

        // 记录表
        $this->reportDao->saveReportLog([
            'adid'          => trim(getProp($params, 'adid')),
            'clickid'       => $clickId,
            'projectid'     => trim(getProp($params, 'projectid')),
            'promotionid'   => trim(getProp($params, 'promotionid')),
            'uid'           => (int)getProp($user, 'uid'),
            'send_order_id' => (int)getProp($params, 'send_order_id'),
            'ad_params'     => getProp($params, 'ad_params'),
            'event_type'    => $eventType,
            'created_at'    => date('Y-m-d H:i:s'),
            'updated_at'    => date('Y-m-d H:i:s'),
        ]);

        // 新用户上报
        $isNewUser = (bool)getProp($user, 'is_new_user');
        if ($isNewUser) {
            // 上报参数
            $paramss = [
                'clickid'    => $clickId,
                'event_type' => $eventType,
                'context'    => [
                    'ad' => [
                        'callback' => $clickId,
                    ]
                ],
                'timestamp'  => (int)(microtime(true) * 1000)
            ];

            // 执行上报
            try {
                ReportDy::dispatch($paramss)->onConnection($this->connection);
            } catch (Exception $e) {
                dLog('exception')->info('reportRegister', [$e->getMessage()]);
            }
        }
    }
}