<?php

namespace App\Services\AIGeneration;

use App\Models\MpGeneratePicTask;
use App\Services\VolcEngineService;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Consts\BaseConst;

class AIImageGenerationService
{
    private $volcEngineService;
    private $httpClient;

    // 模型常量
    const MODEL_JIMENG_4 = 'jimeng_4.0';

    public function __construct(VolcEngineService $volcEngineService)
    {
        $this->volcEngineService = $volcEngineService;
        $this->httpClient = new Client([
            'timeout' => 300,
        ]);
    }

    /**
     * 异步创建图片生成任务
     *
     * @param array $params
     * @return MpGeneratePicTask
     */
    public function createImageGenerationTask(array $params): MpGeneratePicTask
    {
        // // 获取模型类型，默认使用即梦AI 4.0
        // $model = $params['model'] ?? self::MODEL_JIMENG_4;

        // 获取模型类型，默认使用即梦seedream5.0-lite
        $model = $params['model'] ?? 'doubao-seedream-5-0-lite-260128';
        
        // 检查是否有正在处理的任务（仅即梦AI需要排队）
        if ($model === self::MODEL_JIMENG_4 && $this->hasProcessingTask()) {
            // 如果有正在处理的任务，创建排队任务
            return $this->createQueuedTask($params);
        }

        // 生成唯一的任务ID
        $taskId = 'img_gen_' . time() . '_' . uniqid();

        // 创建任务记录
        $task = MpGeneratePicTask::create([
            'task_id' => $taskId,
            'alias_segment_id' => $params['alias_segment_id'] ?? 0,
            'prompt' => $params['prompt'] ?? '',
            'width' => $params['width'] ?? 2048,
            'height' => $params['height'] ?? 2048,
            'image_num' => $params['image_num'] ?? 1,
            'scale' => $params['scale'] ?? 50,
            'ref_img_url' => $params['ref_img_urls'] ?? null,
            'mask_img_url' => $params['mask_img_url'] ?? null,
            'extra_params' => $params['extra_params'] ?? null,
            'status' => MpGeneratePicTask::STATUS_PENDING,
            'model' => $model,
        ]);

        // 仅即梦AI立即提交任务，火山API在定时任务中提交
        if ($model === self::MODEL_JIMENG_4) {
            $this->submitTaskToJimengApi($task);
        }

        return $task;
    }

    /**
     * 检查是否有正在处理的任务
     *
     * @return bool
     */
    private function hasProcessingTask(): bool
    {
        return MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PROCESSING)
            ->exists();
    }

    /**
     * 创建排队任务
     *
     * @param array $params
     * @return MpGeneratePicTask
     */
    private function createQueuedTask(array $params): MpGeneratePicTask
    {
        // 生成唯一的任务ID
        $taskId = 'img_gen_' . time() . '_' . uniqid();
        
        // 获取模型类型
        $model = $params['model'] ?? self::MODEL_JIMENG_4;

        // 创建排队状态的任务记录
        return MpGeneratePicTask::create([
            'task_id' => $taskId,
            'alias_segment_id' => $params['alias_segment_id'] ?? 0,
            'prompt' => $params['prompt'] ?? '',
            'width' => $params['width'] ?? 2048,
            'height' => $params['height'] ?? 2048,
            'image_num' => $params['image_num'] ?? 1,
            'scale' => $params['scale'] ?? 50,
            'ref_img_url' => $params['ref_img_urls'] ?? null,
            'mask_img_url' => $params['mask_img_url'] ?? null,
            'extra_params' => $params['extra_params'] ?? null,
            'status' => MpGeneratePicTask::STATUS_PENDING,
            'model' => $model,
        ]);
    }

    /**
     * 提交任务到即梦AI API
     *
     * @param MpGeneratePicTask $task
     * @return void
     */
    private function submitTaskToJimengApi(MpGeneratePicTask $task): void
    {
        try {
            // 验证环境变量配置
            $accessKey = env('VOLC_AI_AK');
            $secretKey = env('VOLC_AI_SK');
                
            if (empty($accessKey) || empty($secretKey)) {
                $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
                    'error_message' => '火山引擎访问密钥未配置，请检查环境变量AK和SK'
                ]);
                return;
            }
                
            //构建即梦AI 4.0 API请求参数
            $apiParams = [
                'req_key' => 'jimeng_t2i_v40',
                'prompt' => $task->prompt,
                'scale' => $task->scale / 100, //为0-1范围
            ];
            
            // 添加可选参数
            if ($task->image_num > 1) {
                $apiParams['force_single'] = false;
            } else {
                $apiParams['force_single'] = true;
            }
            
            // 参考图片
            if ($task->ref_img_url) {
                $apiParams['image_urls'] = $task->ref_img_url;
            }
                        
            // if ($task->mask_img_url) {
            //     $apiParams['image_urls'] = $task->mask_img_url;
            // }
            
            // 尺寸参数
            $area = $task->width * $task->height; //计算面积
            if ($area >= 1024*1024 && $area <= 4096*4096) {
                $apiParams['size'] = (int)$area;
            }

            dLog('generate')->info('即梦AI文生图参数: ', $apiParams);
            logDB('generate', 'info', '即梦AI文生图任务提交', ['task_id' => $task->task_id, 'params' => $apiParams]);
            
            //调用即梦AI 4.0 API提交任务
            $response = $this->volcEngineService->request(
                'POST',
                'visual.volcengineapi.com', //即梦AI API域名
                '/', // 使用根路径
                [], // Query参数
                json_encode($apiParams),
                $accessKey,
                $secretKey,
                'cv', // 服务标识
                'cn-north-1', //区域
                'CVSync2AsyncSubmitTask',
                '2022-08-31',
                'application/json'
            );
    
            $responseData = json_decode($response['body'], true);
            dLog('generate')->info('即梦AI 4.0 API提交任务响应: ', $responseData);
            logDB('generate', 'info', '即梦AI 4.0 API提交任务响应', ['task_id' => $task->task_id, 'response' => $responseData]);
                
            if ($responseData['code'] !== 10000) {
                // API返回错误
                logDB('generate', 'error', '即梦AI任务提交失败', ['task_id' => $task->task_id, 'error' => $responseData['message'] ?? 'API Error']);
                $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
                    'error_message' => $responseData['message'] ?? 'API Error',
                    'extra_params' => $responseData['data'] ?? []
                ]);
            } else {
                // 任务提交成功，更新状态为处理中
                $updateData = [];
                //存储API返回的任务ID
                if (isset($responseData['data']['task_id'])) {
                    $updateData['task_id'] = $responseData['data']['task_id'];
                    $updateData['extra_params'] = $responseData ?? [];
                }
    
                $task->updateStatus(MpGeneratePicTask::STATUS_PROCESSING, $updateData);
            }
        } catch (\Exception $e) {
            // 记录错误
            logDB('generate', 'error', '即梦AI任务提交异常', ['task_id' => $task->task_id, 'error' => $e->getMessage()]);
            $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
                'error_message' => 'API请求失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 提交任务到火山图片生成API
     *
     * @param MpGeneratePicTask $task
     * @return void
     */
    public function submitTaskToVolcApi(MpGeneratePicTask $task): void
    {
        try {
            // 验证环境变量配置
            $apiKey = env('VOLC_AI_API_KEY');
                
            if (empty($apiKey)) {
                $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
                    'error_message' => '火山引擎API KEY未配置，请检查环境变量VOLC_AI_API_KEY'
                ]);
                return;
            }
            
            // 更新状态为处理中
            $task->updateStatus(MpGeneratePicTask::STATUS_PROCESSING);
                
            // 构建火山图片生成API请求参数
            $apiParams = [
                'model' => isset(BaseConst::MODELS_MAP[$task->model]) ? BaseConst::MODELS_MAP[$task->model] : $task->model,
                'prompt' => $task->prompt,
                'watermark' => false,
            ];
            
            // 尺寸参数
            if ($task->width && $task->height) {
                $apiParams['size'] = $task->width . 'x' . $task->height;
            }
            
            // 参考图片
            if ($task->ref_img_url) {
                if (is_array($task->ref_img_url)) {
                    // $apiParams['image'] = count($task->ref_img_url) === 1 ? $task->ref_img_url[0] : $task->ref_img_url;
                    $apiParams['image'] = $task->ref_img_url;
                } else {
                    $apiParams['image'] = $task->ref_img_url;
                }
            }

            // 生成多图或者单图
            if ((int)$task->image_num === 1) {
                $apiParams['sequential_image_generation'] = 'disabled';
            }else if ($task->image_num > 1) {
                $apiParams['sequential_image_generation'] = 'auto';
                $apiParams['sequential_image_generation_options']['max_images'] = $task->image_num;
            }

            dLog('generate')->info('火山图片生成API参数: ', $apiParams);
            logDB('generate', 'info', '火山图片生成任务提交', ['task_id' => $task->task_id, 'params' => $apiParams]);
            
            // 调用火山图片生成API
            $response = $this->httpClient->post('https://ark.cn-beijing.volces.com/api/v3/images/generations', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $apiKey,
                    'Content-Type' => 'application/json',
                ],
                'json' => $apiParams,
            ]);
    
            $responseData = json_decode($response->getBody()->getContents(), true);
            dLog('generate')->info('火山图片生成API响应: ', $responseData);
            logDB('generate', 'info', '火山图片生成API响应', ['task_id' => $task->task_id, 'response' => $responseData]);
                
            if (isset($responseData['error'])) {
                // API返回错误
                logDB('generate', 'error', '火山图片生成任务失败', ['task_id' => $task->task_id, 'error' => $responseData['error']['message'] ?? 'API Error']);
                $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
                    'error_message' => $responseData['error']['message'] ?? 'API Error',
                    'result_json' => $responseData
                ]);
            } else {
                // 任务提交成功，直接处理结果
                $this->processVolcApiResponse($task, $responseData);
            }
        } catch (\Exception $e) {
            // 记录错误
            dLog('generate')->error('火山API请求失败: ' . $e->getMessage());
            logDB('generate', 'error', '火山图片生成任务异常', ['task_id' => $task->task_id, 'error' => $e->getMessage()]);
            $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
                'error_message' => 'API请求失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 处理火山API响应结果
     *
     * @param MpGeneratePicTask $task
     * @param array $responseData
     * @return void
     */
    private function processVolcApiResponse(MpGeneratePicTask $task, array $responseData): void
    {
        try {
            if (!isset($responseData['data']) || empty($responseData['data'])) {
                $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
                    'error_message' => '未返回图片数据',
                    'result_json' => $responseData
                ]);
                return;
            }

            $result_urls = [];
            foreach ($responseData['data'] as $imageData) {
                if (isset($imageData['error'])) {
                    // 单张图片生成失败
                    dLog('generate')->warning('单张图片生成失败: ', $imageData['error']);
                    continue;
                }

                if (isset($imageData['url'])) {
                    $url = $imageData['url'];
                    $pic_name = 'ai_generation_' . time() . '_' . uniqid();
                    $pic_ext = getImgExtFromUrl($url);
                    $pic_name = $pic_name . $pic_ext;
                    
                    if ($pic_ext === '.png') {
                        $comporessed_data = compressRemoteImageUrlToSize($url);
                        $url = uploadStreamByTos('image', $comporessed_data, $pic_name);
                    } else {
                        // 将图片另存到tos
                        $url = uploadStreamByTos('image', file_get_contents($url), $pic_name);
                    }
                    
                    $result_urls[] = $url;
                }
            }

            if (empty($result_urls)) {
                $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
                    'error_message' => '所有图片生成失败',
                    'result_json' => $responseData
                ]);
                return;
            }

            // 更新任务状态为成功
            $task->updateStatus(MpGeneratePicTask::STATUS_SUCCESS, [
                'result_url' => $result_urls,
                'result_json' => $responseData
            ]);

            // 同步调整分镜图片状态和结果
            $segment_id = getProp($task, 'alias_segment_id');
            if ($segment_id) {
                DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
                    'img_url' => $result_urls[0],
                    'pic_task_status' => '已完成',
                ]);
                
                // 如果是首帧图ID则更新anime表
                if (Redis::sismember('anime_first_frame_urls', $segment_id)) {
                    $anime_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('anime_id');
                    DB::table('mp_animes')->where('id', $anime_id)->update(['first_frame_url' => $result_urls[0], 'updated_at' => date('Y-m-d H:i:s')]);
                    Redis::srem('anime_first_frame_urls', $segment_id);
                }
            }
        } catch (\Exception $e) {
            $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
                'error_message' => '处理响应失败: ' . $e->getMessage()
            ]);
        }
    }

    public function getTaskList($data)
    {
        $task_id = getProp($data, 'task_id');
        $status = getProp($data, 'status');

        $query = MpGeneratePicTask::select('*');
        if ($task_id) {
            $query->where('id', $task_id);
        }
        if ($status) {
            $query->where('status', $status);
        }

        return $query->orderBy('created_at', 'desc')->paginate();
    }

    /**
     * 查询任务状态
     *
     * @param MpGeneratePicTask $task
     * @return array
     */
    public function queryTaskStatus(MpGeneratePicTask $task): array
    {
        // 根据模型类型调用不同的查询方法
        if ($task->model === self::MODEL_JIMENG_4) {
            return $this->queryJimengTaskStatus($task);
        } else {
            // 火山API是同步返回结果，不需要查询
            return [
                'status' => $task->status === MpGeneratePicTask::STATUS_SUCCESS ? 'success' : 'failed',
                'error_message' => $task->error_message,
                'result_url' => $task->result_url,
                'result_json' => $task->result_json ?? []
            ];
        }
    }

    /**
     * 查询即梦AI任务状态
     *
     * @param MpGeneratePicTask $task
     * @return array
     */
    private function queryJimengTaskStatus(MpGeneratePicTask $task): array
    {
        try {
            // 获取API任务ID
            $apiTaskId = $task->task_id ?? null;
                
            if (!$apiTaskId) {
                return [
                    'status' => 'failed',
                    'error_message' => 'API任务ID不存在',
                    'result_url' => null
                ];
            }
    
            //构建查询参数
            $apiParams = [
                'req_key' => 'jimeng_t2i_v40',
                'task_id' => $apiTaskId,
                'req_json' => '{"return_url":true}' // 返回URL格式
            ];
    
            //调用即梦AI 4.0 API查询任务状态
            $response = $this->volcEngineService->request(
                'POST',
                'visual.volcengineapi.com',
                '/', // 使用根路径
                [], // Query参数
                json_encode($apiParams),
                env('VOLC_AI_AK'),
                env('VOLC_AI_SK'),
                'cv',
                'cn-north-1',
                'CVSync2AsyncGetResult',
                '2022-08-31',
                'application/json'
            );
    
            $responseData = json_decode($response['body'], true);
            dLog('generate')->info('即梦AI 4.0 API查询任务状态响应: ', $responseData);
            logDB('generate', 'info', '即梦AI任务状态查询', ['task_id' => $apiTaskId, 'response' => $responseData]);
    
            if ($responseData['code'] !== 10000) {
                // API返回错误
                logDB('generate', 'error', '即梦AI任务状态查询失败', ['task_id' => $apiTaskId, 'error' => $responseData['message'] ?? 'API Error']);
                return [
                    'status' => 'failed',
                    'error_message' => $responseData['message'] ?? 'API Error',
                    'result_url' => null,
                    'result_json' => $responseData ?? []
                ];
            }
    
            // 解析API响应
            $result = $responseData['data'] ?? [];
            $taskStatus = $result['status'] ?? 'failed';
    
            $returnData = [
                'status' => $taskStatus,
                'error_message' => null,
                'result_url' => null,
                'result_json' => $responseData ?? []
            ];
    
            // 如果任务成功，获取结果URL
            if ($taskStatus === 'done' && isset($result['image_urls']) && count($result['image_urls']) > 0) {
                $result_urls = [];
                foreach ($result['image_urls'] as $url) {
                    $pic_name = 'ai_generation_' . time() . '_' . uniqid();
                    $pic_ext = getImgExtFromUrl($url);
                    $pic_name = $pic_name . $pic_ext;
                    
                    if ($pic_ext === '.png') {
                        $comporessed_data = compressRemoteImageUrlToSize($url);
                        $url = uploadStreamByTos('image', $comporessed_data, $pic_name);
                    }else {
                        // 将图片另存到tos
                        $url = uploadStreamByTos('image', file_get_contents($url), $pic_name);
                    }
                    
                    $result_urls[] = $url;
                }
                $returnData['result_url'] = $result_urls;
                $returnData['status'] = 'success';
            } elseif (in_array($taskStatus, ['not_found', 'expired'])) {
                $returnData['status'] = 'failed';
                $returnData['error_message'] = '任务未找到或已过期';
            } elseif ($taskStatus === 'failed') {
                $returnData['status'] = 'failed';
                $returnData['error_message'] = '任务执行失败';
            }
            // in_queue 或 generating状态保持原status
    
            return $returnData;
        } catch (\Exception $e) {
            return [
                'status' => 'failed',
                'error_message' => $e->getMessage(),
                'result_url' => null
            ];
        }
    }

    /**
     * 更新所有待处理任务的状态
     *
     * @return void
     */
    public function updatePendingTasks(): void
    {
        dLog('generate')->info('更新图片状态ing');
        logDB('generate', 'info', '开始更新图片生成任务状态', []);
        
        // 1. 处理火山API的pending任务（批量提交到队列）
        $volcPendingTasks = MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PENDING)
            ->whereIn('model', BaseConst::VOLC_PIC_MODELS)
            ->orderBy('created_at', 'asc')
            ->limit(50) // 每次最多处理50个任务，避免超时
            ->get();

        foreach ($volcPendingTasks as $task) {
            dLog('generate')->info('开始分发火山API任务到队列: ' . $task->task_id);
            logDB('generate', 'info', '分发火山API任务到队列', ['task_id' => $task->task_id]);
            
            // 分发到队列
            \App\Jobs\ProcessVolcImageGenerationJob::dispatch($task->id)->onConnection('redis');
        }
        
        // 2. 获取所有处理中的任务（仅即梦AI需要查询状态）
        $processingTasks = MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PROCESSING)
            ->where('model', self::MODEL_JIMENG_4)
            ->get();

        foreach ($processingTasks as $task) {
            $statusInfo = $this->queryTaskStatus($task);

            if ($statusInfo['status'] === 'success') {
                logDB('generate', 'info', '即梦AI图片生成任务成功', ['task_id' => $task->task_id, 'result_url' => $statusInfo['result_url']]);
                $task->updateStatus(MpGeneratePicTask::STATUS_SUCCESS, [
                    'result_url'    => $statusInfo['result_url'],
                    'result_json'   => $statusInfo['result_json'] ?? []
                ]);

                // 同步调整分镜图片状态和结果
                $segment_id = getProp($task, 'alias_segment_id');
                if ($segment_id) {
                    DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
                        'img_url'   => $statusInfo['result_url'][0],
                        'pic_task_status'   => '已完成',
                    ]);
                    
                    // 如果是首帧图ID则更新anime表
                    if (Redis::sismember('anime_first_frame_urls', $segment_id)) {
                        $anime_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('anime_id');
                        DB::table('mp_animes')->where('id', $anime_id)->update(['first_frame_url'=>$statusInfo['result_url'][0], 'updated_at'=>date('Y-m-d H:i:s')]);
                        Redis::srem('anime_first_frame_urls', $segment_id);
                    }
                }
            } elseif ($statusInfo['status'] === 'failed') {
                logDB('generate', 'error', '即梦AI图片生成任务失败', ['task_id' => $task->task_id, 'error' => $statusInfo['error_message']]);
                $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
                    'error_message' => $statusInfo['error_message'],
                    'result_json'   => $statusInfo['result_json'] ?? []
                ]);

                if (getProp($task, 'alias_segment_id')) {
                    DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
                        'pic_task_status'   => '失败',
                    ]);
                }
            }
            // 如果仍然是处理中状态，不做任何操作
            
            //处理：如果任务处理超过12小时，标记为失败
            $processingTime = now()->diffInHours($task->created_at);
            if ($processingTime > 12) {
                logDB('generate', 'warning', '即梦AI图片生成任务超时', ['task_id' => $task->task_id, 'processing_hours' => $processingTime]);
                $task->updateStatus(MpGeneratePicTask::STATUS_FAILED, [
                    'error_message' => '任务处理超时（超过12小时）'
                ]);
            }
        }

        // 3. 检查是否有任务完成，如果有则处理下一个排队任务（仅即梦AI）
        $this->processNextQueuedTask();
    }

    /**
     * 处理下一个排队的任务
     *
     * @return void
     */
    public function processNextQueuedTask(): void
    {
        // 检查是否还有正在处理的任务（仅即梦AI）
        if ($this->hasProcessingTask()) {
            return; // 如果还有处理中的任务，不处理新任务
        }

        // 获取最早的待处理任务（仅即梦AI）
        $nextTask = MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PENDING)
            ->where('model', self::MODEL_JIMENG_4)
            ->orderBy('created_at', 'asc')
            ->first();

        if ($nextTask) {
            dLog('generate')->info('开始处理排队任务: ' . $nextTask->task_id);
            logDB('generate', 'info', '开始处理即梦AI排队任务', ['task_id' => $nextTask->task_id]);
            $this->submitTaskToJimengApi($nextTask);
        }
    }

    /**
     * 获取任务队列状态
     *
     * @return array
     */
    public function getQueueStatus(): array
    {
        $processingCount = MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PROCESSING)->count();
        $pendingCount = MpGeneratePicTask::where('status', MpGeneratePicTask::STATUS_PENDING)->count();
        
        return [
            'processing_count' => $processingCount,
            'pending_count' => $pendingCount,
            'can_submit_new_task' => $processingCount === 0
        ];
    }
}