package com.fs.app.websocket.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fs.app.params.SendSopParam;
import com.fs.app.params.SopLogsEditParam;
import com.fs.app.websocket.bean.MsgBean;
import com.fs.common.core.domain.R;
import com.fs.common.utils.spring.SpringUtils;
import com.fs.qw.domain.QwUser;
import com.fs.qw.service.IQwUserService;
import com.fs.sop.domain.QwSopLogs;
import com.fs.sop.service.IQwSopLogsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/app/webSocket/{key}")
@Component
public class WebSocketServer {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketServer.class);
    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    IQwSopLogsService qwSopLogsService=SpringUtils.getBean(IQwSopLogsService.class);
    IQwUserService qwUserService=SpringUtils.getBean(IQwUserService.class);



    //发送消息
    public void sendMessage(Session session, String message) throws IOException {
        if(session != null){
            synchronized (session) {
                session.getBasicRemote().sendText(message);

            }
        }
    }
    public void sendBaseMessage(Session session, String message) throws IOException {
        if(session != null){
            synchronized (session) {
                session.getBasicRemote().sendText(message);

            }
        }
    }
    public void sendBaseInfo(String id, String message){
        Session session = sessionPools.get(id);
        try {
            if(session != null){
                sendBaseMessage(session, message);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public int sendBaseSleepInfo(String id, String message){
        try {
            Random random = new Random();
            int randomNumber = random.nextInt(1000);
            Thread.sleep(1+randomNumber); // 5000 毫秒 = 5 秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Session session = sessionPools.get(id);
        try {
            if(session != null){
                sendBaseMessage(session, message);
                return 0;
            }
            if (!id.contains("msg")){
                logger.info("发送消息失败websocket不在线:"+id);
            }

            return 1;
        }catch (Exception e){
            e.printStackTrace();
            return 1;
        }
    }
    //给指定用户发送信息
    public R sendInfo(String id, String message){

        Session session = sessionPools.get(id);

        try {
            if(session != null){
                sendMessage(session, message);
                return R.ok();
            }
            return R.error();
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }
    }

    public R sendInfoAll(String value){

        logger.error("调用全部 操作接口——："+value);

        for (Map.Entry<String, Session> entry : sessionPools.entrySet()) {

            String key = entry.getKey();
            Session session = sessionPools.get(key);

            SendSopParam sopParam=new SendSopParam();
            sopParam.setCmd(value);
            sopParam.setKey(key);

            String message = JSON.toJSONString(sopParam);

            try {
                if(session != null){
                    sendMessage(session, message);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        return R.ok();

    }


    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "key") String key){
        key = key.replaceAll("[^a-zA-Z0-9]", "");
        sessionPools.put(key, session);

        //登录
        QwUser qwUser=new QwUser();
        qwUser.setAppKey(key);
        qwUser.setToolStatus(1L);

        if (!key.contains("msg")){
            logger.info("log链接websocket成功:{}", key);
        }

        qwUserService.updateQwUserByAppKeyTool(qwUser);

    }

    //关闭连接时调用
    @OnClose
    public void onClose(@PathParam(value = "key") String key){
        key = key.replaceAll("[^a-zA-Z0-9]", "");
        sessionPools.remove(key);
        QwUser qwUser=new QwUser();
        qwUser.setAppKey(key);
        qwUser.setToolStatus(0L);
        if (!key.contains("msg")){
            logger.info("{}log断开webSocket连接！当前人数为{}", key, sessionPools.size());
        }
        qwUserService.updateQwUserByAppKeyTool(qwUser);
    }

    //收到客户端信息
    @OnMessage
    public void onMessage(String message) throws IOException{
        MsgBean msg=(MsgBean) JSONObject.parseObject(message, MsgBean.class);
        Session session;
//        System.out.println( "收到数据：" + msg.getCmd());
        try {
            switch (msg.getCmd()){
                case "heartbeat":
                    msg.setKey(msg.getKey().replaceAll("[^a-zA-Z0-9]", ""));
                    session=sessionPools.get(msg.getKey());
                    sendMessage(session, JSONObject.toJSONString(msg));
                    break;
                case "sendMsg":
                    if (msg.getData()!=null&&msg.getData()!=""){

//                        System.out.println("收到heartbeat数据" + msg);

                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        SopLogsEditParam sopLogsEditParam = JSONObject.parseObject(msg.getData(), SopLogsEditParam.class);

                        QwSopLogs sopLogs=new QwSopLogs();
                        sopLogs.setId(sopLogsEditParam.getId());
                        sopLogs.setReceivingStatus(sopLogsEditParam.getReceivingStatus());
                        sopLogs.setRemark(sopLogsEditParam.getRemark());
                        sopLogs.setRealSendTime(sdf.format(new Date()));
                        qwSopLogsService.updateQwSopLogs(sopLogs);
                    }
                    break;
                case "login" :
                    break;
                case "logout" :
                    break;
            }





        }
        catch (Exception e){
            System.out.println( "收到数据" + e.getMessage());
        }

    }
    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable){
        logger.error("发生错误："+session);
        throwable.printStackTrace();
    }


    public Set<String> getSessionPools() {
        Set<String> keys = sessionPools.keySet();
        return keys;
    }
}
