package com.example.meetings.tool;


import com.example.meetings.pojo.response;
import com.example.meetings.pojo.temp;
import com.google.gson.Gson;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/Stream1/{id}")
@Component
public class Chat {
private static final Map<String,Session> onlineUsers = new ConcurrentHashMap<>();

private Session httpSession;
/**
*
* @param session
*/
@OnOpen
public void onOpen(Session session ,EndpointConfig config) throws IOException {
// this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
String user = "1";
System.out.println(session);
httpSession=session;

Gson gson=new Gson();
// System.out.println(string);
// session.getBasicRemote().sendText(string);

// broadcastAllUsers("");
}
@OnMessage
public void onMessage(Session session, String message, @PathParam("id") String id) throws IOException {
if (!id.isEmpty()){
if (id.equals("2")){
new Thread(() -> {
try {
System.out.println(message);
OkHttpClient client = new OkHttpClient();
Gson gson = new Gson();
String requestBody = gson.toJson(Map.of(
"model", "deepseek-r1:7b",
"prompt", message+"\n请总结上方文字",
"stream", true
));

Request request = new Request.Builder()
.url("http://localhost:11434/api/generate")
.post(RequestBody.create(requestBody, MediaType.parse("application/json")))
.build();

Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
session.getBasicRemote().sendText("Error: " + response.code());
return;
}

// 逐行读取流式响应并发送给客户端
try (ResponseBody body = response.body()) {
if (body != null) {
String line;
while ((line = body.source().readUtf8Line()) != null) {
session.getBasicRemote().sendText(line);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
session.getBasicRemote().sendText("{a:"+message+"}");
System.out.println(message);
}
if (id.equals("1")){
new Thread(() -> {
try {
System.out.println(message);
OkHttpClient client = new OkHttpClient();
Gson gson = new Gson();
String requestBody = gson.toJson(Map.of(
"model", "deepseek-r1:7b",
"prompt", message,
"stream", true,
"language","zh"
));

Request request = new Request.Builder()
.url("http://localhost:11434/api/generate")
.post(RequestBody.create(requestBody, MediaType.parse("application/json")))
.build();

Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
session.getBasicRemote().sendText("Error: " + response.code());
return;
}

// 逐行读取流式响应并发送给客户端
try (ResponseBody body = response.body()) {
if (body != null) {
String line;
while ((line = body.source().readUtf8Line()) != null) {
temp temp=new temp();
temp=gson.fromJson(line,com.example.meetings.pojo.temp.class);
response res=new response();
res.content=temp.response;
res.self=false;
res.done= temp.done;
String str=gson.toJson(res);
session.getBasicRemote().sendText(str);
// session.getBasicRemote().sendText(line);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
// session.getBasicRemote().sendText("{a:"+message+"}");
System.out.println(message);
}
}
System.out.println(message);
}
@OnClose
public void onClose(Session session){

}
// @OnError
// public void onError(Session session){
//
// }
public void broadcastAllUsers(String message) {
try {
//遍历map集合
Set<Map.Entry<String, Session>> entries = onlineUsers.entrySet();
for (Map.Entry<String, Session> entry : entries) {
//获取到所有用户对应的session对象
Session session = entry.getValue();
//发送消息
session.getBasicRemote().sendText(message);
}
} catch (Exception e) {
//记录日志
}
}
}