package com.zhgd.xmgl.config;

import cn.hutool.core.text.CharSequenceUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Author: feicongcong
 * @Date: 2022/7/19
 * @Version: V1.0
 */
@ClientEndpoint
@Slf4j
@Component
public class RundeWSClient {

    private Session session;
    private String id;
    private final Map<String, String> rundeUserMap = new HashMap<>();


    @OnOpen
    public void open(Session session) {
        log.info("客户端:" + id + ",连接服务端...");
        this.session = session;
    }

    @OnMessage
    public void onMessage(String message) {
        if (CharSequenceUtil.isNotBlank(message)) {
            log.info("报文:" + message);
            JSONObject rundeResult = JSON.parseObject(message);
            JSONObject adminInfo = rundeResult.getJSONObject("admin_info");
            if (adminInfo != null) {
                rundeUserMap.put(adminInfo.getString("user_name"), adminInfo.getString("admin_id"));
            }
        }
    }

    @OnClose
    public void onClose() {
        log.info("客户端:" + id + ",服务端服务端断开连接");
    }

    /**
     * @param session
     * @param e
     */
    @OnError
    public void onError(Session session, Throwable e) {
        log.error("连接服务端错误:" + this.id, e);
    }

    /**
     * 发送客户端消息到服务端
     *
     * @param message 消息内容
     */
    public void send(String message) {

        this.session.getAsyncRemote().sendText(message);

    }

    public RundeWSClient(String id) {
        this.id = id;
    }

    public RundeWSClient() {
    }

    public Map<String, String> getRundeUserMap() {
        return rundeUserMap;
    }
}
