<?php

namespace App\Helper;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;


/**
 * Class Gpt
 * @package App\Helper
 * @author zbj
 * @date 2023/11/3
 */
class Gpt
{
    /**
     * 头
     * @var string[]
     */
    public $header = [
        'apikey'    =>  'UkzZljFv83Z2qBi5YR1o3f2otAVWtug6',
        'X-CmerApi-Host'    =>  'bizopenai.p.cmer.com',
    ];

    /**
     * 请求域名
     * @var string
     */
    public $api = 'https://api.cmer.com';

    private static $instance;

    public static function instance(){
        if(!self::$instance){
            self::$instance = new static;
        }
        return self::$instance;
    }

    /**
     * 全球搜-文本生成接口。模型:gpt-3.5-turbo
     * @author zbj
     * @date 2023/8/25
     *
     */
    public function openai_chat_qqs($content, $system_content = '')
    {
        $url = $this->api . '/v1/openai_chat';

        $data = [
            'messages' => [],
            'model' => 'gpt-4o-mini'
        ];
        if ($system_content) {
            $data['messages'][] = [
                "role" => "system",
                "content" => $system_content
            ];
        }
        $data['messages'][] = [
            "role" => "user",
            "content" => $content
        ];

        $time = time();
        try {
            $result = Http::withHeaders($this->header)->withOptions(['verify' => false])->acceptJson()
                ->withBody(json_encode($data, JSON_UNESCAPED_UNICODE), 'application/json')
                ->post($url);
            $json = $result->json();
            if (!isset($json['text']) || $json['code'] !==200) {
                Log::error('openai_chat_qqs data:', $data);
                Log::error('openai_chat_qqs result:' . (time() - $time), $json === null ? ['null'] : $json);
                $json = [];
            }
        } catch (\Throwable $e) {
            Log::error('openai_chat_qqs time ' . (time() - $time) . ' error:' . $e->getMessage());
            $json = [];
        }
        return $json['text'] ?? '';
    }

}