package com.wzj.soopin.im.event;

import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;

import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.json.utils.JsonUtils;
import com.wzj.soopin.im.consumer.MessageRocketMQConsumer;
import com.wzj.soopin.im.domain.event.MessageEvent;
import org.dromara.common.mq.service.IRocketMQService;
import com.wzj.soopin.im.service.ITencentIMService;
import org.dromara.system.websocket.MessageWebSocketServer;
import com.wzj.soopin.im.service.impl.TencentIMServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 消息事件监听器
 *
 * @author ruoyi
 */
@Slf4j
@Component
public class MessageEventListener {

    @Autowired
    private IRocketMQService rocketMQService;

    @Autowired
    private MessageWebSocketServer messageWebSocketServer;

    @Autowired
    @Qualifier("systemTencentIMService")
    private ITencentIMService tencentIMService;

    /**
     * 处理消息事件
     */
    @Async
    @EventListener
    public void handleMessageEvent(MessageEvent event) {
        try {
            // 提取消息和用户ID
            String userId = event.getUserIdStr();

            // 创建消息包装对象
//            MessageRocketMQConsumer.MessageWrapper wrapper = new MessageRocketMQConsumer.MessageWrapper();
//            wrapper.setUserId(userId);
//            wrapper.setMessage(event.getMessage());

            // 首先尝试发送消息到腾讯IM
            boolean tencentIMSendSuccess = false;
            try {
                // 消息发送者可能是系统或管理员，这里使用固定的管理员账号作为发送者
                String fromUserId = event.getMessage().getSenderId();
                String toUserId = userId; // 接收者是事件中的用户ID
                String content = event.getMessage().getContent(); // 只取content字段

                // 处理消息变量替换（如果有）
                Map<String, String> variables = new HashMap<>();
                // 这里可以添加变量映射，例如：variables.put("userName", "张三");

                // 从消息中提取标题和描述
                String title = event.getMessage().getTitle();
                String desc = event.getMessage().getContent();

                // 处理变量替换
                if (variables.size() > 0) {
                    title = tencentIMService.processMessageVariables(title, variables);
                    desc = tencentIMService.processMessageVariables(desc, variables);
                }

                // 扩展字段，可以在APP端获取
                String ext = null;
                if (StringUtils.isNotBlank(event.getMessage().getExt())) {
                    ext = JsonUtils.toJsonString(event.getMessage().getExt());
                }

                String templateParams = event.getMessage().getTemplate().getParams();
                // 根据消息类型决定推送方式
                JSONObject params = new JSONObject(templateParams);
                String pushType = null;
                if (params != null && params.get("pushType")!=null) {
                    pushType = String.valueOf(params.get("pushType"));
                }

                if (pushType != null) {
                    switch (pushType) {
                        case "ALL":
                            // 全员推送
                            tencentIMSendSuccess = tencentIMService.pushToAll(title, desc, true, ext);
                            break;
                        case "ATTRIBUTE":
                            // 属性推送
                            Map<String, Object> attributes = new HashMap<>();
                            // 从消息参数中提取属性条件
                            if (params != null && params.containsKey("attributes")) {
                                Object attrObj = params.get("attributes");
                                if (attrObj instanceof Map) {
                                    attributes = (Map<String, Object>) attrObj;
                                }
                            }
                            tencentIMSendSuccess = tencentIMService.pushByAttributes(title, desc, attributes, true, ext);
                            break;
                        case "TAG":
                            // 标签推送
                            if (params != null && params.containsKey("tags")) {
                                Object tagsObj = params.get("tags");
                                if (tagsObj instanceof String[]) {
                                    tencentIMSendSuccess = tencentIMService.pushByTags(title, desc,
                                        Arrays.asList((String[]) tagsObj), true, ext);
                                }
                            }
                            break;
                        case "USER":
                        default:
                            // 单用户推送（默认）
                            tencentIMSendSuccess = tencentIMService.pushToUsers(title, desc,
                                Collections.singletonList(toUserId), true, ext);
                            break;
                    }
                } else {
                    // 默认为单用户推送
                    tencentIMSendSuccess = tencentIMService.sendMessageToTencentIM(fromUserId, toUserId, content,ext);

                }
                if (tencentIMSendSuccess) {
                    log.info("腾讯IM推送成功，userId={}", toUserId);
                } else {
                    log.warn("腾讯IM推送失败，userId={}", toUserId);
                }
            } catch (Exception e) {
                log.error("发送消息到腾讯IM异常，将尝试通过其他方式发送", e);
            }

            boolean rocketMQSendSuccess = false; // 直接设为false，表示不走MQ

            // 如果前两种方式都失败，则尝试直接通过WebSocket发送
            if (!tencentIMSendSuccess && !rocketMQSendSuccess && event.getUserId() != null) {
                try {
                    messageWebSocketServer.sendMessage(
                        event.getUserId(),
                        JsonUtils.toJsonString(event.getMessage())
                    );
                    log.info("消息事件已直接通过WebSocket发送，userId: {}", event.getUserId());
                } catch (Exception e) {
                    log.error("通过WebSocket发送消息失败", e);
                }
            }
        } catch (Exception e) {
            log.error("处理消息事件失败", e);
        }
    }
}
