<?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\LicenseClientService;
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 OrderDetailJobs implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

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

    }

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            //
            $corpId = $this->order_info['corpid'];
            (new DbService())->getConnectionNameByCorpId($corpId);
            // 创建任务记录
            $this->Records = Records::create([
                'job_id' => $this->order_info['order_id'] . '_OrderDetailJobs',
                'name' => static::class,
                'payload' => json_encode($this->order_info),
                'status' => 'processing',
                'started_at' => now()
            ]);
            $result = (new LicenseClientService())->get_order_info($this->order_info['order_id']);
            // 如果获取结果失败
            if (!$result) {
                //删除任务记录
                $this->Records->delete();
                Log::info('job_error', '同步订单详情失败', [$this->order_info]);
                return json_send(['code' => 'error', 'msg' => '获取失败']);
            }
            // 错误提示
            if (isset($result['errcode'])) {
                Log::info('job_error', '同步订单详情失败',[$this->order_info]);
            }
            //删除任务记录

            $this->Records->delete();

            // 成功处理...
        } catch (\Exception $e) {
            // 失败处理...
            if ($this->Records) {
                $this->Records->delete();
            }
            Log::error('job_error', 'OrderDetailJobs处理失败', ['data'=>$this->order_info,'error' => $e->getMessage()]);
        }
    }


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