<?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\Facades\Servers\Wechat\OpenWork;
use App\Models\OpenWork\job\Records;
use Illuminate\Support\Facades\DB;

/**
 * 订单同步队列
 * @author 
 * @version 1.0
 * @date 2025-04-14
 */
class OrderJobs implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

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


    }

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

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

        //
        $corpId = $this->order_data_info['authCorpId'];
        (new DbService())->getConnectionNameByCorpId($corpId);
        // 创建任务记录
        $this->Records = Records::create([
            'job_id' => $this->order_data_info['authCorpId'] . '_OrderJobs',
            'name' => static::class,
            'payload' => json_encode($this->order_data_info),
            'status' => 'processing',
            'started_at' => now()
        ]);

        $authCorpId = $this->order_data_info['authCorpId'];
        $startTime = $this->order_data_info['startTime'];
        $endTime = $this->order_data_info['endTime'];
        $cursor = $this->order_data_info['cursor'];
        $limit = $this->order_data_info['limit'];
        try {
            // 获取实例,
            $app            = OpenWork::getApp();
            // 数据结果
            $result         = $app->license_order->list($authCorpId, $startTime, $endTime, $cursor, $limit);
            // 如果获取结果失败
            if (!$result)  return json_send(['code' => 'error', 'msg' => '获取失败']);
            // 错误提示
            if ($result['errcode']) return json_send(['code' => 'error', 'msg' => OpenWork::getErrmsg($result['errcode'])]);
            //同步本地订单数据
            $sync_status = (new LicenseOrderService())->handle_order_data($authCorpId, $result['order_list']);
            // 列表结果
            $next_cursor = $result['next_cursor'];
            if ($next_cursor != '' && $sync_status && count($result['order_list']) > 0) {
                //添加队列处理订单数据
                $order_data_info = [
                    'authCorpId' => $authCorpId,
                    'startTime' => $startTime,
                    'endTime' => $endTime,
                    'cursor' => $next_cursor,
                    'limit' => $limit
                ];
                $queueName = $authCorpId.'_OrderJobs';
                OrderJobs::dispatch($order_data_info);//如果还有数据继续执行同步
            }
            //删除任务记录
            $this->Records->delete();
        } catch (\Exception $e) {
            // 失败处理...
            if ($this->Records) {
                $this->Records->delete();
            }
            Log::info('job_error', '同步订单账号激活码失败-异常原因',['data'=>$this->order_data_info,'error' => $e->getMessage()]);
        }
    }

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