package com.m2pool.chat.listener;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.m2pool.chat.entity.ChatMessage;
import com.m2pool.chat.entity.ChatRoom;
import com.m2pool.chat.entity.StompPrincipal;
import com.m2pool.chat.mapper.ChatMessageMapper;
import com.m2pool.chat.mapper.ChatRoomMapper;
import com.m2pool.chat.service.impl.StompServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.messaging.Message;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import javax.annotation.Resource;

import static com.m2pool.chat.constant.UserType.TOURIST;

/**
 * websocket通道关闭监听器
 */
@Component
public class WebSocketEventListener implements ApplicationListener<SessionDisconnectEvent>{

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketEventListener.class);

    @Resource
    private StompServiceImpl stompService;

    @Resource
    private ChatRoomMapper chatRoomMapper;

    @Resource
    private ChatMessageMapper chatMessageMapper;

    @Override
    public void onApplicationEvent(SessionDisconnectEvent event) {
        StompPrincipal user = (StompPrincipal) event.getUser();
        Message<byte[]> message = event.getMessage();
        StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
        if (user != null) {
            LOGGER.info("用户{}断开链接：用户类型{},消息类型{}",user.getName(), user.getType(),  accessor.getCommand());
            if (accessor.getCommand() == StompCommand.DISCONNECT && TOURIST.equals(user.getType())) {
                //游客断开链接，通知客服删除游客聊天室
                stompService.customerCloseRoom(user.getName());
                // 删除数据库中游客数据
                int delete = chatRoomMapper.delete(new LambdaUpdateWrapper<ChatRoom>()
                        .eq(ChatRoom::getUserOneEmail, user.getName()).like(ChatRoom::getUserOneEmail, "guest_"));
                int delete1 = chatMessageMapper.delete(new LambdaUpdateWrapper<ChatMessage>()
                        .eq(ChatMessage::getSendEmail, user.getName()).like(ChatMessage::getSendEmail, "guest_"));
                LOGGER.info("删除游客聊天室个数：{},消息个数{}", delete,delete1);
            }

        }

    }
}
