<?php


namespace app\services\process;


use freedom\utils\RedisUtil;
use freedom\utils\SocketSession;
use think\facade\Cache;

/**
 * TODO 倒计时服务
 * Class CountdownService
 * @package app\services\process
 */
class CountdownService
{
    /**
     * TODO 倒计时发送
     * @param int $numberTabId
     * @param array $tableInfo
     * @param array $numberTabInfo
     * @return void
     */
    public static function countdown(int $numberTabId, array $tableInfo, array $numberTabInfo){
        $ws = app('\think\swoole\WebSocket');
        //处理倒计时
        $waitTime = intval($tableInfo['wait_time']);
        //将倒计时用作是redis的过期时间
        RedisUtil::save('countdown_'.$numberTabInfo['id'],$waitTime,$waitTime);
        while($waitTime >= 0){
            $countdown = Cache::store('redis')->get('countdown_'.$numberTabInfo['id']);
            if ($countdown){
                $ws->to(SocketSession::HOUSE_NAME)->emit('startBetCountDown',['status' => true, 'table_id' => $tableInfo['id'], 'count_down' => $waitTime]);
                $waitTime--;
                sleep(1);
                if ($waitTime == 0){
                    //关闭倒计时
                    EndBetService::endBet($numberTabId,$tableInfo);
                }
            }else{
                break;
            }
        }
    }

    /**
     * TODO 倒计时发送(Rob)
     * @param int $numberTabId
     * @param array $tableInfo
     * @param array $numberTabInfo
     * @return void
     */
    public static function countdownRob(int $numberTabId, array $tableInfo, array $numberTabInfo){
        $ws = app('\think\swoole\WebSocket');
        //处理倒计时
        $waitTime = intval($tableInfo['rob_time']);
        //将倒计时用作是redis的过期时间
        RedisUtil::save('countdownRob_'.$numberTabInfo['id'],$waitTime,$waitTime);
        while($waitTime >= 0){
            $countdown = Cache::store('redis')->get('countdownRob_'.$numberTabInfo['id']);
            if ($countdown){
                $ws->to(SocketSession::HOUSE_NAME)->emit('startRobCountDown',['status' => true, 'table_id' => $tableInfo['id'], 'count_down' => $waitTime]);
                $waitTime--;
                sleep(1);
                if ($waitTime == 0){
                    //关闭倒计时
                    EndRobService::endRob($numberTabId,$tableInfo);
                }
            }else{
                break;
            }
        }
    }
}