package org.jeecg.modules.largeScreen.component;

import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.largeScreen.config.CronTaskRegistrar;
import org.jeecg.modules.largeScreen.dto.SocketSendData;
import org.jeecg.modules.largeScreen.task.SchedulingRunnable;
import org.jeecg.modules.largeScreen.task.SecondScreenTask;
import org.jeecg.modules.largeScreen.util.EncoderClassListVo;
import org.jeecg.modules.largeScreen.util.EncoderClassVo;
import org.jeecg.modules.largeScreen.util.SpringUtils;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 二级大屏
 * @ServerEndpoint 注解是一个类层次的注解，它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@Component
@ServerEndpoint(value = "/itdmWebsocket/itdmSecondServer", encoders = {EncoderClassVo.class, EncoderClassListVo.class})
public class WebSocketSecondScreenServer {

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。若要实现服务端与单一客户端通信的话，可以使用Map来存放，其中Key可以为用户标识
    private static CopyOnWriteArraySet<WebSocketSecondScreenServer> webSocketSet = new CopyOnWriteArraySet<WebSocketSecondScreenServer>();


    private static ConcurrentHashMap<String, SchedulingRunnable> webSocketSet1 = new ConcurrentHashMap<String, SchedulingRunnable>();
    //    private static String cabid = "";
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;


    public SecondScreenTask getDemoTask() {
        return SpringUtils.getBean(SecondScreenTask.class);
    }

    public CronTaskRegistrar getCronTaskRegistrar() {
        return SpringUtils.getBean(CronTaskRegistrar.class);
    }


    /**
     * 连接建立成功调用的方法
     *
     * @param session 可选的参数。session为与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
        addOnlineCount();           //在线数加1
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        webSocketSet.remove(this);

        subOnlineCount();
        if (webSocketSet1.get(session.getId()) != null) {
            this.getCronTaskRegistrar().removeCronTask(webSocketSet1.get(session.getId()));
        }

    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException, EncodeException {

        System.out.println("来自客户端的消息:" + message);

        Gson gson = new Gson();

        SocketSendData stringMap = gson.fromJson(message, SocketSendData.class);
        List<String> deviceIds = stringMap.getDeviceIds();
        String id = deviceIds.get(0);
        Integer day = stringMap.getDay();

        if (StringUtils.isNotEmpty(message)) {
            sendUser(this.getDemoTask().getList(id), session);
            if (webSocketSet1.get(session.getId()) != null) {
                this.getCronTaskRegistrar().removeCronTask(webSocketSet1.get(session.getId()));
            }

            SchedulingRunnable task = new SchedulingRunnable("sTask", "taskWithParamsListSecond",id,session);

            this.getCronTaskRegistrar().addCronTask(task, "0/30 * * * * ?");
            webSocketSet1.put(session.getId(), task);
        }

    }

    /**
     * 发生错误时调用
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError (Session session, Throwable error){
        System.out.println("发生错误");
        error.printStackTrace();
    }

    /**
     * 这个方法与上面几个方法不一样。没有用注解，是根据自己需要添加的方法。
     *
     * @param message
     * @throws IOException
     */
    public void sendMessage (Object message) throws EncodeException, IOException {
        this.session.getBasicRemote().sendObject(message);
        //this.session.getAsyncRemote().sendText(message);
    }


    /**
     * 暴露给外部的群发
     *
     * @param message
     * @throws IOException
     */

    public void sendInfo (Object message) throws IOException {

        sendAll(message);

    }

    /**
     * 群发
     *
     * @param message
     */


    public void sendUser (Object message, Session session){

        try {
            session.getBasicRemote().sendObject(message);
        } catch (EncodeException e) {
            this.getCronTaskRegistrar().removeCronTask(webSocketSet1.get(session.getId()));
            e.printStackTrace();
        } catch (IOException e) {
            this.getCronTaskRegistrar().removeCronTask(webSocketSet1.get(session.getId()));
            e.printStackTrace();
        }

    }


    private static void sendAll (Object message){

        Arrays.asList(webSocketSet.toArray()).forEach(item -> {

            WebSocketSecondScreenServer WebsocketServer = (WebSocketSecondScreenServer) item;

            //群发

            try {

                WebsocketServer.sendMessage(message);

            } catch (IOException e) {

                e.printStackTrace();

            } catch (EncodeException e) {

                e.printStackTrace();

            }

        });

    }


    public static synchronized int getOnlineCount () {
        return onlineCount;
    }

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

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

