<?php

namespace App\Jobs\OpenWork\LicenseOrder;

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\Facades\Servers\Wechat\OpenWork;
use App\Models\OpenWork\License\ClientOrderAccount;
use App\Facades\Servers\Logs\Log;
use App\Models\OpenWork\job\Records;
use App\Models\OpenWork\Contact\UserActiveLog;
use Illuminate\Support\Facades\DB;

/**
 * 激活码用户绑定更新数据更新队列
 * @author 唐远望
 * @version 1.0
 * @date 2025-04-10
 */
class AccountCodeJobs implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

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

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $active_code_info = $this->active_code_info;
        $corpid         = $active_code_info['corpid'];
        $active_code    = $active_code_info['active_code'];
        $order_id       = $active_code_info['order_id'];
        (new DbService())->getConnectionNameByCorpId($corpid);
        $this->Records = Records::create([
            'job_id' =>  $this->active_code_info['corpid'] . '_AccountCodeJobs',
            'name' => static::class,
            'payload' => json_encode($this->active_code_info),
            'status' => 'processing',
            'started_at' => now()
        ]);
        $clientOrderAccountmODEL = new ClientOrderAccount();
        $UserActiveLog =new UserActiveLog();
        // 处理激活码用户绑定更新数据
        $app            = OpenWork::getApp();
        // 数据结果
        $result         = $app->license_account->getActiveCodeInfo($corpid, $active_code);
        if (!$result) {
            //删除任务记录
            $this->Records->delete();
            Log::info('job_error', '未找到激活码绑定用户数据-接口查询失败',[$active_code_info]);
            return true;
        }
        // 错误提示
        if ($result['errcode']) {
            //删除任务记录
            $this->Records->delete();
            Log::info('job_error', '激活码数据异常-查询错误', [$result]);
            return true;
        }
        // 处理数据
        if (!isset($result['active_info']['userid'])) {
            //删除任务记录
            $this->Records->delete();
            Log::info('job_error', '未找到激活码绑定用户数据', [$active_code_info]);
            return true;
        }
        $wheres = ['corpid' => $corpid, 'active_code' => $active_code];
        //查询数据
        $client_order_account = $clientOrderAccountmODEL->where($wheres)->first();
        $user_active_log_data=$UserActiveLog->where($wheres)->first();
        if (!$client_order_account) {
            //删除任务记录
            $this->Records->delete();
            Log::info('job_error', '未找到激活码绑定用户数据-本地数据库查询失败', [$wheres]);
            return true;
        };
        try {
            // 更新数据
            $update_data    = [
                'userid' => $result['active_info']['userid'],
                'account_expire_time' => $result['active_info']['expire_time'],
                'account_active_time' => $result['active_info']['active_time'],
                'status' => isset($result['active_info']['userid']) ? 2 : $client_order_account->status, //状态0=正常1=无效2=已使用
            ];
            // 更新数据
            $clientOrderAccountmODEL->where($wheres)->update($update_data);
            if($user_active_log_data){
                $UserActiveLog->where($wheres)->update(['account_expire_time' => $result['active_info']['expire_time'],'account_active_time' => $result['active_info']['active_time']]);
            };
            //删除任务记录
            $this->Records->delete();
            // 成功处理...
        } catch (\Exception $e) {
            // 失败处理...
            if ($this->Records) {
                $this->Records->delete();
            }
            Log::info('job_error', 'AccountCodeJobs任务队列失败', ['data'=>$this->active_code_info,'error' => $e->getMessage()]);
        }
    }

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