<?php

namespace App\Jobs\OpenWork\External;

use App\Servers\DB\DbService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Servers\OpenWork\External\ContactService;
use App\Facades\Servers\Logs\Log;
use App\Models\OpenWork\job\Records;

/**
 * 成员客户信息同步队列
 * @version 1.0
 * @date 2025-04-10
 */
class CustomerJobs implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $customer_data;
    private ContactService $contact_service;
    private $Records;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(array $customer_data)
    {
        //
        $this->customer_data = $customer_data;


        $this->contact_service = app(ContactService::class);
    }

    public function getCorpId()
    {
        return $this->customer_data['corpid'] ?? null;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {

        try {
            $corpId = $this->customer_data['corpid'];
            (new DbService())->getConnectionNameByCorpId($corpId);

            // 创建任务记录
            $this->Records = Records::create([
                'job_id' => $this->customer_data['corpid'] . '_CustomerJobs',
                'name' => static::class,
                'payload' => json_encode($this->customer_data),
                'status' => 'processing',
                'started_at' => now()
            ]);

            //查询客户信息
            $corpid = $this->customer_data['corpid'];
            $userid_list = $this->customer_data['userid_list'];
            $cursor = $this->customer_data['cursor'];
            $limit = $this->customer_data['limit'];
            $result = $this->contact_service->get_external_contact_batchget($corpid, $userid_list, $cursor, $limit);
            //删除任务记录
            $this->Records->delete();
            // 成功处理...
        } catch (\Exception $e) {
            // 失败处理...
            if ($this->Records) {
                $this->Records->delete();
            }
            Log::info('job_error', 'CustomerJobs任务队列失败', ['data' => $this->customer_data, 'error' => $e->getMessage()]);
        }
    }

    public function failed(\Throwable $exception)
    {
        Log::info('job_error', 'CustomerJobs任务队列彻底失败', ['data' => $this->customer_data, 'error' => $exception->getMessage()]);
        // 失败处理...
        if ($this->Records) {
            $this->Records->delete();
        }
    }
}
