<?php

namespace app\services\bet;

use app\models\bet\Bet;
use freedom\utils\RouletteUtil;
use freedom\utils\SocketSession;

/**
 * TODO ToBetRouletteService
 * Class ToBetRouletteService
 * @package app\services\bet
 */

class ToBetRouletteService{

    /**
     * TODO 处理轮盘下注
     * @param array $event
     * @param array $tableInfo
     * @return void
     */
    public static function toBetRoulette(array $event, array $tableInfo){
        $ws = app('\think\swoole\WebSocket');
        $fd = $ws->getSender();
        $data = array();
        $event_amount = $event['amount'];
        $fieldName = 'roulette_'.$event['roulette_type'].'_amount';
        foreach ($event_amount as $k => $v){
            if (intval($v) > 0){
                $data[$k] = intval($v);
            }
        }
        $seat_num = isset($event['seat_num']) && intval($event['seat_num']) > 0 ? intval($event['seat_num']) : 0;

        $time = time();
        $toBetCheck = ToBetCommonService::toBetCheck($tableInfo,$event,$data);
        if ($toBetCheck['status'] == false){
            $ws->emit('toBet',['status' => false, 'table_id' => $tableInfo['id'], 'msg' => $toBetCheck['msg']]);
            SocketSession::resetRepeat($fd,'user','isToBet');
            return;
        }
        $numberTabInfo = $toBetCheck['numberTabInfo'];
        $userInfo = $toBetCheck['userInfo'];
        $amount = array_sum($data);
        $prevBetInfo = Bet::getPrevBetInfo($userInfo['id'],$numberTabInfo['id']);

        if($prevBetInfo){
            $beforeAmount = string_to_array($prevBetInfo[$fieldName]);
            $betTotalAmount = RouletteUtil::amountInc($beforeAmount, $data);
        }else{
            $betTotalAmount = $data;
        }
        $res = Bet::toBet($tableInfo,$userInfo,$numberTabInfo,$prevBetInfo,$data,$seat_num,$betTotalAmount,$time,0,$fieldName);
        $numberTabAmount = string_to_array($numberTabInfo[$fieldName]);
        if($res){
            $ws->emit('toBet',['status' => true, 'table_id' => $tableInfo['id'], 'bet_amount_msg' => [$fieldName => $betTotalAmount], 'money' => ($userInfo['money'] - $amount),'seat_num' => $seat_num, 'msg' => 'to_bet_success']);
            $totalAmountArray = RouletteUtil::amountInc($numberTabAmount, $data);
            $round = [
                'amount_total' => $totalAmountArray,
                'amount_item' => $data
            ];
            $ws->to(SocketSession::HOUSE_NAME)->emit('allBetAmount',['status' => true, 'table_id' => $tableInfo['id'], 'round' => $round]);
        }else{
            $ws->emit('toBet',['status' => false, 'table_id' => $tableInfo['id'], 'msg' => 'to_bet_fail']);
        }
        SocketSession::resetRepeat($fd,'user','isToBet');
    }

}
