<?php

namespace App\Jobs;

use App\Models\InviteUser;
use App\Models\User;
use GuzzleHttp\Client;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class SyncSaasUser implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $user;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($user)
    {
        $this->user = $user;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Log::info("同步saas用户：".$this->user->id);
        $client = new Client();

        $url = config('app.shop_url')."merchant/users";
        $headers = [
            'Key' => config('app.shop_key'), // 自定义头部参数（示例）
        ];
        $from_user_id = $this->user->recommendUserLog?$this->user->recommendUserLog->recommend_user_id:null;
        $data = [
            'accid'=>User::SAAS_PREFIX.$this->user->id,
            'nickname'=>$this->user->name,
            'pic'=>$this->user->avatar,
            'mobile'=>$this->user->mobile,
            'from_accid'=>$from_user_id?User::SAAS_PREFIX.$from_user_id:null,
        ];
        $response = $client->post($url, [
            'headers'=>$headers,
            'json'=>$data,
        ]);
        $body = $response->getBody()->getContents(); // 获取响应内容
        $res = json_decode($body, true);
        if($res['code'] == 1) throw new \Exception($res['message']);
    }
}
