<?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\SocketSession;
use freedom\utils\ToningUtil;
use think\swoole\Websocket;

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

    /**
     * TODO Baccarat开结果处理
     * @param array $event
     * @param array $tableInfo
     * @param Websocket $ws
     * @return void
     */
    public static function openingToning(array $event, array $tableInfo, Websocket $ws){
        //判断结果并推送结果
        $res = self::doOpening($event,$tableInfo);
        if ($res['status'] == false){
            $ws->emit('openingToning',['status' => false, 'msg' => $res['msg']]);
            return;
        }
        list($result,$lastNumberTabInfo,$newNumberTabInfo) = $res['data'];
        $round = array(
            'result' => $result,
            '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('openingToning',['status' => true, 'table_id' => $tableInfo['id'], 'round' => $round]);
        $ws->to(SocketSession::HOUSE_NAME)->emit('openingToningResult',['status' => true, 'table_id' => $tableInfo['id'], 'round' => $round]);
        //处理注单
        self::doBet($ws,$tableInfo,$lastNumberTabInfo);
    }

    /**
     * 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 (!in_array($result,[0,1,2,3,4])) return ['status' => false, 'msg' => 'opening_fail_3'];
        // 统计结果数目
        $boot = Boot::where(['id' => $numberTabInfo['boot_id']])->find();
        $toningCountArray = ToningUtil::countInc($result, $boot['toning_count']);
        $toningCountString = array_to_string($toningCountArray);
        $numberTabInfo['toning_count'] = $toningCountString;
        $numberTabUpdate = ['toning_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,$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){
        $betArray = Bet::getByNumberTabIdValid($numberTabInfo['id']);
        foreach ($betArray AS $v){
            $userInfo = User::get(intval($v['user_id']));
            if (!$userInfo){
                continue;
            }
            if (empty($v['toning_amount'])){
                continue;
            }
            $toningAmountArray = explode(",", $v['toning_amount']);
            $amount = 0;
            $winMoney = 0;
            foreach ($toningAmountArray as $value){
                $itemArray = explode(":", $value);
                $area = $itemArray[0];
                $betAmount = intval($itemArray[1]);
                $amount += $itemArray[1];
                if (($area == 'toning_zero' && $numberTabInfo['toning_result'] == 0) || ($area == 'toning_four' && $numberTabInfo['toning_result'] == 4)){
                    $winMoney = round($betAmount * (1 + $userInfo['price_toning_0']),2) + $winMoney;
                }
                if (($area == 'toning_one' && $numberTabInfo['toning_result'] == 1) || ($area == 'toning_three' && $numberTabInfo['toning_result'] == 3)){
                    $winMoney = round($betAmount * (1 + $userInfo['price_toning_1']),2) + $winMoney;
                }
                if ($area == 'toning_big' && in_array($numberTabInfo['toning_result'], [3,4])){
                    $winMoney = round($betAmount * (1 + $userInfo['price_toning']),2) + $winMoney;
                }
                if ($area == 'toning_small' && in_array($numberTabInfo['toning_result'], [0,1])){
                    $winMoney = round($betAmount * (1 + $userInfo['price_toning']),2) + $winMoney;
                }
                if ($area == 'toning_singular' && in_array($numberTabInfo['toning_result'], [1,3])){
                    $winMoney = round($betAmount * (1 + $userInfo['price_toning']),2) + $winMoney;
                }
                if ($area == 'toning_plural' && in_array($numberTabInfo['toning_result'], [0,2,4])){
                    $winMoney = round($betAmount * (1 + $userInfo['price_toning']),2) + $winMoney;
                }
                if (($area == 'toning_small' && $numberTabInfo['toning_result'] == 2) || ($area == 'toning_big' && $numberTabInfo['toning_result'] == 2)){
                    $winMoney = round($betAmount + $winMoney,2);
                }
            }
            $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'] == true){
                $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']]]);
                }
            }
        }
    }
}