package com.ruoyi.cai.ws.handler.message;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.cai.ws.bean.FdCtxData;
import com.ruoyi.cai.ws.bean.Room;
import com.ruoyi.cai.ws.cache.RoomDataCache;
import com.ruoyi.cai.ws.constant.HangUpEnums;
import com.ruoyi.cai.ws.dto.WsRMsgGen;
import com.ruoyi.cai.ws.handler.AbstractMessageHandle;
import com.ruoyi.cai.ws.handler.IMessageHandler;
import com.ruoyi.cai.ws.service.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 挂断处理
 */
@Component("hangup")
public class HangupMessageHandler extends AbstractMessageHandle implements IMessageHandler {
    @Autowired
    private RoomService roomService;
    @Autowired
    private RoomDataCache roomDataCache;

    @Override
    public void processOn(Room room, FdCtxData fdCtxData, JSONObject map) {
        if(room.getRoomId() == null){
            return;
        }
        // 经测试，app端挂断时，可能会把旧的房间id传上来，所以需要判断id与fd上下文的一致性
        if(!room.getRoomId().equals(fdCtxData.getRoomId())){
            return;
        }
        boolean b = roomDataCache.hangUp(room.getRoomId());
        if(!b){
            return;
        }
        // 触发结算 TODO


        Integer type = fdCtxData.isCaller() ? HangUpEnums.FROM.getCode() : HangUpEnums.TO.getCode();
        sendToCurrent(fdCtxData,WsRMsgGen.hangup("您已挂断",room.getRoomId(), type));
        sendToTar(fdCtxData,WsRMsgGen.hangup("对方已挂断",room.getRoomId(), type));
        roomService.closeAllFd(room.getRoomId());
    }


}
