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.trd.ImDataRes;
import com.ruoyi.cai.trd.ImMsgGen;
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.constant.RoomStatusEnums;
import com.ruoyi.cai.ws.service.RoomService;
import com.ruoyi.cai.ws.service.SettleService;
import com.ruoyi.yunxin.Yunxin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
@Slf4j
public class CheckTimeOutJob {
    @Autowired
    private OnlineDataCache onlineDataCache;
    @Autowired
    private RoomService roomService;
    @Autowired
    private UserCallService userCallService;
    @Autowired
    private SettleService settleService;
    @Autowired
    private Yunxin yunxin;

    /**
     * 检查房间是不是三分钟没有接听， 需要自动挂断掉
     */
//    @Scheduled(fixedDelay = 60,timeUnit = TimeUnit.SECONDS)
    public void run(){
        Set<String> roomIdStr = onlineDataCache.getAll();
        for (String roomIdS : roomIdStr) {
            Long roomId = Long.valueOf(roomIdS);
            this.deal(roomId);
        }
    }

    public void deal(Long roomId){
        log.info("开始执行房间超时检测，是否一直不接 roomId={}",roomId);
        Room room = roomService.load(roomId);
        if(room == null){
            return;
        }
        if(!RoomStatusEnums.STATUS_CALLER_CONNECT.getCode().equals(room.getStatus())
                && !RoomStatusEnums.STATUS_RECEIVER_CONNECT.getCode().equals(room.getStatus())){
            return;
        }
        UserData callUserData = room.getCallUserData();
        UserData receiverUserData = room.getReceiverUserData();
        // 检测是不是3分钟没有接听
        Long connectTimeCaller = callUserData.getConnectTime();
        Long connectTimeReceiver = receiverUserData.getConnectTime();
        boolean timeOut = false;
        if(connectTimeCaller != null && DateUtil.currentSeconds() - connectTimeCaller > 180){
            timeOut = true;
        }else if(connectTimeReceiver != null && DateUtil.currentSeconds() - connectTimeReceiver > 180){
            timeOut = true;
        }
        if(timeOut){
            if(roomService.hangUp(roomId)){
                userCallService.update(Wrappers.lambdaUpdate(UserCall.class)
                        .eq(UserCall::getId,roomId)
                        .set(UserCall::getStatus, RoomStatusEnums.STATUS_TIMEOUT_CANCEL.getCode()));
                // TODO 需要放开主播的接听状态
                roomService.closeAllFd(roomId);
                ImDataRes imDataRes = ImMsgGen.callNotice(3, callUserData.getId(), receiverUserData.getId(), 0);
                yunxin.sendToSync(receiverUserData.getId(),callUserData.getId(),imDataRes);
            }
        }
    }
}
