request->param(); $service = new ImageService(); $service->handleImage($params); $this->success('任务成功提交至队列'); } /** * product 产品专用统一api调用接口 * AI模型调用接口 */ public function GetTxtToTxt(){ $params = $this->request->param(); $prompt = $params['prompt'];//提示词 $old_path = $params['path'] ?? '';//原图路径 $model = $params['model'];//模型 if(empty($model)) { return json(['code' => 1, 'msg' => '模型请求失败']); } $aiGateway = new AIGatewayService(); $service = new ImageService(); if($params['status_val'] == '图生文'){ $service->handleImgToText($params); $res = [ 'code' => 0, 'msg' => '正在优化提示词,请稍等.....' ]; return json($res); }else if($params['status_val'] == '文生文'){ $fullPrompt = $prompt; $fullPrompt .= " 请根据上述内容生成一段完整的话术,要求: 1. 内容必须是连贯的一段话,不要使用列表、分隔线或其他结构化格式 2. 不要包含非文本元素的描述 3. 不要添加任何额外的引导语、解释或开场白 4. 语言流畅自然"; $result = $service->handleTextToText($fullPrompt, $model); if(!empty($params['id'])){ Db::name('product')->where('id', $params['id'])->update(['content' => $result['data']]); } $res = [ 'code' => 0, 'msg' => '优化成功', 'content' => $result['data'] ]; return json($res); }elseif($params['status_val'] == '文生图'){ $service->handleTextToImg($params); $res = [ 'code' => 0, 'msg' => '正在生成图片中,请稍等.....' ]; return json($res); }else{ $this->error('请求失败'); } } public function GetTxtToImg(){ $params = $this->request->param(); $prompt = $params['prompt'];//提示词 $model = $params['model'];//模型 $size = $params['size'];//尺寸 // 调用AI生成图片 $aiGateway = new AIGatewayService(); $res = $aiGateway->callDalleApi($prompt, $model, $size); // 提取base64图片数据 $imageData = ''; $imageType = 'png'; // 默认图片类型 if (isset($res['candidates'][0]['content']['parts'][0]['text'])) { $text_content = $res['candidates'][0]['content']['parts'][0]['text']; // 匹配base64图片数据和类型 if (preg_match('/data:image\/([a-zA-Z0-9]+);base64,([^\s]+)/', $text_content, $matches)) { $imageType = strtolower($matches[1]); $base64Data = $matches[2]; // 解码base64数据 $imageData = base64_decode($base64Data); } } if (!$imageData) { return json(['code' => 1, 'msg' => '图片生成失败,未找到有效图片数据']); } // 创建保存目录(public/uploads/log/YYYY-MM/) $yearMonth = date('Ym'); $saveDir = ROOT_PATH . 'public/uploads/log/' . $yearMonth . '/'; if (!is_dir($saveDir)) { mkdir($saveDir, 0755, true); } // 生成唯一文件名 $fileName = uniqid() . '.' . $imageType; $filePath = $saveDir . $fileName; // 保存图片到本地文件 if (file_put_contents($filePath, $imageData) === false) { return json(['code' => 1, 'msg' => '图片保存失败']); } // 生成前端可访问的URL $imageUrl = '/uploads/log/' . $yearMonth . '/' . $fileName; // 返回标准JSON响应 return json([ 'code' => 0, 'msg' => '图片生成成功', 'data' => [ 'url' => $imageUrl // 'url' => '/uploads/log/202601/695b141099d1e.jpeg' ] ]); } /** * 学生端文生视频接口 - 用于生成视频 */ public function GetTxtToVideo(){ // 获取并验证参数 $params = $this->request->param(); // echo "
";
//    print_r($params);
//    echo "
";die;

        // 正常的视频生成请求处理
        $apiUrl = 'https://chatapi.onechats.ai/v1/videos';
        $apiKey = 'sk-ABO93U8p7u6Sin4yxnAHI8Z8K9hX8YjRO9rfTC0y3Ftv4mNm';

        $postData = [
            'prompt' => $params['prompt'],
            'model' => $params['model'],
            'seconds' => $params['duration'],
            'size' => $params['size'],
        ];

        // 初始化CURL
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $apiKey
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 300);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_HEADER, true); // 获取响应头
        curl_setopt($ch, CURLOPT_VERBOSE, true); // 启用详细输出以进行调试
        // 创建临时文件来捕获详细的cURL输出
        $verbose = fopen('php://temp', 'w+');
        curl_setopt($ch, CURLOPT_STDERR, $verbose);
        // 执行请求
        $response = curl_exec($ch);
        //HTTP状态码
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        // 获取详细的cURL调试信息
        rewind($verbose);
        //CURL调试信息
        $verboseLog = stream_get_contents($verbose);
        fclose($verbose);
        // 分离头部和主体
        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        //响应头部
        $header = substr($response, 0, $header_size);
        //响应主体
        $body = substr($response, $header_size);
        // 检查CURL错误
        $curlError = curl_error($ch);
        curl_close($ch);

        $responseData = json_decode($body, true);

        // 检查API是否返回了错误信息
        if (isset($responseData['error'])) {
            $errorMessage = isset($responseData['error']['message']) ? $responseData['error']['message'] : 'API请求失败';
            return json([
                'code' => 1,
                'msg' => '视频生成请求失败',
                'data' => [
                    'error_type' => isset($responseData['error']['type']) ? $responseData['error']['type'] : 'unknown',
                    'error_code' => isset($responseData['error']['code']) ? $responseData['error']['code'] : 'unknown',
                    'error_message' => $errorMessage
                ]
            ]);
        }

        // 检查是否有自定义错误格式
        if (isset($responseData['code']) && $responseData['code'] === 'fail_to_fetch_task' && isset($responseData['message'])) {
            return json([
                'code' => 1,
                'msg' => '视频生成请求失败',
                'data' => [
                    'error_code' => $responseData['code'],
                    'error_message' => $responseData['message']
                ]
            ]);
        }

        // 检查是否存在id字段
        if (!isset($responseData['id'])) {
            return json([
                'code' => 1,
                'msg' => '无法获取视频ID',
                'data' => [
                    'response_data' => $responseData,
                    'http_code' => $httpCode
                ]
            ]);
        }

        // 1. 先检查视频状态
        $statusUrl = 'https://chatapi.onechats.ai/v1/videos/' . $responseData['id'];
        $statusData = $this->fetchVideoStatus($statusUrl, $apiKey);

        // 检查视频状态
        if ($statusData['status'] !== 'completed') {
            return json([
                'code' => 202,
                'msg' => '视频尚未生成完成',
                'data' => [
                    'video_id' => $responseData['id'],
                    'status' => $statusData['status'],
                    'progress' => $statusData['progress'],
                    'created_at' => $statusData['created_at'],
                    'message' => '请稍后再试,视频仍在' . ($statusData['status'] === 'queued' ? '排队中' : '处理中')
                ]
            ]);
        }

        // 2. 视频生成完成,准备下载
        $apiUrl = 'https://chatapi.onechats.ai/v1/videos/' . $responseData['id'] . '/content';

        // 获取可选的variant参数
        $variant = $this->request->get('variant', '');
        if (!empty($variant)) {
            $apiUrl .= '?variant=' . urlencode($variant);
        }

        // 创建保存目录
        $saveDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'videos' . DS . date('Ymd');
        if (!is_dir($saveDir)) {
            mkdir($saveDir, 0755, true);
        }

        // 生成唯一文件名
        $filename = $responseData['id'] . '.mp4';
        $localPath = DS . 'uploads' . DS . 'videos' . DS . date('Ymd') . DS . $filename;
        $fullPath = $saveDir . DS . $filename;

        // 3. 下载视频
        $videoData = $this->downloadVideo($apiUrl, $apiKey);

        // 4. 保存视频文件
        if (file_put_contents($fullPath, $videoData) === false) {
            throw new Exception('视频保存失败');
        }

        // 确保路径使用正斜杠,并只保存相对路径部分
        $localPath = str_replace('\\', '/', $localPath);
        // 移除开头的斜杠,确保路径格式为uploads/videos/...
        $savePath = ltrim($localPath, '/');

        // 返回成功响应
        return json([
            'code' => 0,
            'msg' => '视频下载成功',
            'data' => [
                'video_id' => $responseData['id'],
                'web_url' => $savePath
            ]
        ]);
    }

    /**
     * 学生端视频状态查询接口 - 用于通过video_id查询视频状态
     */
    public function Getvideo_id(){
        // 获取并验证参数
        $params = $this->request->param();
        $videoId = $params['video_id'] ?? '';

        // 验证video_id参数
        if (empty($videoId)) {
            return json([
                'code' => 1,
                'msg' => '缺少必要参数:video_id',
                'data' => []
            ]);
        }

        $apiUrl = 'https://chatapi.onechats.ai/v1/videos/' . $videoId;
        $apiKey = 'sk-ABO93U8p7u6Sin4yxnAHI8Z8K9hX8YjRO9rfTC0y3Ftv4mNm';

        // 先检查本地是否已经有该视频
        $localVideoPath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'videos' . DS . date('Ymd') . DS . $videoId . '.mp4';
        if (file_exists($localVideoPath)) {
            // 视频已存在本地,直接返回
            $webPath = '/uploads/videos/' . date('Ymd') . '/' . $videoId . '.mp4';
            return json([
                'code' => 0,
                'msg' => '视频下载成功',
                'data' => [
                    'video_id' => $videoId,
                    'web_url' => substr($webPath, 1) // 移除开头的斜杠
                ]
            ]);
        }

        // 检查视频状态
        $statusData = $this->fetchVideoStatus($apiUrl, $apiKey);

        // 检查视频状态
        if ($statusData['status'] !== 'completed') {
            return json([
                'code' => 202,
                'msg' => '视频尚未生成完成',
                'data' => [
                    'video_id' => $videoId,
                    'status' => $statusData['status'],
                    'progress' => isset($statusData['progress']) ? $statusData['progress'] : 0,
                    'created_at' => $statusData['created_at'],
                    'message' => '请稍后再试,视频仍在' . ($statusData['status'] === 'queued' ? '排队中' : '处理中')
                ]
            ]);
        }

        // 视频生成完成,下载视频
        $downloadUrl = 'https://chatapi.onechats.ai/v1/videos/' . $videoId . '/content';

        // 获取可选的variant参数
        $variant = $this->request->get('variant', '');
        if (!empty($variant)) {
            $downloadUrl .= '?variant=' . urlencode($variant);
        }

        // 创建保存目录
        $saveDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'videos' . DS . date('Ymd');
        if (!is_dir($saveDir)) {
            mkdir($saveDir, 0755, true);
        }

        // 生成唯一文件名
        $filename = $videoId . '.mp4';
        $localPath = DS . 'uploads' . DS . 'videos' . DS . date('Ymd') . DS . $filename;
        $fullPath = $saveDir . DS . $filename;

        // 下载视频
        $videoData = $this->downloadVideo($downloadUrl, $apiKey);

        // 保存视频文件
        if (file_put_contents($fullPath, $videoData) === false) {
            throw new Exception('视频保存失败');
        }

        // 确保路径使用正斜杠,并只保存相对路径部分
        $localPath = str_replace(DIRECTORY_SEPARATOR, '/', $localPath);
        // 移除开头的斜杠,确保路径格式为uploads/videos/...
        $savePath = ltrim($localPath, '/');

        // 返回成功响应
        return json([
            'code' => 0,
            'msg' => '视频下载成功',
            'data' => [
                'video_id' => $videoId,
                'web_url' => $savePath
            ]
        ]);
    }

    //获取服务器URL IP地址:端口
    public function GetHttpUrl(){
        $data = Db::name('http_url')->find();
        $fullUrl = "http://" . $data['baseUrl'] . ":" . $data['port'];
        $res = [
            'code' => 0,
            'msg' => '成功',
            'data' => [
                'full_url' => $fullUrl,
                'id' => $data['id'],
                'baseUrl' => $data['baseUrl'],
                'port' => $data['port']
            ]
        ];
        return json($res);
    }


    //获取视频列表
    public function Getvideolist(){
        if (!$this->request->isGet()) {
            $this->error('请求方式错误');
        }
        $params = $this->request->param();
        $search = input('search', '');
        $page = isset($params['page']) ? (int)$params['page'] : 1;
        $limit = isset($params['limit']) ? (int)$params['limit'] : 50;
        $where = [];
        if (!empty($search)) {
            $where['prompt'] = ['like', '%' . $search . '%'];
        }
        $list = Db::name('video')->where('mod_rq', null)
            ->where($where)
            ->order('id desc')
            ->limit(($page - 1) * $limit, $limit)
            ->select();
        $total = Db::name('video')->where('mod_rq', null)
            ->where($where)
            ->count();
        $res['code'] = 0;
        $res['msg'] = '成功';
        $res['count'] = $total;
        $res['data'] = $list;
        return json($res);
    }

    /**
     * 文生视频/图生视频接口
     * @return \think\response\Json
     * @throws \Exception
     */
    //文生视频
    public function video(){
        $params = $this->request->param();

        $apiUrl = 'https://chatapi.onechats.ai/v1/videos';
        $apiKey = 'sk-sWW1GFlnjbrDRb1DkMEzePIxgdvLK6cZt0Qg93yDMVP2z1yN';
        $postData = [
            'prompt' => $params['prompt'],
            'model' => $params['model'],
            'seconds' => $params['seconds'],
            'size' => $params['size'],
        ];

        // 初始化CURL
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $apiKey
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 300);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_HEADER, true); // 获取响应头
        curl_setopt($ch, CURLOPT_VERBOSE, true); // 启用详细输出以进行调试
        // 创建临时文件来捕获详细的cURL输出
        $verbose = fopen('php://temp', 'w+');
        curl_setopt($ch, CURLOPT_STDERR, $verbose);
        // 执行请求
        $response = curl_exec($ch);
        //HTTP状态码
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        // 获取详细的cURL调试信息
        rewind($verbose);
        //CURL调试信息
        $verboseLog = stream_get_contents($verbose);
        fclose($verbose);
        // 分离头部和主体
        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        //响应头部
        $header = substr($response, 0, $header_size);
        //响应主体
        $body = substr($response, $header_size);
        // 检查CURL错误
        $curlError = curl_error($ch);
        curl_close($ch);

        $responseData = json_decode($body, true);

        // 检查API是否返回了错误信息
        if (isset($responseData['error'])) {
            $errorMessage = isset($responseData['error']['message']) ? $responseData['error']['message'] : 'API请求失败';
            return json([
                'code' => 1,
                'msg' => '视频生成请求失败',
                'data' => [
                    'error_type' => isset($responseData['error']['type']) ? $responseData['error']['type'] : 'unknown',
                    'error_code' => isset($responseData['error']['code']) ? $responseData['error']['code'] : 'unknown',
                    'error_message' => $errorMessage
                ]
            ]);
        }

        // 检查是否有自定义错误格式
        if (isset($responseData['code']) && $responseData['code'] === 'fail_to_fetch_task' && isset($responseData['message'])) {
            return json([
                'code' => 1,
                'msg' => '视频生成请求失败',
                'data' => [
                    'error_code' => $responseData['code'],
                    'error_message' => $responseData['message']
                ]
            ]);
        }

        // 检查是否存在id字段
        if (!isset($responseData['id'])) {
            return json([
                'code' => 1,
                'msg' => '无法获取视频ID',
                'data' => [
                    'response_data' => $responseData,
                    'http_code' => $httpCode
                ]
            ]);
        }

        $videoData = [
            'video_id' => $responseData['id'],
            'prompt' => $postData['prompt'],
            'model' => $postData['model'],
            'seconds' => $postData['seconds'],
            'size' => $postData['size'],
            'sys_rq' => date("Y-m-d H:i:s")
        ];

        // 尝试插入数据
        try {
            $res = Db::name('video')->insert($videoData);
            return json([
                'code' => 0,
                'msg' => '视频正在生成中',
                'data ' => [
                    'video_id' => $responseData['id'],
                    'insert_result' => $res
                ]
            ]);
        } catch (Exception $e) {
            return json([
                'code' => 1,
                'msg' => '数据库操作失败',
                'data' => [
                    'error_message' => $e->getMessage()
                ]
            ]);
        }
    }

    /**
     * 获取视频内容
     * 下载已完成的视频内容
     */
    public function videoContent(){
        // 从请求参数获取video_id,如果没有则使用默认值
        $video_id = input('get.video_id');

        $apiKey = 'sk-sWW1GFlnjbrDRb1DkMEzePIxgdvLK6cZt0Qg93yDMVP2z1yN';
        // 1. 先检查视频状态
        $statusUrl = 'https://chatapi.onechats.ai/v1/videos/' . $video_id;
        $statusData = $this->fetchVideoStatus($statusUrl, $apiKey);

        // 检查视频状态
        if ($statusData['status'] !== 'completed') {
            return json([
                'code' => 202,
                'msg' => '视频尚未生成完成',
                'data' => [
                    'video_id' => $video_id,
                    'status' => $statusData['status'],
                    'progress' => $statusData['progress'],
                    'created_at' => $statusData['created_at'],
                    'message' => '请稍后再试,视频仍在' . ($statusData['status'] === 'queued' ? '排队中' : '处理中')
                ]
            ]);
        }

        // 2. 视频生成完成,准备下载
        $apiUrl = 'https://chatapi.onechats.ai/v1/videos/' . $video_id . '/content';

        // 获取可选的variant参数
        $variant = $this->request->get('variant', '');
        if (!empty($variant)) {
            $apiUrl .= '?variant=' . urlencode($variant);
        }

        // 创建保存目录
        $saveDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'videos' . DS . date('Ymd');
        if (!is_dir($saveDir)) {
            mkdir($saveDir, 0755, true);
        }

        // 生成唯一文件名
        $filename = $video_id . '.mp4';
        $localPath = DS . 'uploads' . DS . 'videos' . DS . date('Ymd') . DS . $filename;
        $fullPath = $saveDir . DS . $filename;

        // 3. 下载视频
        $videoData = $this->downloadVideo($apiUrl, $apiKey);

        // 4. 保存视频文件
        if (file_put_contents($fullPath, $videoData) === false) {
            throw new Exception('视频保存失败');
        }

        // 确保路径使用正斜杠,并只保存相对路径部分
        $localPath = str_replace('\\', '/', $localPath);
        // 移除开头的斜杠,确保路径格式为uploads/videos/...
        $savePath = ltrim($localPath, '/');

        // 将正确格式的文件路径存入数据库
        Db::name('video')->where('video_id', $video_id)->update([
            'web_url' => $savePath
        ]);

        // 返回成功响应
        return json([
            'code' => 0,
            'msg' => '视频下载成功',
            'data' => [
                'video_id' => $video_id,
                'local_path' => $localPath,
                'web_url' => $savePath,
                'file_size' => filesize($fullPath)
            ]
        ]);
    }


    /**
     * 获取视频状态
     */
    private function fetchVideoStatus($url, $apiKey) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPGET, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $apiKey,
            'Accept: application/json'
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);

        if ($error) {
            throw new Exception('获取视频状态失败: ' . $error);
        }

        if ($httpCode < 200 || $httpCode >= 300) {
            throw new Exception('获取视频状态失败,HTTP状态码: ' . $httpCode);
        }

        $data = json_decode($response, true);
        if (!is_array($data)) {
            throw new Exception('视频状态数据格式错误');
        }

        return $data;
    }

    /**
     * 下载视频文件
     */
    private function downloadVideo($url, $apiKey) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPGET, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $apiKey
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 300);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);

        if ($error) {
            throw new Exception('视频下载失败: ' . $error);
        }

        if ($httpCode < 200 || $httpCode >= 300) {
            throw new Exception('视频下载失败,HTTP状态码: ' . $httpCode);
        }

        return $response;
    }



    private function sendPostRequest($url, $data, $apiKey)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $apiKey,
            'Accept: application/json',
            'Content-Type: application/json'
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60); // 延长超时时间
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        return [
            'response' => $response,
            'http_code' => $httpCode,
            'error' => $error
        ];
    }

    /**
     * 文本生成图片并保存第一张结果
     * @param array $params 请求参数
     * @return array 返回结果
     */
    public function txttowimg()
    {
        // API配置
        $config = [
            'api_url' => 'https://chatapi.onechats.ai/mj/submit/imagine',
            'fetch_url' => 'https://chatapi.onechats.ai/mj/task/',
            'api_key' => 'sk-iURfrAgzAjhZ4PpPLwzmWIAhM7zKfrkwDvyxk4RVBQ4ouJNK',
            'default_prompt' => '一个猫',
            'wait_time' => 3 // 等待生成完成的秒数
        ];
        try {
            // 1. 准备请求数据
            $prompt =  $config['default_prompt'];
            $postData = [
                'botType' => 'MID_JOURNEY',
                'prompt' => $prompt,
                'base64Array' => [],
                'accountFilter' => [
                    'channelId' => "",
                    'instanceId' => "",
                    'modes' => [],
                    'remark' => "",
                    'remix' => true,
                    'remixAutoConsidered' => true
                ],
                'notifyHook' => "",
                'state' => ""
            ];

            // 2. 提交生成请求
            $generateResponse = $this->sendApiRequest($config['api_url'], $postData, $config['api_key']);
            $generateData = json_decode($generateResponse, true);
            if (empty($generateData['result'])) {
                throw new Exception('生成失败: '.($generateData['message'] ?? '未知错误'));
            }
            $taskId = $generateData['result'];
            // 3. 等待图片生成完成
            sleep($config['wait_time']);
            // 4. 获取生成结果
            $fetchUrl = $config['fetch_url'].$taskId.'/fetch';
            $fetchResponse = $this->sendApiRequest($fetchUrl, [], $config['api_key'], 'GET');
            $fetchData = json_decode($fetchResponse, true);
            if (empty($fetchData['imageUrl'])) {
                throw new Exception('获取图片失败: '.($fetchData['message'] ?? '未知错误'));
            }
            // 5. 处理返回的图片数组(取第一张)
            $imageUrls = is_array($fetchData['imageUrl']) ? $fetchData['imageUrl'] : [$fetchData['imageUrl']];
            $firstImageUrl = $imageUrls[0];
            // 6. 保存图片到本地
            $savePath = $this->saveImage($firstImageUrl);
            // 7. 返回结果
            return [
                'code' => 200,
                'msg' => '图片生成并保存成功',
                'data' => [
                    'local_path' => $savePath,
                    'web_url' => request()->domain().$savePath,
                    'task_id' => $taskId
                ]
            ];
        } catch (Exception $e) {
            // 错误处理
            return [
                'code' => 500,
                'msg' => '处理失败: '.$e->getMessage(),
                'data' => null
            ];
        }
    }

    /**
     * 发送API请求
     * @param string $url 请求地址
     * @param array $data 请求数据
     * @param string $apiKey API密钥
     * @param string $method 请求方法
     * @return string 响应内容
     * @throws Exception
     */
    private function sendApiRequest($url, $data, $apiKey, $method = 'POST')
    {
        $ch = curl_init();

        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer '.$apiKey,
                'Accept: application/json',
                'Content-Type: application/json'
            ],
            CURLOPT_POSTFIELDS => $method === 'POST' ? json_encode($data) : null,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_FAILONERROR => true
        ]);

        $response = curl_exec($ch);
        $error = curl_error($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($error) {
            throw new Exception('API请求失败: '.$error);
        }

        if ($httpCode < 200 || $httpCode >= 300) {
            throw new Exception('API返回错误状态码: '.$httpCode);
        }

        return $response;
    }

    /**
     * 保存图片到本地
     * @param string $imageUrl 图片URL
     * @return string 本地保存路径
     * @throws Exception
     */
    private function saveImage($imageUrl)
    {
        // 1. 创建存储目录
        $saveDir = ROOT_PATH.'public'.DS.'uploads'.DS.'midjourney'.DS.date('Ymd');
        if (!is_dir($saveDir)) {
            mkdir($saveDir, 0755, true);
        }

        // 2. 生成唯一文件名
        $filename = uniqid().'.png';
        $localPath = DS.'uploads'.DS.'midjourney'.DS.date('Ymd').DS.$filename;
        $fullPath = $saveDir.DS.$filename;

        // 3. 下载图片
        $ch = curl_init($imageUrl);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_CONNECTTIMEOUT => 15
        ]);

        $imageData = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);

        if (!$imageData) {
            throw new Exception('图片下载失败: '.$error);
        }

        // 4. 验证图片类型
        $imageInfo = getimagesizefromstring($imageData);
        if (!in_array($imageInfo['mime'] ?? '', ['image/png', 'image/jpeg'])) {
            throw new Exception('下载内容不是有效图片');
        }

        // 5. 保存文件
        if (!file_put_contents($fullPath, $imageData)) {
            throw new Exception('图片保存失败');
        }

        return $localPath;
    }






    /**
     * 查询队列列表
     * 统计文件对应的队列情况
     */
    public function get_queue_logs()
    {
        $params = $this->request->param('old_image_file', '');
        $queue_logs = Db::name('queue_logs')
            ->where('old_image_file', $params)
            ->order('id desc')
            ->select();

        $result = [];  //初始化变量,避免未定义错误

        foreach ($queue_logs as &$log) {
            $taskId = $log['id'];
            $statusCount = Db::name('image_task_log')
                ->field('status, COUNT(*) as count')
                ->where('task_id', $taskId)
                ->where('mod_rq', null)
                ->group('status')
                ->select();

            $log['已完成数量'] = 0;
            $log['处理中数量'] = 0;
            $log['排队中的数量'] = 0;
            $log['失败数量'] = 0;

            foreach ($statusCount as $item) {
                switch ($item['status']) {
                    case 0:
                        $log['排队中的数量'] = $item['count'];
                        break;
                    case 1:
                        $log['处理中数量'] = $item['count'];
                        break;
                    case 2:
                        $log['已完成数量'] = $item['count'];
                        break;
                    case -1:
                        $log['失败数量'] = $item['count'];
                        break;
                }
            }

            // if ($log['排队中的数量'] >$log['已完成数量']) {
            //     $result[] = $log;
            // }

            if ($log['排队中的数量']) {
                $result[] = $log;
            }

            // if ($log['处理中数量'] >= 0) {
            //     $result[] = $log;
            // }
        }

        return json([
            'code' => 0,
            'msg'  => '查询成功',
            'data' => $result,
            'count' => count($result)
        ]);
    }

    /**
     * 查询总队列状态(统计当前处理的数据量)
     */
    public function queueStats()
    {
        $statusList = Db::name('image_task_log')
            ->field('status, COUNT(*) as total')
            ->where('mod_rq', null)
            ->where('create_time', '>=', date('Y-m-d 00:00:00'))
            ->group('status')
            ->select();


        $statusCount = [];
        foreach ($statusList as $item) {
            $statusCount[$item['status']] = $item['total'];
        }
        // 总数为所有状态和
        $total = array_sum($statusCount);
        //获取队列当前状态
        $statusText = Db::name('queue_logs')->order('id desc')->value('status');
        return json([
            'code' => 0,
            'msg' => '获取成功',
            'data' => [
                '总任务数'     => $total,
                '待处理'   => $statusCount[0]  ?? 0,
                '处理中'   => $statusCount[1]  ?? 0,
                '成功'   => $statusCount[2]  ?? 0,
                '失败'     => $statusCount[-1] ?? 0,
                '当前状态' => $statusText
            ]

        ]);
    }

    /**
     * 显示当前运行中的队列监听进程
     */
    public function viewQueueStatus()
    {
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis->auth('123456');
        $redis->select(15);

        $key = 'queues:imgtotxt';

        // 判断 key 是否存在,避免报错
        if (!$redis->exists($key)) {
            return json([
                'code' => 0,
                'msg'  => '查询成功,队列为空',
                'count' => 0,
                'tasks_preview' => []
            ]);
        }

        $count = $redis->lLen($key);
        $list = $redis->lRange($key, 0, 9);

        // 解码 JSON 内容,确保每一项都有效
        $parsed = array_filter(array_map(function ($item) {
            return json_decode($item, true);
        }, $list), function ($item) {
            return !is_null($item);
        });

        return json([
            'code' => 0,
            'msg'  => '查询成功',
            'count' => $count,
            'tasks_preview' => $parsed
        ]);
    }

    /**
     * 清空队列并删除队列日志记录
     */
    public function stopQueueProcesses()
    {

        Db::name('image_task_log')
            ->where('log', '队列中')
            ->whereOr('status', 1)
            ->where('create_time', '>=', date('Y-m-d 00:00:00'))
            ->update([
                'status' => "-1",
                'log' => '清空取消队列',
                'mod_rq' => date('Y-m-d H:i:s')
            ]);

        Db::name('image_task_log')
            ->whereLike('log', '%处理中%')
            ->where('create_time', '>=', date('Y-m-d 00:00:00'))
            ->update([
                'status' => "-1",
                'log' => '清空取消队列',
                'mod_rq' => date('Y-m-d H:i:s')
            ]);

        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis->auth('123456');
        $redis->select(15);

        $key_txttoimg = 'queues:txttoimg:reserved';
        $key_txttotxt = 'queues:txttotxt:reserved';
        $key_imgtotxt = 'queues:imgtotxt:reserved';
        $key_imgtoimg = 'queues:imgtoimg:reserved';


        // 清空 Redis 队列
        $redis->del($key_txttoimg);
        $redis->del($key_txttotxt);
        $redis->del($key_imgtotxt);
        $redis->del($key_imgtoimg);

        $count = $redis->lLen($key_txttoimg) + $redis->lLen($key_txttotxt) + $redis->lLen($key_imgtotxt) + $redis->lLen($key_imgtoimg);

//        if ($count === 0) {
//            return json([
//                'code' => 1,
//                'msg'  => '暂无队列需要停止'
//            ]);
//        }
        return json([
            'code' => 0,
            'msg'  => '成功停止队列任务'
        ]);
    }

    /**
     * 开启队列任务
     * 暂时用不到、服务器已开启自动开启队列模式
     */
//    public function kaiStats()
//    {
//        // 判断是否已有监听进程在运行
//        $check = shell_exec("ps aux | grep 'queue:listen' | grep -v grep");
//        if ($check) {
//            return json([
//                'code' => 1,
//                'msg'  => '监听进程已存在,请勿重复启动'
//            ]);
//        }
//        // 启动监听
//        $command = 'nohup php think queue:listen --queue --timeout=300 --sleep=3 --memory=256 > /var/log/job_queue.log 2>&1 &';
//        exec($command, $output, $status);
//        if ($status === 0) {
//            return json([
//                'code' => 0,
//                'msg'  => '队列监听已启动'
//            ]);
//        } else {
//            return json([
//                'code' => 1,
//                'msg'  => '队列启动失败',
//                'output' => $output
//            ]);
//        }
//    }
    /**
     * 通过店铺ID-查询对应店铺表数据
     *
     */
    public function PatternApi()
    {
        $params = $this->request->param('pattern_id', '');
        $tableName = 'pattern-' . $params;

        // 连接 MongoDB
        $mongo = Db::connect('mongodb');

        // 查询指定 skc 的数据
        $data = $mongo->table($tableName)
            ->field('
                name,
                skc,
                file
            ')
            ->where("skc", '0853004152036')
            ->select();

        $data = json_decode(json_encode($data), true);  // 数组

        return json([
            'code' => 0,
            'msg' => '获取成功',
            'data' => $data
        ]);
    }


    /**
     * 新增产品模版
     */
    public function Add_Product_Template(){
        try {
            // 获取请求参数
            $params = $this->request->param();

            $chinese_description  = $params['chinese_description'] ?? '';
            $template_image_url = $params['template_image_url'] ?? '';
            $template_name = $params['template_name'] ?? '';
            $size = $params['size'] ?? '';
            $style = $params['style'] ?? '';
            $type = $params['type'] ?? '';
            $sys_id = $params['sys_id'] ?? '';
            $seconds = $params['seconds'] ?? '';
            $video_id = $params['video_id'] ?? '';

            if (empty($template_name)) {
                return json(['code' => 1, 'msg' => '模板名称不能为空']);
            }

            $data = [
                'chinese_description' => $chinese_description,
                'template_image_url' => $template_image_url,
                'template_name' => $template_name,
                'type' => $type,
                'style' => $style,
                'seconds' => $seconds,
                'size' => $size,
                'video_id' => $video_id,
                'sys_id' => $sys_id,
                'sys_rq' => date('Y-m-d H:i:s'),
                'create_time' => date('Y-m-d H:i:s')
            ];

//            echo "
";
//            print_r($data);
//            echo "
";die;
            // 记录插入的数据用于调试
//            Log::record('准备插入模板数据: ' . json_encode($data), 'info');

            $result = Db::name('product_template')->insert($data);

            if ($result) {
//                Log::record('模板保存成功,插入数据: ' . json_encode($data), 'info');
                return json(['code' => 0, 'msg' => '模板保存成功']);
            } else {
//                Log::record('模板保存失败,插入数据: ' . json_encode($data) . ',受影响行数: ' . $result, 'error');
                return json(['code' => 1, 'msg' => '模板保存失败: 数据库操作未影响任何行']);
            }
        } catch (\Exception $e) {
            // 捕获并记录异常信息
            Log::record('模板保存异常: ' . $e->getMessage(), 'error');
            Log::record('异常堆栈: ' . $e->getTraceAsString(), 'error');
            return json(['code' => 1, 'msg' => '模板保存失败: ' . $e->getMessage()]);
        }
    }


    /**
     * 新查询产品模版
     */
    public function product_template()
    {
        // 查询模版表
        $products = Db::name('product_template')->select();

        $http_url = Db::name('http_url')->field('baseUrl,port')->find();
        if ($products && $http_url) {
            $base_url = !empty($http_url['baseUrl']) && !empty($http_url['port'])
                ? 'http://' . $http_url['baseUrl'] . ':' . $http_url['port'] : '';

            if ($base_url) {
                foreach ($products as &$val) {
                    $val['template_image_url'] = $base_url . $val['template_image_url'];
                }
            }
        }

        return json([
            'code' => 0,
            'msg' => '请求成功',
            'data' => $products
        ]);
    }



}