package com.huiju.estateagents.websocket;

import com.alibaba.fastjson.JSONObject;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.entity.TaChat;
import com.huiju.estateagents.service.ISysButtonInMenuService;
import com.huiju.estateagents.service.ITaChatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/wx/chat/{sid}")
@Component
public class ChatServer {
    private static Logger log = LoggerFactory.getLogger(ChatServer.class);

    private static ApplicationContext applicationContext;

    private static ITaChatService taChatService = null;

    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static int onlineCount = 0;
    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    private static CopyOnWriteArraySet<ChatServer> webSocketSet = new CopyOnWriteArraySet<>();

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;

    /**
     * 接收sid
     */
    private String sid="";
    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("sid") String sid) {
        removeSameFromSets(sid);
        this.session = session;
        webSocketSet.add(this);
//        addOnlineCount();
        this.sid=sid;
        log.info("有新窗口开始监听: "+sid+" ,当前在线人数为 " + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        removeFromSets();
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        // 心跳
        if ("ping".equals(message)) {
            try {
                this.sendMessage("pong");
            } catch (IOException e) {
                System.out.println("断链"+ e.getMessage());
            }
            return;
        }

        JSONObject jsnMsg = JSONObject.parseObject(message);

        if (null == ChatServer.taChatService) {
            ChatServer.taChatService = applicationContext.getBean(ITaChatService.class);
        }
        System.out.println("收到的聊天消息的信息=========" + jsnMsg.toJSONString());
        ResponseBean resp = ChatServer.taChatService.chat(jsnMsg);
        TaChat taChat = (TaChat) resp.getData();

        try {
            ChatServer.send(JSONObject.toJSONString(taChat), taChat.getReceivePerson());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
        removeFromSets();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    private void removeFromSets() {
        for(ChatServer c: webSocketSet) {
            if (sid.equals(c.sid)) {
                webSocketSet.remove(c);
//                subOnlineCount();
                log.info("有一连接关闭:"+sid+"！当前在线人数为" + getOnlineCount());
            }
        }
    }

    private void removeSameFromSets(String currentSid) {
        for(ChatServer c: webSocketSet) {
            if (currentSid.equals(c.sid)) {
                webSocketSet.remove(c);
//                subOnlineCount();
                log.info("有一连接关闭:"+sid+"！当前在线人数为" + getOnlineCount());
            }
        }
    }

    /**
     * 发自定义消息
     * */
    public static void send(String message, @PathParam("sid") String sid) throws IOException {
        for (ChatServer item : webSocketSet) {
            try {
                //这里可以设定只推送给这个sid的，为null则全部推送
                if(sid==null) {
                    item.sendMessage(message);
                }else if(item.sid.equals(sid)){
                    log.info("推送消息到窗口 "+sid+"，推送内容: "+message);
                    item.sendMessage(message);
                }
            } catch (IOException e) {
                log.error("推送消息错误: " + e.getMessage());
                continue;
            }
        }
    }

    public static synchronized boolean isOnline(String sid) {
        for (ChatServer item : webSocketSet) {
            if(item.sid.equals(sid)){
                return true;
            }
        }

        return false;
    }

    public static synchronized int getOnlineCount() {
        return webSocketSet.size();
    }

//    public static synchronized void addOnlineCount() {
//        ChatServer.onlineCount++;
//    }

//    public static synchronized void subOnlineCount() {
//        ChatServer.onlineCount--;
//    }

    public static void setApplicationContext(ApplicationContext applicationContext) {
        ChatServer.applicationContext = applicationContext;
    }
}
