package com.tourism.webadmin.ws.mq;

import com.alibaba.fastjson.JSON;
import com.tourism.webadmin.app.website.dto.InteractionMessageDto;
import com.tourism.webadmin.app.website.dto.SystemMessageDTO;
import com.tourism.webadmin.back.model.TourImMessage;
import com.tourism.webadmin.back.model.constant.NoticeType;
import com.tourism.webadmin.back.service.TourImMessageService;
import com.tourism.webadmin.enums.SystemDefault;
import com.tourism.webadmin.enums.SystemDefaultHead;
import com.tourism.webadmin.strategy.dto.FocusDTO;
import com.tourism.webadmin.ws.handle.SystemMessageHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.*;

@Configuration
public class RabbitMQConsumer {
    @Autowired
    private SystemMessageHandler systemMessageHandler;
    @Autowired
    private TourImMessageService tourImMessageService;

    /**
     * 系统消息
     * @param message
     * @throws Exception
     */
    @RabbitListener(queues = "systemQueue")
    public void getSystemMessage(String message) throws Exception {
        //转换为json对象
        SystemMessageDTO systemMessageDTO = JSON.parseObject(message, SystemMessageDTO.class);
            //从json对象中获取GetUserId //getUserId sendUserId sendTime
            String userId = systemMessageDTO.getGetUserId();
            if (Objects.nonNull(userId) && StringUtils.isBlank(userId.toString())) {
                //构建数据库对象
                TourImMessage build = new TourImMessage();
                build.setIsTop(0);
                build.setMessageType(0);
                build.setDataState(1);
                build.setNoticeType(NoticeType.NOTICE_SYSTEM);
                build.setRevocationTag(0);
                build.setReadByUsers("-1");
                build.setDeletedByUsers("");
                build.setGroupId(SystemDefault.SYSTEM_USERID_OR_GROUPID);
                build.setCreateTime(new Date());
                build.setUpdateTime(new Date());
                build.setCreateUserId(Long.valueOf(systemMessageDTO.getSendUserId()));
                build.setUpdateUserId(Long.valueOf(systemMessageDTO.getSendUserId()));
                build.setMessageContent(JSON.toJSONString(systemMessageDTO));
                //websocket推送
                systemMessageHandler.sendAllMessage(new TextMessage(message));
                //消息入库
                tourImMessageService.save(build);
            }else if (Objects.nonNull(userId) && StringUtils.isNotBlank(userId.toString())){
                //获取websocket在线集合
                Map<String, WebSocketSession> sessionMap = systemMessageHandler.getSessionMap();
                //判断是否接收人是否在线
                boolean containsKey = sessionMap.containsKey(userId.toString());
                if (containsKey) {
                    //在线直接已读
                    ArrayList<String> strings = new ArrayList<>();
                    strings.add(userId.toString());
                    TourImMessage build = new TourImMessage();
                    build.setIsTop(0);
                    build.setMessageType(0);
                    build.setMessageContent(JSON.toJSONString(systemMessageDTO));
                    build.setDataState(1);
                    build.setNoticeType(NoticeType.NOTICE_SYSTEM);
                    build.setRevocationTag(0);
                    build.setReadByUsers("-1");
                    build.setDeletedByUsers("");
                    build.setReadByUsers(JSON.toJSONString(strings));
                    build.setCreateTime(new Date());
                    build.setUpdateTime(new Date());
                    build.setGroupId(SystemDefault.SYSTEM_USERID_OR_GROUPID);
                    build.setCreateUserId(Long.valueOf(systemMessageDTO.getSendUserId()));
                    build.setUpdateUserId(Long.valueOf(systemMessageDTO.getSendUserId()));
                    //发送给在线人消息
                    systemMessageHandler.sendMessage(JSON.toJSONString(message),sessionMap.get(userId.toString()));
                    //入库
                    tourImMessageService.save(build);

                }else {
                    //设置为离线消息
                    TourImMessage build = new TourImMessage();
                    build.setIsTop(0);
                    build.setMessageType(0);
                    build.setMessageContent(JSON.toJSONString(systemMessageDTO));
                    build.setDataState(1);
                    build.setNoticeType(3);
                    build.setRevocationTag(0);
                    build.setReadByUsers("-1");
                    build.setDeletedByUsers("");
                    build.setCreateTime(new Date());
                    build.setUpdateTime(new Date());
                    build.setGroupId(SystemDefault.SYSTEM_USERID_OR_GROUPID);
                    build.setCreateUserId(Long.valueOf(systemMessageDTO.getSendUserId()));
                    build.setUpdateUserId(Long.valueOf(systemMessageDTO.getSendUserId()));
                    //入库
                    tourImMessageService.save(build);
                }
            }else {
                return;
            }
    }


    /**
     * 互动消息
     * @param message
     * @throws Exception
     */
    @RabbitListener(queues = "interactQueue")
    public void getInteractMessage(String message) throws Exception {
        //处理互动消息
        InteractionMessageDto interactDTO = JSON.parseObject(message, InteractionMessageDto.class);

        TourImMessage tourImMessage = new TourImMessage();
        tourImMessage.setMessageType(0);

        tourImMessage.setReadByUsers("-3");
        tourImMessage.setGroupId(SystemDefault.INTERACT_USERID_OR_GROUPID);//互动消息
        tourImMessage.setMessageContent(message);
        tourImMessage.setMessageType(interactDTO.getMessageType());
        tourImMessage.setNoticeType(Integer.valueOf(interactDTO.getNoticeType()));
        //群聊ID
        tourImMessage.setGroupId(Long.valueOf(SystemDefaultHead.INTERACT_USERID_OR_GROUPID.getGroupId()));

        tourImMessage.setCreateTime(new Date());
        tourImMessage.setCreateUserId(Long.valueOf(interactDTO.getSendUserId()));
        tourImMessage.setUpdateTime(new Date());
        tourImMessage.setUpdateUserId(Long.valueOf(interactDTO.getSendUserId()));

        Map<String, WebSocketSession> sessionMap = systemMessageHandler.getSessionMap();
        if (sessionMap.containsKey(interactDTO.getGetUserId())) {
            systemMessageHandler.sendSingleMessage(new TextMessage(message), sessionMap.get(interactDTO.getGetUserId()));
        }
        tourImMessageService.save(tourImMessage);
    }

    /**
     * 关注消息
     * @param message
     * @throws Exception
     */

    @RabbitListener(queues = "focusQueue")
    public void getFocusMessage(String message) throws Exception {
        // 转换为 JSON 对象
        FocusDTO focusDTO = JSON.parseObject(message, FocusDTO.class);
        String userId = focusDTO.getGetUserId();

        if (!Objects.isNull(userId) &&! StringUtils.isBlank(userId)) {
            Map<String, WebSocketSession> sessionMap = systemMessageHandler.getSessionMap();
            boolean isUserOnline = sessionMap.containsKey(userId);
            if (isUserOnline) {
                // 在线直接已读并发送消息
                systemMessageHandler.sendMessage(message, sessionMap.get(userId));
            }
            // 构建消息对象
            TourImMessage tourImMessage = buildFocusMessage(focusDTO, List.of(userId));
            // 消息入库
            tourImMessageService.save(tourImMessage);
        }
    }

    private TourImMessage buildFocusMessage(FocusDTO focusDTO, List<String> readByUsers) {
        TourImMessage message = new TourImMessage();
        message.setIsTop(0);
        message.setMessageType(0);
        message.setDataState(1);
        message.setNoticeType(NoticeType.NOTICE_FOCUS);
        message.setRevocationTag(0);
        message.setReadByUsers("-2");
        message.setDeletedByUsers("");
        message.setCreateTime(new Date());
        message.setUpdateTime(new Date());
        message.setGroupId(SystemDefault.FOCUS_USERID_OR_GROUPID);
        message.setCreateUserId(Long.valueOf(focusDTO.getSendUserId()));
        message.setUpdateUserId(Long.valueOf(focusDTO.getSendUserId()));
        message.setMessageContent(JSON.toJSONString(focusDTO));
//        if (readByUsers != null) {
//            message.setReadByUsers(JSON.toJSONString(readByUsers));
//        }
        return message;
    }


}
