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.cache.RoomDataCache;
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("refuse")
public class RefuseMessageHandler extends AbstractMessageHandle implements IMessageHandler {
    @Autowired
    private RoomDataCache roomDataCache;
    @Autowired
    private RoomService roomService;
    @Autowired
    private UserCallService userCallService;
    @Autowired
    private Yunxin yunxin;
    @Override
    public void processOn(Room room, FdCtxData fdCtxData, JSONObject map) {
        if(!fdCtxData.isReceiver() || !RoomStatusEnums.STATUS_RECEIVER_CONNECT.getCode().equals(room.getStatus())){
            return;
        }
        boolean b = roomDataCache.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.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,room.getRoomId())
                .set(UserCall::getStatus,RoomStatusEnums.STATUS_REFUSE.getCode()));
    }
}
