<?php


namespace app\services\opening;

use app\models\bet\Bet;
use app\models\process\Boot;
use app\models\process\NumberTab;
use app\models\user\User;
use app\services\connect\InitTableService;
use freedom\utils\RouletteUtil;
use freedom\utils\SocketSession;
use think\swoole\Websocket;

/**
 * TODO Baccarat开结果服务
 * Class OpeningRouletteService
 * @package app\services\opening
 */
class OpeningRouletteService
{

    /**
     * TODO Baccarat开结果处理
     * @param array $event
     * @param array $tableInfo
     * @param Websocket $ws
     * @return void
     */
    public static function openingRoulette(array $event, array $tableInfo, Websocket $ws){
        //判断结果并推送结果
        $res = self::doOpening($event,$tableInfo);
        if ($res['status'] == false){
            $ws->emit('openingRoulette',['status' => false,'table_id' => $tableInfo['id'], 'msg' => $res['msg']]);
            return;
        }
        list($result,$resultParse,$lastNumberTabInfo,$newNumberTabInfo) = $res['data'];
        $round = array(
            'result' => $result,
            'result_parse' => $resultParse,
            'boot_id' => $newNumberTabInfo['boot_id'],
            'boot_num' => $newNumberTabInfo['boot_num'],
            'number_tab_id' => $newNumberTabInfo['id'],
            'previous_number_tab_id' => $lastNumberTabInfo['id'],
            'number_tab_number' => $newNumberTabInfo['number'],
            'number_tab_status' => InitTableService::numberTabStatus($newNumberTabInfo)
        );
        $ws->emit('openingRoulette',['status' => true, 'table_id' => $tableInfo['id'], 'round' => $round]);
        $ws->to(SocketSession::HOUSE_NAME)->emit('openingRouletteResult',['status' => true, 'table_id' => $tableInfo['id'], 'round' => $round]);
        //处理注单
        self::doBet($ws,$tableInfo,$lastNumberTabInfo,$result,$resultParse);
    }

    /**
     * TODO 判断结果
     * @param array $event
     * @param array $tableInfo
     * @return array
     */
    public static function doOpening(array $event, array $tableInfo): array
    {
        if (!isset($event['number_tab_id'])) return ['status' => false, 'msg' => 'opening_fail_2'];
        $numberTabId = intval($event['number_tab_id']);
        $numberTabInfo = NumberTab::getByTableIdOrderByIdDesc($tableInfo);
        if (!$numberTabInfo || $numberTabId != $numberTabInfo['id']) return ['status' => false, 'msg' => 'opening_fail_2'];
        if ($numberTabInfo['bet_status'] != 2) return ['status' => false, 'msg' => 'opening_fail_4'];
        $result = intval($event['result']);
        if ($result < 0 || $result > 36) return ['status' => false, 'msg' => 'opening_fail'];
        $boot = Boot::where(['id' => $numberTabInfo['boot_id']])->find();
        $afterCountArray = RouletteUtil::parseCount($result);
        $beforeCountString = $boot['roulette_count'];
        $beforeCountArray = string_to_array($beforeCountString);
        $countArray = RouletteUtil::countInc($beforeCountArray, $afterCountArray);
        $countString = array_to_string($countArray);
        $numberTabInfo['roulette_count'] = $countString;
        $resultParse = RouletteUtil::parseResult($result);
        $numberTabUpdate = ['roulette_result' => $result, 'end_time' => time(), 'bet_status' => 3];
        $newNumberTabInfo = NumberTab::next($numberTabInfo,$numberTabUpdate,$tableInfo);
        if ($newNumberTabInfo){
            $lastNumberTabInfo = array_merge($numberTabInfo,$numberTabUpdate);
            return ['status' => true, 'data' => [$result,$resultParse,$lastNumberTabInfo,$newNumberTabInfo]];
        }else{
            return ['status' => false, 'msg' => 'opening_fail'];
        }
    }

    /**
     * TODO Bet处理
     * @param Websocket $ws  桌子信息
     * @param array $tableInfo  桌子信息
     * @param array $numberTabInfo  开结果的当前局信息
     * @return void
     */
    public static function doBet(Websocket $ws, array $tableInfo, array $numberTabInfo, int $result, array $resultParse){
        $betArray = Bet::getByNumberTabIdValid($numberTabInfo['id']);
        foreach ($betArray AS $v){
            $userInfo = User::get(intval($v['user_id']));
            if (!$userInfo) continue;
            if (empty($v['roulette_european_amount']) && empty($v['roulette_french_amount'])) continue;
            $priceArray = string_to_array($userInfo['price_roulette']);

            $amount = 0;
            $winMoney = 0;
            $roulette_amount = $v['roulette_european_amount'] ? $v['roulette_european_amount'] : $v['roulette_french_amount'];
            $amountArray = string_to_array($roulette_amount);
            foreach ($amountArray as $key => $value){
                $amount += intval($value);

                if(in_array($key, ['zeroGame','neighborsOfZero','orphans','theThird'])){
                    if($key == 'zeroGame'){
                        $split_value = $value / 4;
                        if($result == 26){
                            $winMoney = round($split_value * (1 + $priceArray['straight']),2) + $winMoney;
                        }
                        if(in_array($result,[0,3,12,15,32,35])){
                            $winMoney = round($split_value * (1 + $priceArray['split']),2) + $winMoney;
                        }
                    }
                    if($key == 'neighborsOfZero'){
                        $split_value = $value / 9;
                        if(in_array($result,[4,7,12,15,18,21,19,22,32,35])){
                            $winMoney = round($split_value * (1 + $priceArray['split']),2) + $winMoney;
                        }
                        if(in_array($result,[0,2,3])){
                            $winMoney = round($split_value * 2 * (1 + $priceArray['triple']),2) + $winMoney;
                        }
                        if(in_array($result,[25,26,28,29])){
                            $winMoney = round($split_value * 2 * (1 + $priceArray['corner']),2) + $winMoney;
                        }
                    }

                    if($key == 'orphans'){
                        $split_value = $value / 5;
                        if($result == 1){
                            $winMoney = round($split_value * (1 + $priceArray['straight']),2) + $winMoney;
                        }
                        if(in_array($result,[6,9,14,17,20,31,34])){
                            if($result == 17){
                                $winMoney = round($split_value * 2 * (1 + $priceArray['split']),2) + $winMoney;
                            }else{
                                $winMoney = round($split_value * (1 + $priceArray['split']),2) + $winMoney;
                            }
                        }
                    }
                    if($key == 'theThird'){
                        $split_value = $value / 6;
                        if(in_array($result,[5,8,10,11,13,16,23,24,27,30,33,36])){
                            $winMoney = round($split_value * (1 + $priceArray['split']),2) + $winMoney;
                        }
                    }
                } else {
                    if(in_array($key,['low','high','odd','even','red','black','column_1','column_2','column_3','dozen_1','dozen_2','dozen_3'])){
                        if (in_array($key, $resultParse)){
                            if(in_array($key,['low','high','odd','even','red','black'])){
                                $winMoney = round($value * (1 + $priceArray[$key]),2) + $winMoney;
                            }else{
                                $keyArray = explode("_", $key);
                                $winMoney = round($value * (1 + $priceArray[$keyArray[0]]),2) + $winMoney;
                            }

                        }
                    }else{
                        $keyArray = explode("_", $key);
                        if($keyArray[0] == 'straight') {
                            if ($keyArray[1] == $result) {
                                $winMoney = round($value * (1 + $priceArray[$keyArray[0]]),2) + $winMoney;
                            }
                        }else{
                            $betZoneArr = explode("-", $keyArray[1]);
                            if(in_array($result,$betZoneArr)){
                                $winMoney = round($value * (1 + $priceArray[$keyArray[0]]),2) + $winMoney;
                            }
                        }
                    }
                }

            }
            $winTotal = $winMoney - $amount;
            /**
             * Model处理
             * @param array $tableInfo 桌子信息
             * @param array $betInfo bet信息
             * @param array $userInfo bet用户信息
             * @param array $numberTabInfo 局信息
             * @param float $amount 下注总数
             * @param float $winTotal 赢金额
             * @param float $ximaliang 洗码量
             */
            $res = Bet::openingBet($tableInfo,$v,$userInfo,$numberTabInfo,$amount,$winTotal,0);
            if ($res['status']){
                $tableUser = app('swoole.table.user');
                $userSession = $tableUser->get((string) $v['user_id']);
                if ($userSession && is_array($userSession)){
                    $ws->setSender(0)->to($userSession['fd'])->emit('opening',['status' => true, 'table_id' => $tableInfo['id'], 'round' => ['money' => $res['money'], 'win_total' => $winTotal, 'previous_number_tab_id' => $v['number_tab_id']]]);
                }
            }
        }
    }
}