<?php

namespace App\Jobs\OpenWork\Contact;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Servers\DB\DbService;
use App\Models\OpenWork\job\Records;
use App\Facades\Servers\Logs\Log;
use App\Servers\OpenWork\Group\ChatService;

/**
 * 群信息队列
 * @author 唐远望
 * @date 2025-06-06
 * @version 1.0
 */

class GroupChatJobs implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    private $group_chat_data;
    private $Records;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(array $group_chat_data)
    {
        $this->group_chat_data = $group_chat_data;
    }

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $corpId = $this->group_chat_data['authCorpId'];
        (new DbService())->getConnectionNameByCorpId($corpId);

        // 创建任务记录
        $this->Records = Records::create([
            'job_id' => $this->group_chat_data['authCorpId'] . '_GroupChatJobs',
            'name' => static::class,
            'payload' => json_encode($this->group_chat_data),
            'status' => 'processing',
            'started_at' => now()
        ]);
        $corpid = $this->group_chat_data['authCorpId'];
        $params_data = $this->group_chat_data['params_data'];
        try {
            (new ChatService())->format_group_chat_list_page($corpid, $params_data);
            //删除任务记录
            $this->Records->delete();
        } catch (\Exception $e) {
            // 失败处理...
            if ($this->Records) {
                $this->Records->delete();
            }
            Log::info('job_error', '群信息队列失败-异常原因', ['data'=>$this->group_chat_data,'error' => $e->getMessage()]);
        }
    }


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