<?php

namespace App\Jobs\OpenWork\External;

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 App\Servers\OpenWork\External\ContactService;
use App\Models\OpenWork\job\Records;
use App\Facades\Servers\Logs\Log;
use App\Servers\DB\DbService;

/**
 * 处理联系人外部客户
 * @author 唐远望
 * @version 1.0
 * @date 2025-06-05
 */

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

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


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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            $corpId = $this->customer_user_data['corpid'];
            (new DbService())->getConnectionNameByCorpId($corpId);
            $contactService = new ContactService();
            // 创建任务记录
            $this->Records = Records::create([
                'job_id' => $this->customer_user_data['corpid'] . '_CustomerUserjobs',
                'name' => static::class,
                'payload' => json_encode($this->customer_user_data),
                'status' => 'processing',
                'started_at' => now()
            ]);
            $corpid = $this->customer_user_data['corpid'];
            $external_contact_info = $this->customer_user_data['external_contact_info'];
            $follow_info = $this->customer_user_data['follow_info'];
            $result = $contactService->handle_account_inheritance_log($corpid, $external_contact_info,$follow_info);
            //删除任务记录
            $this->Records->delete();
            // 成功处理...
        } catch (\Exception $e) {
            if ($this->Records) {
                $this->Records->delete();
            }
            // 如果错误信息里面包含字符UNIQUE_（数据唯一）则不写日志
            if (stripos($e->getMessage(), 'UNIQUE_') === false) {
                // 记录错误日志
                Log::info('job_error', 'CustomerUserJobs任务队列失败', ['data' => $this->customer_user_data, 'error' => $e->getMessage()]);
            }
        }
    }

    public function failed(\Throwable $exception)
    {
        Log::info('job_error', 'CustomerUserJobs任务队列彻底失败', ['data' => $this->customer_user_data, 'error' => $exception->getMessage()]);
        // 只有在Records存在时才删除
        if ($this->Records) {
            $this->Records->delete();
        }
    }
}
