package cn.com.ty.lift.push.websocket.handler;

import cn.com.ty.lift.common.constants.ApiConstants;
import cn.com.ty.lift.push.websocket.dao.entity.TimeyMessage;
import cn.com.ty.lift.push.websocket.dao.entity.model.RealTimeMessage;
import cn.com.ty.lift.push.websocket.dao.entity.model.TimeyMessageVo;
import cn.com.ty.lift.push.websocket.service.TimeyMessageService;
import cn.com.ty.lift.push.websocket.service.UserService;
import cn.hutool.json.JSONUtil;
import org.springframework.web.socket.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TimeyMessageHandler implements WebSocketHandler {
	
	private TimeyMessageService timeyMessageService;

	private UserService userService;
	
	public TimeyMessageHandler(){}
	
	public TimeyMessageHandler(TimeyMessageService timeyMessageService, UserService userService) {
		this.timeyMessageService = timeyMessageService;
		this.userService = userService;
	}
	
	//在线用户列表
    private static final Map<Long, WebSocketSession> users;
   
    static {
        users = new HashMap<>();
    }
    
    //新增socket
    @Override
    public void afterConnectionEstablished(WebSocketSession session){
    	 Long userId = getCurrentUser(session);
    	 users.put(userId, session);
         if (userId != null) ;
    }
 
    //接收socket信息
    @Override
	public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
    	try{
    		Long userId = getCurrentUser(webSocketSession);
    		TimeyMessage timeyMessage = new TimeyMessage();
    		timeyMessage.setUserId(userId);
    		List<TimeyMessageVo> voList = new ArrayList<>();
    		pushMessageToUser(userId, voList);
    	 }catch(Exception e){
      	   e.printStackTrace();
         }		
	}
    /**
     *@Author huangyuan
     *@Description 给多个用户推送消息
     *@Date 21:36 2019-04-19
     *@Param [userIds, timeyMessages, count]
     *@return boolean
     **/
	public static boolean pushMessageToUsers(List<Long> userIds, List<TimeyMessageVo> timeyMessages){
        try{
            if(userIds != null && userIds.size() > 0) {
                for(Long userId : userIds) {
                    WebSocketSession session = users.get(userId);
                    if(session != null) {
                        //新建消息体
                        RealTimeMessage realTimeMessage;
                        if(timeyMessages == null || timeyMessages.size() > 0){
                            TimeyMessageVo vo = timeyMessages.get(0);
                            realTimeMessage = new RealTimeMessage(timeyMessages);
                            realTimeMessage.setSize((long) timeyMessages.size());
                            realTimeMessage.setMsgType(vo.getType());
                        } else {
                            realTimeMessage = new RealTimeMessage();
                            realTimeMessage.setSize(0L);
                        }
                        session.sendMessage(new TextMessage(JSONUtil.parseObj(realTimeMessage).toString()));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     *@Author huangyuan
     *@Description 把消息推给单个用户
     *@Date 21:35 2019-04-19
     *@Param [userId, timeyMessages]
     *@return boolean
     **/
    public static boolean pushMessageToUser(Long userId, List<TimeyMessageVo> timeyMessages){
        List<Long> userIds = new ArrayList<>();
        userIds.add(userId);
        return pushMessageToUsers(userIds, timeyMessages);
    }

    /**
     *@Author huangyuan
     *@Description 给单独用户推送信息
     *@Date 00:35 2019-04-20
     *@Param [userId, timeyMessage]
     *@return boolean
     **/
    public static boolean pushMessageToUser(Long userId, TimeyMessage timeyMessage){
        TimeyMessageVo vo = new TimeyMessageVo(timeyMessage);
        List<TimeyMessageVo> voList = new ArrayList<>();
        voList.add(vo);
        return pushMessageToUser(userId, voList);
    }
 
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            session.close();
        }
        System.out.println("连接出错");
        users.remove(getCurrentUser(session));
    }
 
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("连接已关闭：" + status);
        users.remove(getCurrentUser(session));
    }
 
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
    
    /**
     * 获取用户id，作为标识
     *@author huangy
     *@date 2018年9月18日
     *@param session
     *@return Long
     *@throws
     */
    private Long getCurrentUser(WebSocketSession session) {
    	Long userId;
    	try {
    		userId  = (Long) session.getAttributes().get(ApiConstants.CURRENT_USER_ID);
    	} catch (Exception e) {
    		e.printStackTrace();
    		return null;
    	}
    	return userId;
    }

}
