<?php
namespace app\services\bet;

use app\models\bet\Bet;
use app\models\process\NumberTab;
use app\models\user\User;
use freedom\utils\SocketSession;

/**
 * TODO ToSeatService
 * Class ToSeatService
 * @package app\services\bet
 */
class ToLeaveSeatService
{
    /**
     * TODO 处理toSeat
     * @param array $event
     * @param array $tableInfo
     * @return void
     */
    public static function toLeaveSeat(array $event, array $tableInfo){
        $ws = app('\think\swoole\WebSocket');
        $fd = $ws->getSender();
        $numberTabId = isset($event['number_tab_id']) && intval($event['number_tab_id']) > 0 ? intval($event['number_tab_id']) : 0;
        $userId = isset($event['user_id']) && intval($event['user_id']) > 0 ? intval($event['user_id']) : 0;
        $numberTabInfo = NumberTab::getByTableIdOrderByIdDesc($tableInfo);

        /** 验证是否和当前铺同一铺 */
        if ($numberTabInfo['id'] != $numberTabId){
            $ws->emit('toLeaveSeat',['status' => false, 'table_id' => $tableInfo['id'], 'msg' => 'to_leave_seat_fail_1']);
            SocketSession::resetRepeat($fd,'user','isToLeaveSeat');
            return;
        }

        $userInfo = User::get(['id' => $userId, 'status' => 1, 'is_delete' => 0]);
        /** 验证会员有效 */
        if (!$userInfo || $userInfo['bet_type'] != 2){
            $ws->emit('toLeaveSeat',['status' => false, 'table_id' => $tableInfo['id'], 'msg' => 'to_leave_seat_fail_2']);
            SocketSession::resetRepeat($fd,'user','isToLeaveSeat');
            return;
        }

        /** 验证本局是否下注 */
        $prevBetInfo = Bet::getPrevBetInfo($userInfo['id'],$numberTabInfo['id']);
        if($prevBetInfo){
            $ws->emit('toLeaveSeat',['status' => false, 'table_id' => $tableInfo['id'], 'msg' => 'to_leave_seat_fail_3']);
            SocketSession::resetRepeat($fd,'user','isToLeaveSeat');
            return;
        }

        $res = Bet::toLeaveSeat($userInfo,$numberTabInfo);
        if ($res){
            $numberTabInfo = NumberTab::getByTableIdOrderByIdDesc($tableInfo);
            $table_seat_info = json_decode($numberTabInfo['seat_json'],true);
            $leaveMsg = ['user_id' => $userInfo['id'], 'manager_id' => $userInfo['manager_id']];
            $ws->to(SocketSession::HOUSE_NAME)->emit('toLeaveSeat',['status' => true, 'table_id' => $tableInfo['id'],'leaveMsg' => $leaveMsg, 'table_seat_info' => $table_seat_info[$userInfo['manager_id']], 'msg' => 'to_leave_seat_success']);
        }else{
            $ws->emit('toLeaveSeat',['status' => false, 'table_id' => $tableInfo['id'], 'msg' => 'to_leave_seat_fail']);
        }
        SocketSession::resetRepeat($fd,'user','isToLeaveSeat');
    }

}