package com.ssyf.ws.handler.biz;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ssyf.ws.constants.CommandType;
import com.ssyf.ws.domain.Command;
import com.ssyf.ws.domain.WsMessage;
import com.ssyf.ws.handler.CommandHandler;
import com.ssyf.ws.handler.system.MessageDispatcher;
import com.ssyf.ws.service.MessageService;
import com.ssyf.ws.service.WsClientService;
import com.ssyf.ws.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * 聊天命令处理器
 * 处理所有聊天相关的命令
 */
@Slf4j
@Component
public class ChatCommandHandler implements CommandHandler {

    @Autowired
    private MessageDispatcher messageDispatcher;
    
    @Autowired
    private MessageService messageService;

    @Autowired
    private WsClientService wsClientService;

    /**
     * 初始化时注册处理器
     */
    @PostConstruct
    public void init() {
        messageDispatcher.registerHandler(CommandType.CHAT_INIT, this);
        messageDispatcher.registerHandler(CommandType.CHAT_SEND, this);
        messageDispatcher.registerHandler(CommandType.CHAT_RECEIVE, this);
        messageDispatcher.registerHandler(CommandType.CHAT_STATUS_QUERY, this);
        messageDispatcher.registerHandler(CommandType.CHAT_STATUS_UPDATE, this);
        messageDispatcher.registerHandler(CommandType.CHAT_READ_CONFIRM, this);
        log.info("聊天命令处理器注册完成");
    }

    @Override
    public void handle(Command command, WebSocketSession session) {
        CommandType commandType = command.getType();
        
        switch (commandType) {
            case CHAT_INIT:
                handleChatInit(command, session);
                break;
            case CHAT_SEND:
                handleChatSend(command, session);
                break;
            case CHAT_STATUS_QUERY:
                handleChatStatusQuery(command, session);
                break;
            case CHAT_READ_CONFIRM:
                handleChatReadConfirm(command, session);
                break;
            default:
                log.warn("未处理的聊天命令类型: {}", commandType);
                sendErrorResponse(session, "不支持的聊天命令类型");
        }
    }

    private void handleChatInit(Command command, WebSocketSession session) {
        Object object = command.getOriginalMessage().getData();
        if(object == null){
            log.warn("聊天初始化命令数据为空");
            this.wsClientService.sendErrorMessage(session, command.getOriginalMessage(), "聊天初始化命令数据为空");
            return;
        }
        String masterAccountId = "";
        String fansAccountId = "";
        if (object instanceof Map) {
            Map<String, Object> data = (Map<String, Object>) object;
            masterAccountId = (String) data.get("masterAccountId");
            fansAccountId = (String) data.get("fansAccountId");
        }else if(object instanceof String){
            String json = (String) object;
            Map<String, Object> data = JSONUtil.toBean(json, Map.class);
            masterAccountId = (String) data.get("masterAccountId");
            fansAccountId = (String) data.get("fansAccountId");
        }else if(object instanceof JSONObject){
            JSONObject data = (JSONObject) object;
            masterAccountId = (String) data.get("masterAccountId");
            fansAccountId = (String) data.get("fansAccountId");
        }else {
            log.warn("聊天初始化命令数据格式错误");
            this.wsClientService.sendErrorMessage(session, command.getOriginalMessage(), "聊天初始化命令数据格式错误");
            return;
        }
        if (masterAccountId == null || masterAccountId.isEmpty() || fansAccountId == null || fansAccountId.isEmpty()) {
            log.warn("聊天初始化命令数据错误");
            this.wsClientService.sendErrorMessage(session, command.getOriginalMessage(), "聊天初始化命令数据错误");
            return;
        }
        this.wsClientService.initChatSession(session, masterAccountId, fansAccountId);
    }

    /**
     * 处理发送消息命令
     */
    private void handleChatSend(Command command, WebSocketSession session) {
        WsMessage message = command.getOriginalMessage();
        log.debug("收到发送消息命令: {}", message);
    }

    /**
     * 处理消息状态查询命令
     */
    private void handleChatStatusQuery(Command command, WebSocketSession session) {
        WsMessage message = command.getOriginalMessage();
        log.debug("收到消息状态查询命令: {}", message);

    }

    /**
     * 处理消息已读确认命令
     */
    private void handleChatReadConfirm(Command command, WebSocketSession session) {
        WsMessage message = command.getOriginalMessage();
        log.debug("收到消息已读确认命令: {}", message);
    }

    /**
     * 发送响应消息
     */
    private void sendResponse(WebSocketSession session, WsMessage response) {
        try {
            if (session.isOpen()) {
                session.sendMessage(new TextMessage(JsonUtils.toJson(response)));
            }
        } catch (IOException e) {
            log.error("发送聊天响应失败", e);
        }
    }

    /**
     * 发送错误响应
     */
    private void sendErrorResponse(WebSocketSession session, String errorMsg) {

    }

    /**
     * 生成消息ID
     */
    private String generateMessageId() {
        return "msg_" + System.currentTimeMillis() + "_" + UUID.randomUUID().toString().substring(0, 8);
    }
}