<?php

namespace App\Jobs\GrowingIO;

use GuzzleHttp\Client;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class UserInfoReportJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    protected $data;

    /**
     * 上报用户信息，data为包含loginUserId的二维数组
     *
     * UserGenderReportJob constructor.
     * @param  array  $data
     */
    public function __construct($data)
    {
        $this->data = $data;
    }

    public function handle()
    {
        try {
            if (config('app.env') !== 'production') {
                return;
            }
            $client = new Client();

            $data = $this->data;

            $url = 'https://data.growingio.com/826fb1882511d92d/loginUserId';

            $keyArray = join(',', array_column($data, 'loginUserId'));
            $response = $client->post($url, [
                'headers' => [
                    'Access-Token' => '8809c8b595e946b383e55392e31b2719',
                    'Content-Type' => 'application/json'
                ],
                'query' => [
                    'auth' => $this->authToken('826fb1882511d92d', 'fa0d997b177040da9d83a435f6af87b2', $keyArray),
                ],
                'json' => $data
            ]);
        } catch (\Throwable $exception) {
            \Log::error($exception);
        }
    }

    public function authToken($projectKeyId, $secretKey, $keyArray)
    {
        $message = "ai=" . $projectKeyId . "&loginUserId=" . $keyArray;
        return hash_hmac('sha256', $message, $secretKey, false);
    }
}
