package cn.van333.mt2ql.wxMessage.binance;

import cn.van333.mt2ql.wxMessage.utils.SpringContextUtil;
import cn.van333.mt2ql.wxMessage.utils.WXUtil;
import com.alibaba.fastjson2.JSONObject;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Leo
 * @version 1.0
 * @create 2024/03/11 0011 下午 03:52
 * @description：
 */
public class WSClient extends WebSocketClient {
    private List<JSONObject> dataList = new ArrayList<>();

    public WSClient(String url) throws URISyntaxException {
        super(new URI(url));
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        System.out.println("连接建立");
    }

    @Override
    public void onMessage(String message) {
        /** 数据结构 {"e":"avgPrice","E":1710146170238,"s":"APTUSDT","i":"5m","w":"13.26427038","T":1710146170230}
         拿出所有的数据 */
        JSONObject data = JSONObject.parseObject(message);
        dataList.add(data);
        if (dataList.size() == 5) {
            StringBuilder text = new StringBuilder();
            for (JSONObject jsonObject : dataList) {
                String type = jsonObject.getString("s");
                String price = jsonObject.getString("w");
                Long start = jsonObject.getLong("T");
                Long end = jsonObject.getLong("E");
                text.append(type).append(" ").append(price).append(" ").append(start).append(" ").append(end).append("\n");
            }
            WXUtil wxUtil = SpringContextUtil.getBean(WXUtil.class);
            wxUtil.sendTextMessage("wxid_kr145nk7l0an31", text.toString(), 2, "wxid_kr145nk7l0an31"); // 假设send方法接受List作为参数，如果不是，你需要修改这行代码
            dataList.clear();
        }


    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        System.out.println("连接关闭");
    }

    @Override
    public void onError(Exception ex) {
        System.out.println("发生错误: " + ex.getMessage());
    }
}
