<?php
declare(strict_types=1);

namespace App\Controller;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

class SseController extends AbstractController
{
    public function stream(RequestInterface $request, ResponseInterface $response)
    {
          $params = [
              "model"=>"glm-4",
              "messages"=>[
                  [
                      "role"=>"system",
                      "content"=>"你是一个乐于解答各种问题的助手,你的任务是为用户提供专业、准确、有见地的建议。"//$requireData['message']
                  ],
                  [
                      "role"=>"user",
                      "content"=>"我是一个初级程序员,如何快速的提升自己"//$requireData['message']
                  ]
              ],
              "stream"=>true
          ];
         $apiUrl = "https://open.bigmodel.cn/api/paas/v4/chat/completions";
         $result= $this->callApi($apiUrl, 'POST', $params, ['Authorization: Bearer be1856920c54ac537b530d69bc2eda73.gOO2BMq9NXavzEMq']);
          $arr =  preg_split('/\n\s*\n/', $result);
        // 开始流式传输
        $this->container->get(\Swoole\Http\Response::class)->status(200);
        foreach ($arr as $val){
            $response->write("$val\n\n");
            usleep(1000000); // 暂停1秒
        }
        return $response;
    }


    function callApi($url, $method = 'GET', $data = null, $headers = [])
    {
        $ch = curl_init();

        // 配置 CURL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        // 如果是 POST/PUT 请求,附加数据
        if ($data && ($method === 'POST' || $method === 'PUT')) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            $headers[] = 'Content-Type: application/json';
        }
        // 附加头部信息
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        // 执行请求
        $response = curl_exec($ch);
        // 错误处理
        if (curl_errno($ch)) {
            $response = json_encode(['error' => curl_error($ch)]);
        }
        curl_close($ch);
        return $response;
    }

}