package com.zehong.framework.web.service;

import com.alibaba.fastjson.JSONArray;
import com.zehong.common.utils.spring.SpringUtils;
import com.zehong.framework.web.domain.server.WebSocketBean;
import com.zehong.system.domain.SysNotice;
import com.zehong.system.service.ISysNoticeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author geng
 * webSocket工具类
 */
@Component
@ServerEndpoint("/webSocket/{userId}")
public class WebSocketServer {

    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    /**
     * 错误最大重试次数
     */
    private static final int MAX_ERROR_NUM = 10;

    /**
     * 用来存放每个客户端对应的webSocket对象。
     */
    private static Map<String,WebSocketBean> webSocketInfo;

    static
    {
        // concurrent包的线程安全map
        webSocketInfo = new ConcurrentHashMap<>();
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        WebSocketBean bean = new WebSocketBean();
        bean.setSession(session);
        webSocketInfo.put(userId,bean);
        sendMessage(userId,initNotice(userId));
        log.info("客户端连接服务器session id :"+session.getId()+"，当前连接数：" + webSocketInfo.size());
    }

    private String initNotice(String userId){
        SysNotice notice = new SysNotice();
        notice.setUserId(Long.valueOf(userId));
        notice.setStatus("0");
        ISysNoticeService sysNoticeService = SpringUtils.getBean(ISysNoticeService.class);
        List<SysNotice> notices = sysNoticeService.selectNoticeList(notice);
        if(CollectionUtils.isEmpty(notices)){
            return "";
        }
        return JSONArray.toJSONString(notices);
    }

    @OnClose
    public void onClose(Session session) {
        // 客户端断开连接移除websocket对象
        for (Map.Entry<String, WebSocketBean> entry : webSocketInfo.entrySet()) {
            if(session.getId().equals(entry.getValue().getSession().getId())){
                webSocketInfo.remove(entry.getKey());
            }
        }
        log.info("客户端断开连接，当前连接数：" + webSocketInfo.size());
    }


    @OnMessage
    public void onMessage(Session session, String message) {

        log.info("客户端 session id: "+session.getId()+"，消息:" + message);

        // 此方法为客户端给服务器发送消息后进行的处理，可以根据业务自己处理，这里返回页面
        //sendMessage(session, "服务端返回" + message);

    }

    @OnError
    public void onError(Session session, Throwable throwable) {

        log.error("发生错误"+ throwable.getMessage(),throwable);
    }

    /**
     * 根据userId 推送用户信息
     * @param userId
     */
    public void sendMessage(String userId){
        sendMessage(userId,initNotice(userId));
    }


    /**
     * 发送消息
     * @param userId 用户id
     * @param message 消息体
     */
    public void sendMessage(String userId, String message) {
        WebSocketBean bean = webSocketInfo.get(userId);
        if(bean == null) return;
        try{
            // 发送消息
            bean.getSession().getBasicRemote().sendText(message);

            // 清空错误计数
            bean.cleanErrorNum();
        }catch (Exception e){
            log.error("发送消息失败"+ e.getMessage(),e);
            int errorNum = bean.getErroerLinkCount();
            // 小于最大重试次数重发
            if(errorNum <= MAX_ERROR_NUM){
                sendMessage(userId, message);
            }else{
                log.error("发送消息失败超过最大次数");
                // 清空错误计数
                bean.cleanErrorNum();
            }
        }
    }
}
