package com.gxwebsoft.love.socketio.handler;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.gxwebsoft.common.core.config.ConfigProperties;
import com.gxwebsoft.common.system.entity.Role;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.UserService;
import com.gxwebsoft.love.entity.ChatMessage;
import com.gxwebsoft.love.service.ChatConversationService;
import com.gxwebsoft.love.service.ChatMessageService;
import com.gxwebsoft.love.socketio.cache.ClientCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;



/**
 * socket处理拦截器
 * @author machenike
 */

@Component
public class SocketIOHandler {


    @Resource
    private ChatMessageService messageService;

    @Resource
    private ChatConversationService conversationService;

    @Resource
    private ClientCache clientCache;

    @Resource
    private UserService userService;

    @Resource
    private ConfigProperties configProperties;
    /**
     * 日志
     */
    private final static Logger logger = LoggerFactory.getLogger(SocketIOHandler.class);




    /**
     * 客户端连上socket服务器时执行此事件
     * @param client
     */
    @OnConnect
    public void onConnect(SocketIOClient client) {
        String userId = client.getHandshakeData().getSingleUrlParam("userId");
        logger.debug("socket client auth success [userId="+userId+"]");
        UUID sessionId = client.getSessionId();


        // 管理员
        String isAdmin = client.getHandshakeData().getSingleUrlParam("isAdmin");
        if(StringUtils.isNotBlank(isAdmin)){
           // todo 权限验证
            clientCache.saveClient("admin",sessionId, client);
        }else {
            clientCache.saveClient(userId,sessionId, client);
        }

        System.out.println("userId: "+userId+"连接建立成功 - "+sessionId);
        logger.info("当前在线人数:{}",clientCache.getOnLineCount());

    }


    /**
     * 客户端断开socket服务器时执行此事件
     * @param client
     */
    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        String userId = client.getHandshakeData().getSingleUrlParam("userId");
        UUID sessionId = client.getSessionId();
        clientCache.deleteSessionClientByUserId(userId,sessionId);
        System.out.println("userId: "+userId+"连接关闭成功 - "+sessionId);

    }

    /**
     *
     * @param client
     */
    @OnEvent( value = "message")
    @Transactional
    public void onMessage(SocketIOClient client, AckRequest request, ChatMessage message) {

    }

}