package com.aiup.service.service.impl;

import com.aiup.service.domain.exception.CommonException;
import com.aiup.service.domain.openai.ChatRequest;
import com.aiup.service.domain.openai.ChatResponse;
import com.aiup.service.domain.query.GptChatQuery;
import com.aiup.service.service.OpenAiService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
@Slf4j
public class OpenAiServiceImpl implements OpenAiService {

    @Value("${openai.model}")
    private String model;

    @Value("${openai.api.javaUrl}")
    private String apiUrl;

    @Autowired
    private RestTemplate restTemplate;
     /**
     * ChatGPT聊天
     * @param query
     * @return
     */
     @Override
    public String chat(GptChatQuery query){
         log.warn("aaaaaaa");
        // create a request
         query.setPwd("yunzhongyu123abcd");
        ChatRequest request = new ChatRequest(model, query.getPrompt());
        // call the API
         String str = restTemplate.postForObject(apiUrl, query, String.class);
         JSONObject jsonObject = JSON.parseObject(str);
         if(jsonObject.containsKey("result") && jsonObject.getInteger("result") ==1) {
             String content  = jsonObject.getJSONObject("retValue").getString("content");
             return content;
         }
         else {
             throw  new CommonException("服务忙1，请重试");
         }
    }
}
