<?php


namespace app\services\opening;

use app\models\bet\Bet;
use app\models\process\NumberTab;
use app\models\user\User;
use app\services\connect\InitTableService;
use app\services\waybill\WaybillRemindService;
use freedom\utils\CardPosition;
use freedom\utils\RedisUtil;
use freedom\utils\SocketSession;
use think\swoole\Websocket;

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

    /**
     * TODO Baccarat开结果处理
     * @param array $event
     * @param array $tableInfo
     * @param Websocket $ws
     * @return void
     */
    public static function openingBaccarat(array $event, array $tableInfo, Websocket $ws){
        //判断结果并推送结果
        $res = self::doOpening($event,$tableInfo);
        if ($res['status'] == false){
            $ws->emit('openingBaccarat',['status' => false, 'msg' => $res['msg']]);
            return;
        }
        list($opening,$pair,$luck_six,$big_small,$banker,$player,$lastNumberTabInfo,$newNumberTabInfo) = $res['data'];
        $round = array(
            'opening' => $opening,
            'pair' => $pair,
            'luck_six' => $luck_six,
            'big_small' => $big_small,
            'banker' => $banker,
            'player' => $player,
            '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('openingBaccarat',['status' => true, 'table_id' => $tableInfo['id'], 'round' => $round]);
        $ws->to(SocketSession::HOUSE_NAME)->emit('openingBaccaratResult',['status' => true, 'table_id' => $tableInfo['id'], 'round' => $round]);
        //处理注单
        self::doBet($ws,$tableInfo,$lastNumberTabInfo);
        //处理好路
        WaybillRemindService::parseWaybillRemind($tableInfo['game_id'], $tableInfo['id'], $tableInfo['table_name'], $newNumberTabInfo['boot_id']);
    }

    /**
     * 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'];
        $luck_six = 0;
        $big_small = 0;
        $banker = null;
        $player = null;
        if ($tableInfo['is_scavenging'] == 1){
            $cardInfo = RedisUtil::getCardPosition($numberTabId);
            if (!isset($cardInfo['banker_1']) || !isset($cardInfo['banker_2']) || !isset($cardInfo['player_1']) || !isset($cardInfo['player_2'])){
                return ['status' => false, 'msg' => 'opening_fail_6'];
            }
            if (!isset($cardInfo['player_3'])) $cardInfo['player_3'] = 0;
            if (!isset($cardInfo['banker_3'])) $cardInfo['banker_3'] = 0;
            $checkOpenScan = CardPosition::checkOpenScan($cardInfo);
            if (!$checkOpenScan) return ['status' => false, 'msg' => 'opening_fail_6'];
            $banker_1 = CardPosition::interchangeCard($cardInfo['banker_1']);
            $banker_2 = CardPosition::interchangeCard($cardInfo['banker_2']);
            $banker_3 = CardPosition::interchangeCard($cardInfo['banker_3']);
            $player_1 = CardPosition::interchangeCard($cardInfo['player_1']);
            $player_2 = CardPosition::interchangeCard($cardInfo['player_2']);
            $player_3 = CardPosition::interchangeCard($cardInfo['player_3']);
            $banker = CardPosition::interchangeNumber($banker_1) + CardPosition::interchangeNumber($banker_2) + CardPosition::interchangeNumber($banker_3);
            $player = CardPosition::interchangeNumber($player_1) + CardPosition::interchangeNumber($player_2) + CardPosition::interchangeNumber($player_3);
            // 求余
            if($banker >= 10){
                $banker = $banker % 10;
            }
            if($player >= 10){
                $player = $player % 10;
            }
            // 判断结果
            if($banker > $player){
                // 庄赢
                $opening = 1;
            }elseif($banker < $player){
                // 闲赢
                $opening = 2;
            }elseif($banker == $player){
                // 庄赢
                $opening = 3;
            }else{
                return ['status' => false, 'msg' => 'opening_fail_5'];
            }
            // 比较对子
            if(intval($banker_1) == intval($banker_2) && intval($player_1) == intval($player_2)){
                $pair = 3;
            }elseif(intval($banker_1) == intval($banker_2)){
                $pair = 1;
            }elseif(intval($player_1) == intval($player_2)){
                $pair = 2;
            }else{
                $pair = 0;
            }
            // 判断幸运6
            if ($opening == 1 && $banker == 6){
                if ($banker_3 > 0){
                    $luck_six = 3;
                } else {
                    $luck_six = 2;
                }
            }
            // 判断大小
            if ($banker_3 > 0 || $player_3 > 0){
                $big_small = 1;
            } else {
                $big_small = 2;
            }
        }else{
            $opening = intval($event['opening']);
            $banker_pair = intval($event['banker_pair']);
            $player_pair = intval($event['player_pair']);
            $luck_six = intval($event['luck_six']);
            //处理开盘
            if($banker_pair == 1 && $player_pair == 2){
                //庄闲对
                $pair = 3;
            }elseif($banker_pair == 1 && $player_pair != 2){
                //庄对
                $pair = 1;
            }elseif($banker_pair != 1 && $player_pair == 2){
                //和对
                $pair = 2;
            }else{
                $pair = 0;
            }
        }
        if (!in_array($opening,[1,2,3])) return ['status' => false, 'msg' => 'opening_fail_3'];
        //开盘
        $numberTabUpdate = ['result' => $opening, 'pair' => $pair, 'luck_six' => $luck_six, 'big_small' => $big_small, 'end_time' => time(), 'bet_status' => 3];
        $newNumberTabInfo = NumberTab::next($numberTabInfo,$numberTabUpdate,$tableInfo);
        if ($newNumberTabInfo){
            $lastNumberTabInfo = array_merge($numberTabInfo,$numberTabUpdate);
            return ['status' => true, 'data' => [$opening,$pair,$luck_six,$big_small,$banker,$player,$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;
            }
            $amount = $v['banker_amount'] + $v['player_amount'] + $v['tie_amount'] + $v['banker_pair_amount'] + $v['player_pair_amount'] + $v['luck_six_amount'] + $v['big_amount'] + $v['small_amount'];
            $winMoney = 0;
            // 双边洗码
            $ximaliang = 0;
            if($userInfo['type_xima'] == 1){
                $ximaliang = abs($v['banker_amount'] - $v['player_amount']);
            }
            if($numberTabInfo['result'] == 1){
                // 庄赢
                if ($v['banker_amount'] > 0){
                    if ($v['baccarat_type'] == 1){
                        if ($numberTabInfo['luck_six'] > 0){
                            $winMoney = round($v['banker_amount'] * (1 + 0.5),2) + $winMoney;
                        } else {
                            $winMoney = round($v['banker_amount'] * (1 + 1),2) + $winMoney;
                        }
                    } else {
                        $winMoney = round($v['banker_amount'] * (1 + $userInfo['price_banker']),2) + $winMoney;
                    }
                }
                // 单边洗码
                if($userInfo['type_xima'] == 2){
                    $ximaliang = $v['player_amount'];
                }
            }elseif($numberTabInfo['result'] == 2){
                // 闲赢
                if($v['player_amount'] > 0){
                    $winMoney = $v['player_amount'] * (1 + $userInfo['price_player']) + $winMoney;
                }
                // 单边洗码
                if($userInfo['type_xima'] == 2){
                    $ximaliang = $v['banker_amount'];
                }
            }elseif($numberTabInfo['result'] == 3) {
                $ximaliang = 0;
                // 和赢
                if($v['tie_amount'] > 0){
                    $winMoney = $v['tie_amount'] * (1 + $userInfo['price_tie_baccarat']) + $winMoney;
                }
                // 开 和，下注庄和闲不扣钱
                if($v['banker_amount'] > 0 && $v['player_amount'] > 0){
                    $winMoney = $v['player_amount'] + $v['banker_amount'] + $winMoney;
                }elseif($v['banker_amount'] > 0){
                    $winMoney = $v['banker_amount'] + $winMoney;
                } elseif ($v['player_amount'] > 0){
                    $winMoney = $v['player_amount'] + $winMoney;
                }
            }
            if($numberTabInfo['pair'] == 3){
                // 计算庄对下注的赢钱金额
                if ($v['banker_pair_amount'] > 0) {
                    $winMoney = $v['banker_pair_amount'] * (1 + $userInfo['price_pair']) + $winMoney;
                }
                //计算闲对下注的赢钱金额
                if ($v['player_pair_amount'] > 0) {
                    $winMoney = $v['player_pair_amount'] * (1 + $userInfo['price_pair']) + $winMoney;
                }
            }elseif($numberTabInfo['pair'] == 1){
                if ($v['banker_pair_amount'] > 0) {
                    $winMoney = $v['banker_pair_amount'] * (1 + $userInfo['price_pair']) + $winMoney;
                }
            }elseif($numberTabInfo['pair'] == 2){
                if ($v['player_pair_amount'] > 0) {
                    $winMoney = $v['player_pair_amount'] * (1 + $userInfo['price_pair']) + $winMoney;
                }
            }
            if ($numberTabInfo['luck_six'] == 2 && $v['luck_six_amount'] > 0){
                $winMoney = $v['luck_six_amount'] * (1 + $userInfo['price_luck_six_2']) + $winMoney;
            }
            if ($numberTabInfo['luck_six'] == 3 && $v['luck_six_amount'] > 0){
                $winMoney = $v['luck_six_amount'] * (1 + $userInfo['price_luck_six_3']) + $winMoney;
            }
            if ($numberTabInfo['big_small'] == 1){
                $winMoney = $v['big_amount'] * (1 + $userInfo['price_big']) + $winMoney;
            }
            if ($numberTabInfo['big_small'] == 2){
                $winMoney = $v['small_amount'] * (1 + $userInfo['price_small']) + $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,$ximaliang);
            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']]]);
                }
            }
        }
    }
}