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

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

    /**
     * TODO Baccarat开结果处理
     * @param array $event
     * @param array $tableInfo
     * @param Websocket $ws
     * @return void
     */
    public static function openingDice(array $event, array $tableInfo, Websocket $ws){
        //判断结果并推送结果
        $res = self::doOpening($event,$tableInfo);
        if ($res['status'] == false){
            $ws->emit('openingDice',['status' => false, 'msg' => $res['msg']]);
            return;
        }
        list($resultArray,$resultParse,$lastNumberTabInfo,$newNumberTabInfo) = $res['data'];
        $round = array(
            'result' => $resultArray,
            '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('openingDice',['status' => true, 'table_id' => $tableInfo['id'], 'round' => $round]);
        $ws->to(SocketSession::HOUSE_NAME)->emit('openingDiceResult',['status' => true, 'table_id' => $tableInfo['id'], 'round' => $round]);
        //处理注单
        self::doBet($ws,$tableInfo,$lastNumberTabInfo,$resultArray,$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'];
        $resultArray = explode(',', $event['result']);
        $resultTrue = true;
        foreach ($resultArray as $v){
            if (!in_array(intval($v), [1,2,3,4,5,6])){
                $resultTrue = false;
                break;
            }
        }
        if ($resultTrue == false || count($resultArray) != 3) return ['status' => false, 'msg' => 'opening_fail_3'];
        $boot = Boot::where(['id' => $numberTabInfo['boot_id']])->find();
        $afterCountArray = DiceUtil::parseCount($resultArray);
        $beforeCountString = $boot['dice_count'];
        $beforeCountArray = string_to_array($beforeCountString);
        $countArray = DiceUtil::countInc($beforeCountArray, $afterCountArray);
        $countString = array_to_string($countArray);
        $numberTabInfo['dice_count'] = $countString;
        $resultParse = DiceUtil::parseResult($resultArray);
        $numberTabUpdate = ['dice_result' => $event['result'], 'end_time' => time(), 'bet_status' => 3];
        $newNumberTabInfo = NumberTab::next($numberTabInfo,$numberTabUpdate,$tableInfo);
        if ($newNumberTabInfo){
            $lastNumberTabInfo = array_merge($numberTabInfo,$numberTabUpdate);
            return ['status' => true, 'data' => [$resultArray,$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, array $resultArray, array $resultParse){
        $betArray = Bet::getByNumberTabIdValid($numberTabInfo['id']);
        foreach ($betArray AS $v){
            $userInfo = User::get(intval($v['user_id']));
            if (!$userInfo) continue;
            if (empty($v['dice_amount'])) continue;
            $priceArray = string_to_array($userInfo['price_dice']);
            $amountArray = string_to_array($v['dice_amount']);
            $amount = 0;
            $winMoney = 0;
            foreach ($amountArray as $key => $value){
                $amount += intval($value);
                if (in_array($key, ['living_1','living_2','living_3','living_4','living_5','living_6'])){
                    $keyArray = explode("_", $key);
                    $count = DiceUtil::getLivingCount($resultArray, intval($keyArray[1]));
                    if ($count == 1){
                        $winMoney = round($value * (1 + $priceArray['once']),2) + $winMoney;
                    } elseif ($count == 2){
                        $winMoney = round($value * (1 + $priceArray['double']),2) + $winMoney;
                    } elseif ($count == 3){
                        $winMoney = round($value * (1 + $priceArray['triple']),2) + $winMoney;
                    }
                } else {
                    if (in_array($key, $resultParse)){
                        $winMoney = round($value * (1 + $priceArray[$key]),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']]]);
                }
            }
        }
    }
}