package com.ruoyi.cai.ws.job;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.cai.domain.UserCall;
import com.ruoyi.cai.service.UserCallService;
import com.ruoyi.cai.ws.bean.Room;
import com.ruoyi.cai.ws.bean.UserData;
import com.ruoyi.cai.ws.cache.OnlineDataCache;
import com.ruoyi.cai.ws.cache.RoomCtxCache;
import com.ruoyi.cai.ws.constant.HangUpEnums;
import com.ruoyi.cai.ws.constant.RoomStatusEnums;
import com.ruoyi.cai.ws.dto.WsR;
import com.ruoyi.cai.ws.dto.WsRMsgGen;
import com.ruoyi.cai.ws.service.RoomService;
import com.ruoyi.cai.ws.service.SettleService;
import com.ruoyi.cai.ws.util.RoomWebSocketUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class HeartbeatJob {

    @Autowired
    private OnlineDataCache onlineDataCache;
    @Autowired
    private RoomService roomService;
    @Autowired
    private UserCallService userCallService;
    @Autowired
    private SettleService settleService;
    @Autowired
    private RoomCtxCache roomCtxCache;


    /**
     * 30秒执行一次 心跳只处理接听后的心跳
     */
    @Scheduled(fixedDelay = 30,timeUnit = TimeUnit.SECONDS)
    public void run(){
        Set<String> all = onlineDataCache.getAll();
        for (String roomIdS : all) {
            try {
                Long roomId = Long.valueOf(roomIdS);
                Room room = roomService.load(roomId);
                if(room == null){
                    return;
                }
                if(!room.isCanCall()){
                    return;
                }
                UserData callUserData = room.getCallUserData();
                UserData receiverUserData = room.getReceiverUserData();
                boolean timeOut = false;
                WsR hangup = null;
                if(isHeartTimeout(callUserData)){
                    timeOut = true;
                    hangup = WsRMsgGen.hangup("呼叫方连接中断", roomId, HangUpEnums.FROM.getCode());
                }else if(isHeartTimeout(receiverUserData)){
                    timeOut = true;
                    hangup = WsRMsgGen.hangup("接听方连接中断", roomId, HangUpEnums.TO.getCode());
                }
                if(timeOut){
                    if(roomService.hangUp(roomId)){
                        userCallService.update(Wrappers.lambdaUpdate(UserCall.class)
                                .eq(UserCall::getId,roomId)
                                .set(UserCall::getStatus, RoomStatusEnums.STATUS_TIMEOUT_CANCEL.getCode()));
                        settleService.processOn(roomId);
                    }
                    List<String> keys = roomCtxCache.getSessionKeysByRoomId(roomId);
                    RoomWebSocketUtil.sendSendMessage(keys,  hangup);
                    roomService.closeAllFd(roomId);
                }
            }catch (Exception e){
                log.error("定时心跳检测失败！",e);
            }

        }
    }

    /**
     * 是否心跳超时
     * @param userData
     * @return
     */
    private boolean isHeartTimeout(UserData userData){
        if(userData.getConnectTime() == null){
            return false;
        }
        if(DateUtil.currentSeconds() - userData.getHeartTime() < 120){
            return false;
        }
        return true;
    }
}
