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.yunxin.data.ImDataRes;
import com.ruoyi.yunxin.data.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 com.ruoyi.yunxin.enums.CallNoticeEnum;
import com.ruoyi.yunxin.service.YunxinWsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 被叫方拒绝通话
 */
@Component("refuse")
public class RefuseMessageHandler extends AbstractMessageHandle implements IMessageHandler {
    @Autowired
    private RoomService roomService;
    @Autowired
    private UserCallService userCallService;
    @Autowired
    private YunxinWsService yunxinWsService;

    @Override
    public void processOn(Room room, FdCtxData fdCtxData, JSONObject map) {
        if(!fdCtxData.isReceiver() || !RoomStatusEnums.STATUS_RECEIVER_CONNECT.getCode().equals(room.getStatus())){
            return;
        }
        boolean b = roomService.hangUp(room.getRoomId());
        if(!b){
            return;
        }
        sendToCurrent(fdCtxData, WsRMsgGen.hangup("已拒绝",room.getRoomId(), HangUpEnums.REFUSE.getCode()));
        sendToTar(fdCtxData,WsRMsgGen.hangup("对方已拒绝",room.getRoomId(), HangUpEnums.REFUSE.getCode()));
        roomService.closeAllFd(room.getRoomId());

        //发送IM通知
        Long receiverId = room.getReceiverId();
        Long callerId = room.getCallId();
        yunxinWsService.sendToCallNotifyAsync(callerId,receiverId, CallNoticeEnum.REFUSE,0L);

        // 更新房间状态
        userCallService.update(Wrappers.lambdaUpdate(UserCall.class)
                .eq(UserCall::getId,room.getRoomId())
                .set(UserCall::getStatus,RoomStatusEnums.STATUS_REFUSE.getCode()));
    }


}
