
package com.tmerclub.cloud.im.socket.platform;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.tmerclub.cloud.api.auth.bo.UidInfoBO;

import com.tmerclub.cloud.api.auth.feign.TokenFeignClient;
import com.tmerclub.cloud.api.platform.feign.SysUserFeignClient;
import com.tmerclub.cloud.api.platform.vo.SysUserVO;
import com.tmerclub.cloud.api.user.feign.UserFeignClient;
import com.tmerclub.cloud.api.user.vo.UserApiVO;
import com.tmerclub.cloud.common.cache.util.RedisUtil;
import com.tmerclub.cloud.common.database.vo.PageVO;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.util.Json;
import com.tmerclub.cloud.common.util.MapUtil;
import com.tmerclub.cloud.im.constants.Constant;
import com.tmerclub.cloud.im.constants.MsgCode;
import com.tmerclub.cloud.im.constants.SendType;
import com.tmerclub.cloud.im.model.ImMsgBizUserHistory;
import com.tmerclub.cloud.im.service.ImMsgBizUserHistoryService;
import com.tmerclub.cloud.im.socket.app.UserOnlineWebSocketServer;
import com.tmerclub.cloud.im.socket.app.UserWebSocketServer;
import com.tmerclub.cloud.im.vo.MessageInfoVO;
import com.tmerclub.cloud.im.vo.MsgItemVO;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 平台收到的消息
 * 10,"无法获取用户信息"
 * 11,"账户已在别处登录，请刷新"
 * 12,"对方不在线"
 * 13, "内容格式有误"
 *
 * @author Lzk
 */
@ServerEndpoint("/p/ua/im/websocket/{token}/{userId}")
@Component
public class SysWebSocketServer {
    private static final Logger LOG = LoggerFactory.getLogger(SysWebSocketServer.class);

    /**
     * userId为key
     */
    public static final ConcurrentHashMap<String, Session> SYS_MAP = new ConcurrentHashMap<>(256);

    private static TokenFeignClient tokenFeignClient;

    private static SysUserFeignClient sysUserFeignClient;

    private static UserFeignClient userFeignClient;

    private static SysUserFeignClient sysUserClient;

    private static ImMsgBizUserHistoryService imMsgBizUserHistoryService;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        tokenFeignClient = applicationContext.getBean(TokenFeignClient.class);
        sysUserFeignClient = applicationContext.getBean(SysUserFeignClient.class);
        userFeignClient = applicationContext.getBean(UserFeignClient.class);
        imMsgBizUserHistoryService = applicationContext.getBean(ImMsgBizUserHistoryService.class);
        sysUserClient = applicationContext.getBean(SysUserFeignClient.class);
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) throws IOException {
        token = Base64.decodeStr(token);
        UidInfoBO uidInfoBO = tokenFeignClient.checkToken(token);
        if (uidInfoBO == null) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(MsgCode.CAN_NOT_FIND_USER_INFO, "无法获取平台用户信息")));
            }
            return;
        }

        // 如果原来就有token
        Session oldSession = SYS_MAP.get(Constant.SYS_PREFIX + uidInfoBO.getUserId());
        if (oldSession != null) {
            // 客户端收到11，关闭ws链接，弹出提示
            if (oldSession.isOpen()) {
                oldSession.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(11, "账户已在别处登录，请刷新")));
                oldSession.close();
            }
        }

        SYS_MAP.put(Constant.SYS_PREFIX + uidInfoBO.getUserId(), session);
        if (session.isOpen()) {
            session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success("ok")));
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam("token") String token, @PathParam("userId") Long userId) {
        SYS_MAP.remove(Constant.SYS_PREFIX + userId);
    }

    /**
     * 连接错误调用的方法
     */
    @OnError
    public void onError(Session session, @PathParam("token") String token, Throwable error, @PathParam("userId") Long userId) {
        SYS_MAP.remove(Constant.SYS_PREFIX + userId);
        LOG.error("平台客服执行异常：{}", error);
    }

    /**
     * 收到客户端消息后调用的方法，该消息由用户发过来
     *
     * @param sourceMessage 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String sourceMessage, @PathParam("token") String token, Session session) throws IOException {
        token = Base64.decodeStr(token);
        UidInfoBO uidInfoBO = tokenFeignClient.checkToken(token);
        if (Objects.isNull(uidInfoBO)) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(MsgCode.CAN_NOT_FIND_USER_INFO, "无法获取平台的用户信息")));
            }
            return;
        }

        if (StrUtil.isBlank(sourceMessage)) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(MsgCode.CONTENT_FORMAT_ERROR, "平台的消息内容格式有误")));
            }
            return;
        }

        MessageInfoVO messageInfo = Json.parseObject(sourceMessage, MessageInfoVO.class);

        if (Objects.isNull(messageInfo)) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(MsgCode.CONTENT_FORMAT_ERROR, "平台消息内容格式有误")));
            }
            return;
        }

        // 保持心跳
        if (StrUtil.equals(messageInfo.getContent(), Constant.HEART_BEAT)) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.HEART_BEAT, "保持心跳")));
            }
            return;
        }

        Long userId = messageInfo.getToId();
        ServerResponseEntity<UserApiVO> userApiResponse = userFeignClient.getInsiderUserData(userId);
        if (!userApiResponse.isSuccess()) {
            throw new LuckException(userApiResponse.getMsg());
        }
        UserApiVO user = userApiResponse.getData();
        if (Objects.isNull(user)) {
            user = new UserApiVO();
            user.setUserName("*用户已注销*");
            user.setNickName("*用户已注销*");
            user.setUserId(userId);
        }

        sendToUser(messageInfo, uidInfoBO, user, session);
    }

    public void sendToUser(MessageInfoVO messageInfo, UidInfoBO uidInfoBO, UserApiVO user, Session session) throws IOException {
        ServerResponseEntity<SysUserVO> sysUserResponse2 = sysUserFeignClient.getSysUserByUserId(uidInfoBO.getUserId());
        if (!sysUserResponse2.isSuccess()) {
            throw new LuckException(sysUserResponse2.getMsg());
        }
        SysUserVO sysUser2 = sysUserResponse2.getData();

        // 获取消息历史
        if (Objects.nonNull(messageInfo.getHistory()) && Objects.equals(messageInfo.getHistory(), true)) {
            PageVO<MsgItemVO> msgItemPage = imMsgBizUserHistoryService.getPlatformUserHistory(uidInfoBO, messageInfo, user, sysUser2);
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.HISTORY, msgItemPage)));
            }
            return;
        }

        // 标记消息已读
        if (Objects.nonNull(messageInfo.getRead()) && Objects.equals(messageInfo.getRead(), true)) {
            markIsRead(messageInfo, uidInfoBO, user, session);
            return;
        }

        if (Objects.nonNull(messageInfo.getOnlineOrOffline()) && Objects.equals(messageInfo.getOnlineOrOffline(), true)) {
            sendOnlineMsg(user, session);
        }

        String tempString = RedisUtil.get(Constant.IN_CHARGE_SYS + messageInfo.getToId());
        Long sysUserId = null;
        if (Objects.nonNull(tempString)) {
            sysUserId = Long.valueOf(tempString.substring(4));
            SysUserVO userVO = sysUserFeignClient.getSysUserByUserId(sysUserId).getData();
            if (userVO == null) {
                // 负责客户的客服不存在，删除缓存
                RedisUtil.del(Constant.IN_CHARGE_SYS + messageInfo.getToId());
            } else if (!Objects.equals(sysUserId, uidInfoBO.getUserId())) {
                if (session.isOpen()) {
                    session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(15, "不是你负责的客户")));
                }
                return;
            }
        }

        // 用户注销后不可以进行后面的操作
        if (Objects.isNull(user.getUserId())) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(MsgCode.USER_ACCOUNT_CANCELLATION, "无接收消息的联系人")));
            }
            return;
        }
        if (Objects.isNull(user.getStatus())) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(MsgCode.USER_ACCOUNT_CANCELLATION, "用户账号已注销")));
            }
            return;
        }
        // 获取可转接客服列表
        if (Objects.nonNull(messageInfo.getPlatformUserList()) && Objects.equals(messageInfo.getPlatformUserList(), true)) {
            getCanTransferList(uidInfoBO, session);
            return;
        }

        // 转接客服
        if (Objects.nonNull(messageInfo.getChangeTo()) && Objects.equals(messageInfo.getChangeTo(), true)) {
            transfer(messageInfo, uidInfoBO, user, session);
            return;
        }

        // 发送消息
        if (Objects.nonNull(messageInfo.getContent()) && !messageInfo.getContent().isEmpty()) {
            sendMsgToUser(messageInfo, uidInfoBO, user, sysUser2, sysUserId);
        }
    }

    private static void sendMsgToUser(MessageInfoVO messageInfo, UidInfoBO uidInfoBO, UserApiVO user, SysUserVO sysUser2, Long sysUserId) throws IOException {
        ImMsgBizUserHistory imMsgBizUserHistory = imMsgBizUserHistoryService.savePlatformUserHistory(messageInfo, uidInfoBO);
        // 在线的话发送消息，不在线的话留言
        Session userSession = UserWebSocketServer.USER_MAP.get(Constant.USER_PREFIX + messageInfo.getToId());
        if (Objects.nonNull(userSession)) {
            if (Objects.isNull(sysUserId)) {
                RedisUtil.set(Constant.IN_CHARGE_SYS + messageInfo.getToId(), "test" + uidInfoBO.getUserId(), 0);
            }
            imMsgBizUserHistory.setNickName(sysUser2.getNickName());
            MsgItemVO msgItem = imMsgBizUserHistoryService.getUserPlatformMsgItem(user, imMsgBizUserHistory);
            if (userSession.isOpen()) {
                SysUserVO sysUserVO = sysUserFeignClient.getSimpleByUserId(sysUserId);
                msgItem.setNickName(sysUserVO.getNickName());
                userSession.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(msgItem)));
            }
            List<Session> sessionList = MapUtil.getSessionByKeyPrefix(UserOnlineWebSocketServer.USER_ONLINE_MAP, Constant.ONLINE_USER_PREFIX + messageInfo.getToId() + Constant.UNDERLINE);
            if (!sessionList.isEmpty()) {
                MsgItemVO msgItem2 = new MsgItemVO();
                msgItem2.setNewMessage(true);
                for (Session onlineSession : sessionList) {
                    if (Objects.nonNull(onlineSession) && onlineSession.isOpen()) {
                        String jsonString = Json.toJsonString(ServerResponseEntity.success(msgItem2));
                        onlineSession.getBasicRemote().sendText(jsonString);
                    }
                }
            }
        }
    }

    private static void transfer(MessageInfoVO messageInfo, UidInfoBO uidInfoBO, UserApiVO user, Session session) throws IOException {
        if (Objects.nonNull(messageInfo.getPlatformUserId())) {
            Session userSession = UserWebSocketServer.USER_MAP.get(Constant.USER_PREFIX + messageInfo.getToId());
            Session sysSession = SYS_MAP.get(Constant.SYS_PREFIX + messageInfo.getPlatformUserId());
            if (Objects.nonNull(sysSession)) {
                RedisUtil.set(Constant.IN_CHARGE_SYS + messageInfo.getToId(), "test" + messageInfo.getPlatformUserId(), 0);
                ServerResponseEntity<SysUserVO> sysUserResponse3 = sysUserFeignClient.getSysUserByUserId(messageInfo.getPlatformUserId());
                if (!sysUserResponse3.isSuccess()) {
                    throw new LuckException(sysUserResponse3.getMsg());
                }
                SysUserVO sysUser3 = sysUserResponse3.getData();
                ImMsgBizUserHistory imMsgBizUserHistory = imMsgBizUserHistoryService.savePlatformChangeEmployeeReply(uidInfoBO, sysUser3, user);
                imMsgBizUserHistory.setNickName(sysUser3.getNickName());
                MsgItemVO msgItem = imMsgBizUserHistoryService.getUserPlatformMsgItem(user, imMsgBizUserHistory);
                if (session.isOpen()) {
                    session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.CHANGE_EMPLOYEE_SUCCESS, msgItem)));
                }
                // 在线的话发送消息，不在线的话留言
                if (Objects.nonNull(userSession) && userSession.isOpen()) {
                    userSession.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.CHANGE_EMPLOYEE_SUCCESS, msgItem)));
                }
                if (sysSession.isOpen()) {
                    sysSession.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.CHANGE_EMPLOYEE_SUCCESS, msgItem)));
                }
            }
        }
    }

    private static void getCanTransferList(UidInfoBO uidInfoBO, Session session) throws IOException {
        List<String> keys = MapUtil.getKeysByPrefixAndExcludeKey(SYS_MAP, Constant.SYS_PREFIX, Constant.SYS_PREFIX + uidInfoBO.getUserId());
        List<SysUserVO> listSysUser = new ArrayList<>(com.tmerclub.cloud.common.constant.Constant.INITIAL_CAPACITY);
        if (CollUtil.isEmpty(keys)) {
            return;
        }
        long tempLength = (Constant.SYS_PREFIX).length();
        for (String key : keys) {
            Long tempSysUserId = Long.valueOf(key.substring((int) tempLength));
            ServerResponseEntity<SysUserVO> dbSysUserResponse = sysUserClient.getSysUserByUserId(tempSysUserId);
            if (!dbSysUserResponse.isSuccess()) {
                throw new LuckException(dbSysUserResponse.getMsg());
            }
            SysUserVO dbSysUser = dbSysUserResponse.getData();
            SysUserVO onlineSysUser = new SysUserVO();
            onlineSysUser.setSysUserId(dbSysUser.getSysUserId());
            onlineSysUser.setNickName(dbSysUser.getNickName());
            listSysUser.add(onlineSysUser);
        }
        if (session.isOpen()) {
            session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.EMPLOYEE_ONLINE, listSysUser)));
        }
    }

    private static void sendOnlineMsg(UserApiVO user, Session session) throws IOException {
        Boolean isExist = MapUtil.isExistKeyPrefix(UserOnlineWebSocketServer.USER_ONLINE_MAP, Constant.ONLINE_USER_PREFIX + user.getUserId() + Constant.UNDERLINE + "*");
        MsgItemVO msgItem = new MsgItemVO();
        msgItem.setChatType(SendType.PLATFORM);
        msgItem.setUserId(user.getUserId());
        msgItem.setOnlineOrOffline(isExist);
        if (session.isOpen()) {
            session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.ONLINE_OR_OFFLINE, msgItem)));
        }
    }

    private static void markIsRead(MessageInfoVO messageInfo, UidInfoBO uidInfoBO, UserApiVO user, Session session) throws IOException {
        Integer updateNum = imMsgBizUserHistoryService.markUserReadBySendType(SendType.PLATFORM, messageInfo, uidInfoBO, user.getUserId());
        if (updateNum > 0) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.READ, "ok")));
            }
            Session userSession = UserWebSocketServer.USER_MAP.get(Constant.USER_PREFIX + messageInfo.getToId());
            if (Objects.nonNull(userSession)) {
                if (userSession.isOpen()) {
                    userSession.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.READ, messageInfo.getMsgIds())));
                }
            }
        }
    }

}
