<?php

namespace App\Jobs\OpenWork\License;

use App\Servers\DB\DbService;
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\Corp\LicenseOrderService;
use App\Facades\Servers\Logs\Log;
use App\Models\OpenWork\job\Records;
use Illuminate\Support\Facades\DB;

/**
 * 订单账号激活码同步队列
 * @author 唐远望
 * @version 1.0
 * @date 2025-04-14
 */
class OrderAccountJobs implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

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


    }

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

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

        $corpId = $this->request_account_data['corpid'];
        (new DbService())->getConnectionNameByCorpId($corpId);
        // 创建任务记录

        $this->Records = Records::create([
            'job_id' => $this->request_account_data['order_id'] . '_OrderAccountJobs',
            'name' => static::class,
            'payload' => json_encode($this->request_account_data),
            'status' => 'processing',
            'started_at' => now()
        ]);

        $order_id = $this->request_account_data['order_id'];
        $cursor   = $this->request_account_data['cursor'];
        $limit    = $this->request_account_data['limit'];
        try {
            $result   = (new LicenseOrderService())->request_handle_order_data($order_id, $cursor, $limit);
            if (!$result) {
                Log::info('job_error', '同步订单账号激活码失败-订单ID:',['error' => $this->request_account_data]);
            }
            if ($result['errcode']) {
                Log::info('job_error', '同步订单账号激活码失败-错误原因',  ['data'=>$this->request_account_data,'error' => $result]);
            }

            $this->Records->delete();
        } catch (\Exception $e) {
            // 失败处理...
            if ($this->Records) {
                $this->Records->delete();
            }
            Log::info('job_error', '同步订单账号激活码失败-异常原因',['data'=>$this->request_account_data,'error' => $e->getMessage()]);
        }
    }

    public function failed(\Throwable $exception)
    {
        Log::info('job_error', 'OrderAccountJobs彻底失败', ['data'=>$this->request_account_data,'error' => $exception]);

        // 失败处理...
        if ($this->Records) {
            $this->Records->delete();
        }
    }
}
