package cn.com.capcloud.core.websocket;

import cn.com.capcloud.api.action.service.ApiService;
import cn.com.capcloud.ccui.core.common.json.JackJSONObject;
import cn.com.capcloud.core.system.user.User;
import cn.com.capcloud.core.system.user.UserService;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/ws/websocket/{userId}")
public class WebSocket {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(WebSocket.class);

    private Session session;

    private static CopyOnWriteArraySet<WebSocket> webSockets=new CopyOnWriteArraySet<>();

    private String userId;

    @Resource
    private UserService userService;
    @Resource
    private ApiService apiService;
    private static WebSocket action;
    @PostConstruct
    public void init(){
        action=this;
        action.userService=this.userService;
        action.apiService=this.apiService;
    }
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId){
        this.session = session;
        webSockets.add(this);
        this.userId = userId;
    }
    @OnClose
    public void onClose(){
        webSockets.remove(this);
        //连接断开
    }
    @OnMessage
    public void onMessage(String message){
        //客户端发来的消息
        runMessage(message,this.userId);
    }

    @OnError
    public void OnError(Session session,Throwable error){
        //发生错误
    }

    /**
     * 群发自定义消息
     */
    public static void sendMessage(String message){
        for (WebSocket webSocket:webSockets) {
            //广播消息
            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                //发送异常
            }
        }
    }
    /**
     * 指定发送
     */
    public static void sendMessageById(String message,String userId){
        for (WebSocket webSocket:webSockets) {
            //广播消息
            try {
                if(webSocket.userId.equals(userId)){
                    webSocket.session.getBasicRemote().sendText(message);
                }
            } catch (IOException e) {
                //发送异常
            }
        }
    }

    /**
     * 接收前端消息
     */
    public void runMessage(String message,String userId){
        JackJSONObject jsonObject= JackJSONObject.fromObject(message);
        Map<String, Object> dsMap = action.apiService.findDataSourceByCode(String.valueOf(jsonObject.get("dsCode")));
        String actionClass=String.valueOf(dsMap.get("my_action_class"));
        String methodName=String.valueOf(jsonObject.get("methodName"));
        mySelfMethodNoRet(actionClass,methodName,message,userId);
    }


    public static void mySelfMethodNoRet(String actionName, String methodName, String message, String userId) {
        try {
            Class actionClass = Class.forName(actionName);
            Object myActionClassInstance=actionClass.newInstance();
            Method method = null;
            try {
                method = actionClass.getMethod(methodName,String.class, String.class);
            } catch (NoSuchMethodException e) {
                logger.info("异常，扩展类找不多对应的方法，请检查 "+methodName+" 方法是否正确，或是否更新");
            } catch (SecurityException e) {
            }
            method.invoke(myActionClassInstance,message,userId);
        } catch (Exception e) {
        }
    }
}
