package com.goafanti.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.goafanti.ChatAI.BaiduChatErrorEnums;
import com.goafanti.ChatAI.bo.InputsendGLM;
import com.goafanti.ChatAI.bo.OutChatER;
import com.goafanti.ChatAI.bo.SseMap;
import com.goafanti.ChatAI.bo.SseResult;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class SseEmitterUtils {


    public void sseEmitterSend(String id, InputsendGLM in) throws IOException {
        SseResult res =  SseMap.sseEmitterMap.get(id);
        BufferedReader reader=null;
        InputStreamReader inputStreamReader=null;
        OutputStream outputStream=null;
        try {
            String local_url="http://172.16.1.160:8800/stream";
            URL url = new URL(local_url);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            // 构造请求体
//            String requestBody = "{\"messages\":[{\"role\":\"user\",\"content\":\"给我介绍一条从四川自驾到拉萨的路线\"}],\"stream\":true}";
            String requestBody=JSON.toJSONString(in);
            System.out.println(requestBody);
            byte[] postData = requestBody.getBytes(StandardCharsets.UTF_8);
            connection.setRequestProperty("Content-Length", String.valueOf(postData.length));
            outputStream =connection.getOutputStream();
            outputStream.write(postData);
            InputStream responseStream = connection.getInputStream();
            inputStreamReader = new InputStreamReader(responseStream, "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            String line;

            while ((line = reader.readLine())!= null) {
                // 每行数据中以 "data:" 开头的部分即为实际的响应数据
                if (StringUtils.isNotBlank(line)){
                    if (line.startsWith("data:")) {
                        String data = line.substring("data:".length()).trim();
                        System.out.println(data);
                        JSONObject jsonObject = JSONObject.parseObject(data);
                        Boolean isEnd = jsonObject.getBoolean("finished");
                        res.sseEmitter.send(line);
                        if(isEnd){
                            break;
                        }
                        //错误返回格式{"error_code":110,"error_msg":"Access token invalid or no longer valid"}
                    }else if(line.startsWith("{")) {
                        JSONObject jsonObject = JSONObject.parseObject(line);
                        Integer errorCode = jsonObject.getInteger("error_code");
                        OutChatER out=new OutChatER();
                        if (errorCode!=null){
                            out.setError_code(errorCode);
                            if (errorCode.equals("336003")){
                                out.setError_msg(BaiduChatErrorEnums.BycodeGetMsg(errorCode)+jsonObject.getString("error_msg"));
                            }else {
                                out.setError_msg(BaiduChatErrorEnums.BycodeGetMsg(errorCode));
                            }
                        }
                        String errorStr= JSON.toJSONString(out);
                        res.sseEmitter.send(errorStr);
                    }
                }
            }
            res.sseEmitter.complete();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        }catch (IllegalStateException e){
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            inputStreamReader.close();
            outputStream.close();
            reader.close();
            res.sseEmitter.complete();
            SseMap.sseEmitterMap.remove(id);
        }
    }


}
