<?php
/**
 * Created by PhpStorm.
 * User: z-yang
 * Date: 2020/12/24
 * Time: 11:36
 */

namespace App\Jobs;

use DB;
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 AsyncUserRegister
 * @package App\Jobs\
 */
class AsyncUserRegister implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $uid;
    private $distribution_channel_id;
    private $register_ip;
    private $user_agent;
    private $user_created_at;

    const SUCCESS = 'success';


    public function __construct($uid,$distribution_channel_id,$register_ip,$user_agent,$user_created_at){
        $this->uid = $uid;
        $this->distribution_channel_id = $distribution_channel_id;
        $this->register_ip = $register_ip;
        $this->user_agent = $user_agent;
        $this->user_created_at = $user_created_at;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $this->reportToChannel();
    }

    private function reportToChannel(){
        $link = $this->getReportUrl($this->distribution_channel_id);
        if(!$link) return ;
        $client = new Client(['timeout'=>3.0]);
        try{
            $result = $client->request('post',$link,['form_params'=>[
                'uid'=>$this->uid,
                'distribution_channel_id'=>$this->distribution_channel_id,
                'register_ip'=>$this->register_ip,
                'user_agent'=>$this->user_agent,
                'user_created_at'=>$this->user_created_at
            ]])->getBody()->getContents();
            if($result && str_contains(strtolower($result),self::SUCCESS)){
                return ;
            }
            $error = 'result error ,'.$result;
        }catch (\Exception $e){
            $error = 'exception,'.$e->getMessage();
        }
        DB::table('report_to_channel_users')->insert([
            'uid'=>$this->uid,
            'distribution_channel_id'=>$this->distribution_channel_id,
            'register_ip'=>$this->register_ip,
            'user_agent'=>$this->user_agent,
            'user_created_at'=>$this->user_created_at,
            'report_status'=>0,
            'error_msg'=>$error,
            'created_at'=>date('Y-m-d H:i:s'),
            'updated_at'=>date('Y-m-d H:i:s'),
        ]);
    }


    private function getReportUrl($distribution_channel_id){
        return '';
    }

}