package com.pz.chat.controller;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pz.chat.util.CurPool;
import com.pz.chat.util.JsonUtils;
import com.pz.chat.util.SpringContextUtil;
import com.pz.common.core.domain.entity.SysUser;
import com.pz.system.domain.MsgInfo;
import com.pz.system.domain.SessionList;
import com.pz.system.mapper.MsgInfoMapper;
import com.pz.system.mapper.SessionListMapper;
import com.pz.system.mapper.SysUserMapper;
import com.pz.system.service.IMsgInfoService;
import com.pz.system.service.ISessionListService;
import com.pz.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@ServerEndpoint("/websocket/{userId}/{sessionId}")
public class ChatController {

    @Resource
    private SessionListMapper sessionListMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private MsgInfoMapper msgInfoMapper;

    private Session session;

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") Integer userId, @PathParam(value = "sessionId") String sessionId) {
        this.session = session;
        // 打开连接时保存WebSocket的会话对象
        CurPool.webSockets.put(userId, this);
        // 将WebSocket对象放入WebSocket连接池中
        List<Object> list = new ArrayList<>();
        list.add(sessionId);
        list.add(session);
        // 将会话ID和会话对象放入会话池中
        CurPool.sessionPool.put(userId, list);
    }

    @OnClose
    public void onClose() {
        // 断开连接删除用户删除session
        Long userId = Long.parseLong(this.session.getRequestParameterMap().get("userId").get(0));
        // 获取用户ID
        CurPool.sessionPool.remove(userId);
        CurPool.webSockets.remove(userId);
        // 从会话池和连接池中移除WebSocket对象
        if (sysUserMapper == null) {
            this.sysUserMapper = (SysUserMapper) SpringContextUtil.getBean("sysUserMapper");
        }
        SysUser user = sysUserMapper.selectUserById(userId);
        // 从用户池中移除用户
        CurPool.curUserPool.remove(user.getNickName());
    }

    @OnMessage
    public void onMessage(String message) {
        String sessionId = this.session.getRequestParameterMap().get("sessionId").get(0);
        // 获取会话ID
        if (sessionId == null) {
            System.out.println("sessionId 错误");
        }
        if (sessionListMapper == null) {
            this.sessionListMapper = (SessionListMapper) SpringContextUtil.getBean("sessionListMapper");
        }
        // 根据会话ID注入SeesionListMapper
        if (sysUserMapper == null) {
            this.sysUserMapper = (SysUserMapper) SpringContextUtil.getBean("sysUserMapper");
        }
        // 根据会话ID注入UserMapper
        if (msgInfoMapper == null) {
            this.msgInfoMapper = (MsgInfoMapper) SpringContextUtil.getBean("msgInfoMapper");
        }
        SessionList sessionList = sessionListMapper.selectById(Long.parseLong(sessionId));
        // 根据会话ID查询会话列表

        SysUser user = sysUserMapper.selectUserById(sessionList.getUserId());
        // 根据会话列表中的用户ID查询用户信息
        MsgInfo msgInfo = new MsgInfo();
        msgInfo.setContent(message);
        msgInfo.setFromUserId(sessionList.getUserId());
        msgInfo.setFromUserName(user.getNickName());
        msgInfo.setToUserId(sessionList.getToUserId());
        msgInfo.setToUserName(sessionList.getListName());
        msgInfo.setUnReadFlag(0L);
        // 创建消息对象,设置消息的内容、创建时间、发送方和接收方的信息
        msgInfoMapper.insert(msgInfo);
        // 将消息持久化到数据库中
        List<Object> list = CurPool.sessionPool.get(sessionList.getToUserId());
        // 根据接收方的用户ID从会话池中获取会话列表
        if (list == null || list.isEmpty()) {
            sessionListMapper.addUnReadCount(sessionList.getToUserId(), sessionList.getUserId());
            // 用户不存在,更新未读消息数量
        } else {
            String id = sessionListMapper.selectIdByUser(sessionList.getToUserId(), sessionList.getUserId()) + "";
            String o = list.get(0) + "";
            if (id.equals(o)) {
                sendTextMessage(sessionList.getToUserId(), JsonUtils.objectToJson(msgInfo));
                // 会话存在,直接发送消息
            } else {
                if (StringUtils.isNotBlank(id)) {
                    SessionList tmpSessionList = new SessionList();
                    tmpSessionList.setUserId(sessionList.getToUserId());
                    tmpSessionList.setToUserId(sessionList.getUserId());
                    tmpSessionList.setListName(user.getNickName());
                    tmpSessionList.setUnReadCount(1L);
                    sessionListMapper.insert(tmpSessionList);
                    // 新增会话列表
                } else {
                    sessionListMapper.addUnReadCount(sessionList.getToUserId(), sessionList.getUserId());
                    // 更新未读消息数量
                }
                List<SessionList> sessionLists = sessionListMapper.selectList(Wrappers.<SessionList>lambdaQuery().eq(SessionList::getUserId, sessionList.getToUserId()));
                // 会话不存在,发送会话列表消息
                sendTextMessage(sessionList.getToUserId(), JsonUtils.objectToJson(sessionLists));
            }
        }
        // 输出收到的消息
        System.out.println("【websocket消息】收到客户端消息:" + message);
    }

    public void sendTextMessage(Long userId, String message) {
        Session session = (Session) CurPool.sessionPool.get(userId).get(1);
        // 根据用户ID从会话池中获取会话对象
        if (session != null) {
            try {
                session.getBasicRemote().sendText(message);
                // 发送文本消息
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}