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

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.cai.domain.UserCall;
import com.ruoyi.cai.service.UserCallService;
import com.ruoyi.cai.trd.ImDataRes;
import com.ruoyi.cai.trd.ImMsgGen;
import com.ruoyi.yunxin.Yunxin;
import com.ruoyi.cai.ws.bean.FdCtxData;
import com.ruoyi.cai.ws.bean.Room;
import com.ruoyi.cai.ws.constant.HangUpEnums;
import com.ruoyi.cai.ws.constant.RoomStatusEnums;
import com.ruoyi.cai.ws.handler.IMessageHandler;
import com.ruoyi.cai.ws.service.RoomService;
import com.ruoyi.cai.ws.dto.WsRMsgGen;
import com.ruoyi.cai.ws.handler.AbstractMessageHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 主叫方取消通话
 */
@Component("cancel")
public class CancelMessageHandler extends AbstractMessageHandle implements IMessageHandler {
    @Autowired
    private UserCallService userCallService;
    @Autowired
    private RoomService roomService;
    @Autowired
    private Yunxin yunxin;
    @Override
    public void processOn(Room room, FdCtxData fdCtxData, JSONObject map) {
        if(!fdCtxData.isCaller()){
            return;
        }
        if(!RoomStatusEnums.STATUS_CALLER_CONNECT.getCode().equals(room.getStatus())
            && !RoomStatusEnums.STATUS_RECEIVER_CONNECT.getCode().equals(room.getStatus())){
            return;
        }
        Long roomId = room.getRoomId();
        sendToCurrent(fdCtxData,WsRMsgGen.hangup("通话已取消",roomId, HangUpEnums.CANCEL.getCode()));
        sendToReceiver(roomId,WsRMsgGen.hangup("对方已取消",roomId, HangUpEnums.CANCEL.getCode()));
        roomService.closeAllFd(roomId);
        // IM
        Long receiverId = room.getReceiverUserData().getId();
        Long callerId = room.getCallUserData().getId();
        ImDataRes imDataRes = ImMsgGen.callNotice(1, callerId, receiverId, 0);
        yunxin.sendTo(receiverId,callerId,imDataRes);
        // 更新房间状态
        userCallService.update(Wrappers.lambdaUpdate(UserCall.class)
                .eq(UserCall::getId,roomId)
                .set(UserCall::getStatus,RoomStatusEnums.STATUS_CALLER_CANCEL.getCode()));
    }
}
