<?php

namespace App\Jobs;

use App\Consts\SysConsts;
use App\Modules\User\Models\QappUserRententionLog;
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 UserRententionJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $uid;
    protected $read_time;
    protected $register_time;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(int $uid, string $read_time, string $register_time)
    {
        $this->uid = $uid;
        $this->read_time = $read_time;
        $this->register_time = $register_time;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $date = date('Y-m-d', strtotime($this->read_time));
        $exists = QappUserRententionLog::where('uid', $this->uid)->exists();
        if ($exists) {
            return;
        }
        $client = new Client();
        $params = [
            'uid' => $this->uid,
            'source' => 'wdy'
        ];
        $params['sign'] = _sign($params, SysConsts::TIKTOK_KEY);
        $url = 'https://newtrackapi.zhuishuyun.com/api/qappuser/rentention';
        $response =  $client->post($url, ['form_params' => $params])->getBody()->getContents();
        myLog('new_user_rentention')->info($response);
        $result =  json_decode($response);
        if ($result) {
            if ($result->code == 0) {
                QappUserRententionLog::create([
                    'date' => $date,
                    'uid' => $this->uid,
                    'register_time' => $this->register_time,
                    'read_time' => $this->read_time,
                ]);
            }
        }
    }
}
