<?php

namespace App\Jobs;

use App\Models\MpGeneratePicTask;
use App\Services\AIGeneration\AIImageGenerationService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ProcessVolcImageGenerationJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 任务最大尝试次数
     *
     * @var int
     */
    public $tries = 3;

    /**
     * 任务超时时间（秒）
     *
     * @var int
     */
    public $timeout = 300;

    /**
     * 任务ID
     *
     * @var int
     */
    protected $taskId;

    /**
     * 创建一个新的任务实例
     *
     * @param int $taskId
     * @return void
     */
    public function __construct(int $taskId)
    {
        $this->taskId = $taskId;
        $this->onQueue('{GenerateVolcPics}');
    }

    /**
     * 执行任务
     *
     * @param AIImageGenerationService $service
     * @return void
     */
    public function handle(AIImageGenerationService $service)
    {
        try {
            // 查找任务
            $task = MpGeneratePicTask::find($this->taskId);
            
            if (!$task) {
                dLog('generate')->error('队列任务：找不到图片生成任务', ['task_id' => $this->taskId]);
                logDB('generate', 'error', '队列任务：找不到图片生成任务', ['task_id' => $this->taskId]);
                return;
            }

            // 检查任务状态，只处理pending状态的任务
            if ($task->status !== MpGeneratePicTask::STATUS_PENDING) {
                dLog('generate')->info('队列任务：任务状态不是pending，跳过处理', [
                    'task_id' => $this->taskId,
                    'status' => $task->status
                ]);
                return;
            }

            dLog('generate')->info('队列任务：开始处理火山API图片生成任务', ['task_id' => $this->taskId]);

            // 调用服务方法提交任务到火山API
            $service->submitTaskToVolcApi($task);

            dLog('generate')->info('队列任务：火山API图片生成任务处理完成', ['task_id' => $this->taskId]);

        } catch (\Exception $e) {
            dLog('generate')->error('队列任务：处理火山API图片生成任务失败', [
                'task_id' => $this->taskId,
                'error' => $e->getMessage()
            ]);
            logDB('generate', 'error', '队列任务：处理火山API图片生成任务失败', [
                'task_id' => $this->taskId,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            // 重新抛出异常，让队列系统处理重试
            throw $e;
        }
    }

    /**
     * 任务失败时的处理
     *
     * @param \Throwable $exception
     * @return void
     */
    public function failed(\Throwable $exception)
    {
        dLog('generate')->error('队列任务：火山API图片生成任务最终失败', [
            'task_id' => $this->taskId,
            'error' => $exception->getMessage()
        ]);
        logDB('generate', 'error', '队列任务：火山API图片生成任务最终失败', [
            'task_id' => $this->taskId,
            'error' => $exception->getMessage(),
            'attempts' => $this->attempts()
        ]);

        // 更新任务状态为失败
        try {
            $task = MpGeneratePicTask::find($this->taskId);
            if ($task && $task->status === MpGeneratePicTask::STATUS_PENDING) {
                $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
                    'error_message' => '队列任务处理失败: ' . $exception->getMessage()
                ]);
            }
        } catch (\Exception $e) {
            dLog('generate')->error('队列任务：更新任务状态失败', [
                'task_id' => $this->taskId,
                'error' => $e->getMessage()
            ]);
        }
    }
}
