<?php

namespace App\Jobs\OpenWork\External;

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\DB\DbService;
use App\Models\OpenWork\job\Records;
use App\Facades\Servers\Logs\Log;
use App\Servers\OpenWork\External\CorpTagService;

/**
 * 标签信息同步
 * @author 唐远望
 * @version 1.0
 * @date 2025-08-19
 */
class TagJobs implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $message_data;
    protected $Records;

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            $corpid = $this->message_data['corpid'];
            (new DbService())->getConnectionNameByCorpId($corpid);
            // 创建任务记录
            $this->Records = Records::create([
                'job_id' => $corpid . '_TagJobs',
                'name' => static::class,
                'payload' => json_encode($this->message_data),
                'status' => 'processing',
                'started_at' => now()
            ]);
            $tag = $this->message_data['tag_list'];
            $group_id = $this->message_data['group_id'];
            $follow_tag_list = $this->message_data['follow_tag_list'];
            (new CorpTagService())->handle_corp_tag($corpid,$tag, $group_id, $follow_tag_list);
            //删除任务记录
            $this->Records->delete();
        } catch (\Exception $e) {
            // 失败处理...
            if ($this->Records) {
                $this->Records->delete();
            }
            if (stripos($e->getMessage(), 'UNIQUE_') === false) {
                // 记录错误日志
                Log::info('job_error', 'TagJobs任务队列执行失败', ['data' => $this->message_data, 'error' => $e->getMessage()]);
            }
        }
    }


    public function failed(\Throwable $exception)
    {
        Log::info('job_error', 'TagJobs任务队列执行彻底失败', ['data' => $this->message_data, 'error' => $exception]);
        // 失败处理...
        if ($this->Records) {
            $this->Records->delete();
        }
    }
}
