package com.ssyf.task.websocket.msg;

import cn.hutool.json.JSONObject;
import com.ssyf.task.websocket.WsMessageStorageService;
import com.ssyf.third.bmiss.model.LiveRoom;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
public class ToastTipMessageHandler implements WsMessageHandler {

    @Autowired
    private WsMessageStorageService persistenceService;

    @Override
    public boolean supports(String scene, String type) {
        return "live".equals(scene) && "chat".equals(type);
    }

    /**
     * {"scene":"live","type":"chat","room_number":6273,"data":{"msg_type":1,"user":{"user_id":7281,"nick_name":"\u52ab\u6e21\u4eba","user_number":44020101,"head_portrait":"https:\/\/cos.bmiss3.zhubei.cn\/application_static_data\/static_data\/user\/avatar\/default\/7281_1764136746.png","head_portrait_box":"","noble_level":0,"consume_val":0},"content":[{"text":"\u52ab\u6e21\u4eba:","color":"#91D9FF"},{"text":"\u4e3b\u64ad\u4eca\u5929\u7684\u76f4\u64ad\u5185\u5bb9\u771f\u7cbe\u5f69\uff0c\u652f\u6301\u4e00\u4e0b\uff01","color":"#FFFFFF"}],"raw_content":"\u4e3b\u64ad\u4eca\u5929\u7684\u76f4\u64ad\u5185\u5bb9\u771f\u7cbe\u5f69\uff0c\u652f\u6301\u4e00\u4e0b\uff01","display_img":[{"local_img":"https:\/\/cos.bmiss3.zhubei.cn\/application_static_data\/static_data\/wealth\/wealth_29.png","network_img":"https:\/\/cos.bmiss3.zhubei.cn\/application_static_data\/static_data\/wealth\/wealth_29.png","img_type":"wealth_level","msg":""}],"grid":null,"at_user_id":0,"at_user":null}}
     * @param roomId 直播间ID
     * @param message 原始消息JSON对象
     * @param liveRoom
     * @param token
     */
    @Override
    public void handle(Integer roomId, JSONObject message, LiveRoom liveRoom, String token) {
        JSONObject data = message.getJSONObject("data");
        if (data == null || !data.containsKey("raw_content")) {
            return;
        };
        
        String msgContent = data.getStr("raw_content");
        String nickname = "";
        String sourceRole = "";
        String sourceUserId = "";
        if (data.containsKey("user")) {
            JSONObject user = data.getJSONObject("user");
            nickname = user.getStr("nick_name");
            sourceUserId = user.getStr("user_number");

            if(Objects.equals(liveRoom.getUser_id() , user.getInt("user_id")) || Objects.equals(liveRoom.getUser_number() , user.getInt("user_number"))){
                sourceRole = "anchor";
            }else{
                sourceRole = "user";
            }
        }


        // 调用持久化服务放入缓冲队列
        persistenceService.bufferMessage(roomId, nickname, "toast_tip", msgContent, message.toString() , sourceRole, sourceUserId);
    }
}