<?php


namespace app\models\bet;


use app\models\process\NumberTab;
use app\models\user\Recharge;
use app\models\user\User;
use freedom\basic\BaseModel;
use freedom\traits\ModelTrait;
use freedom\utils\DiceUtil;
use freedom\utils\ToningUtil;
use freedom\utils\RouletteUtil;
use think\facade\Db;

/**
 * TODO 注单Model
 * Class Bet
 * @package app\models\bet
 */
class Bet extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';
    /**
     * 模型名称
     * @var string
     */
    protected $name = 'bet';

    use ModelTrait;

    /**
     * TODO 获取有效Bet
     * @param int $numberTabId
     * @return array
     */
    public static function getByNumberTabIdValid(int $numberTabId, string $field = '*'): array
    {
        $select = self::where(['number_tab_id' => $numberTabId, 'status' => 1])->field($field)->select();
        if (!empty($select)) return $select->toArray();
        else return [];
    }

    /**
     * TODO 获取抢庄Bet
     * @param int $numberTabId
     * @param int $robBankerId
     * @return array
     */
    public static function getByNumberTabIdRob(int $numberTabId, int $robBankerId): array
    {

        $find = self::where(['number_tab_id' => $numberTabId, '', 'status' => 1, 'user_id' => $robBankerId])->find();
        if ($find) return $find->toArray();
        else return [];
    }

    /**
     * TODO 获取非抢庄Bet
     * @param int $numberTabId
     * @param int $robBankerId
     * @return array
     */
    public static function getByNumberTabIdNotRob(int $numberTabId, int $robBankerId): array
    {

        $select = self::where(['number_tab_id' => $numberTabId, '', 'status' => 1])->where(['user_id','<>',$robBankerId])->select();
        if ($select) return $select->toArray();
        else return [];
    }

    /**
     * TODO 获取今日Win总数
     * @param int $userId
     * @return float
     */
    public static function getWinTotalToday(int $userId): float
    {
        $startTime = strtotime(date('Y-m-d'));
        $endTime = time();
        return self::where(['user_id' => $userId])->where('unify_time', ['between',[$startTime,$endTime]])->sum("win_total");
    }

    /**
     * TODO 获取同局的Bet
     * @param int $userId
     * @param int $numberTabId
     * @return array
     */
    public static function getPrevBetInfo(int $userId, int $numberTabId): array
    {
        $find = self::where(['user_id' => $userId, 'number_tab_id' => $numberTabId, 'status' => 1])->order('id DESC')->find();
        if ($find) return $find->toArray();
        else return [];
    }

    /**
     * TODO  抢庄 AllGame
     * @param array $userInfo
     * @param array $numberTabInfo
     * @return bool
     */
    public static function toRob(array $userInfo, array $numberTabInfo): bool
    {
        Db::startTrans();
        try {
            NumberTab::where(['id' => $numberTabInfo['id']])->update(['rob_banker_id' => $userInfo['id'], 'rob_banker_username' => $userInfo['username']]);
            $bet = [
                'agent_parent_id_path' => $userInfo['agent_parent_id_path'],
                'user_id' => $userInfo['id'],
                'username' => $userInfo['username'],
                'nickname' => $userInfo['nickname'],
                'table_id' => $numberTabInfo['table_id'],
                'boot_id' => $numberTabInfo['boot_id'],
                'boot_num' => $numberTabInfo['boot_num'],
                'number_tab_id' => $numberTabInfo['id'],
                'number' => $numberTabInfo['number'],
                'game_id' => $numberTabInfo['game_id'],
                'game_name' => $numberTabInfo['game_name'],
                'table_name' => $numberTabInfo['table_name'],
                'sumday_id' => $numberTabInfo['sumday_id'],
                'day' => $numberTabInfo['day'],
                'money_before_bet' => $userInfo['money'],
                'money_after_bet' => $userInfo['money'],
                'create_time' => time(),
            ];
            self::create($bet);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }

    /**
     * TODO  落座 AllGame
     * @param array $userInfo
     * @param array $numberTabInfo
     * @param array $tableInfo
     * @param int $seatNum
     * @return bool
     */
    public static function toSeat(array $userInfo, array $numberTabInfo, array $tableInfo,int $seatNum): bool
    {
        Db::startTrans();
        try {
            $seatArr = json_decode($numberTabInfo['seat_json'],true);
            if(empty($seatArr[$userInfo['manager_id']])){
                $seat_num = $tableInfo['seat_num'] >=4 ? $tableInfo['seat_num'] + 1 : $tableInfo['seat_num'];
                $seat_arr = [];
                for($i=1;$i<=$seat_num;$i++){
                    if($i != 4){
                        $seat_arr[$i] = 0;
                    }
                }
                $managerSeatArr = $seat_arr;
            }else{
                $managerSeatArr = $seatArr[$userInfo['manager_id']];
            }

            $nowSeatNum = array_search($userInfo['id'],$managerSeatArr);
            if($nowSeatNum){
                $managerSeatArr[$nowSeatNum] = 0;
            }
            $managerSeatArr[$seatNum] = $userInfo['id'];
            $seatArr[$userInfo['manager_id']] = $managerSeatArr;
            $newSeatJson = json_encode($seatArr);
            NumberTab::where(['id' => $numberTabInfo['id']])->update(['seat_json' => $newSeatJson]);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }
    /**
     * TODO  离座 AllGame
     * @param array $userInfo
     * @param array $numberTabInfo
     * @return bool
     */
    public static function toLeaveSeat(array $userInfo, array $numberTabInfo): bool
    {
        Db::startTrans();
        try {
            $seatArr = json_decode( $numberTabInfo['seat_json'],true);
            $managerSeatArr = $seatArr[$userInfo['manager_id']];

            $nowSeatNum = array_search($userInfo['id'],$managerSeatArr);
            if($nowSeatNum){
                $managerSeatArr[$nowSeatNum] = 0;
            }
            $seatArr[$userInfo['manager_id']] = $managerSeatArr;
            $newSeatJson = json_encode($seatArr);
            NumberTab::where(['id' => $numberTabInfo['id']])->update(['seat_json' => $newSeatJson]);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }

    /**
     * TODO toBet   AllGame
     * @param array $tableInfo      桌子信息
     * @param array $userInfo       用户信息
     * @param array $numberTabInfo  铺信息
     * @param array $prevBetInfo    上一次的注单信息
     * @param array $betAmount      当前的下注信息
     * @param int   $seat_num       座位号
     * @param array $betTotalAmount 用户当前铺总额信息
     * @param int   $time           时间
     * @param int   $baccaratType   百家乐免佣抽佣
     * @param string $rouletteType  骰子欧式法式
     * @return bool
     */
    public static function toBet(
        array $tableInfo,
        array $userInfo,
        array $numberTabInfo,
        array $prevBetInfo,
        array $betAmount,
        int $seat_num,
        array $betTotalAmount,
        int $time,
        int $baccaratType,
        string $rouletteType = ''
    ): bool {
        Db::startTrans();
        try {

            // number_tab 铺表总额更新
            if ($tableInfo['game_id'] == 1){
                NumberTab::where('id',$numberTabInfo['id'])
                    ->inc('banker_amount',$betAmount['banker_amount'])
                    ->inc('player_amount',$betAmount['player_amount'])
                    ->inc('tie_amount',$betAmount['tie_amount'])
                    ->inc('banker_pair_amount',$betAmount['banker_pair_amount'])
                    ->inc('player_pair_amount',$betAmount['player_pair_amount'])
                    ->inc('luck_six_amount',$betAmount['luck_six_amount'])
                    ->inc('big_amount',$betAmount['big_amount'])
                    ->inc('small_amount',$betAmount['small_amount'])
                    ->update();
            } elseif ($tableInfo['game_id'] == 2){
                NumberTab::where('id',$numberTabInfo['id'])
                    ->inc('banker_amount',$betAmount['banker_amount'])
                    ->inc('player_amount',$betAmount['player_amount'])
                    ->inc('tie_amount',$betAmount['tie_amount'])
                    ->update();
            } elseif ($tableInfo['game_id'] == 4 || $tableInfo['game_id'] == 5){
                NumberTab::where('id',$numberTabInfo['id'])
                    ->inc('amount_player_1',$betAmount['amount_player_1'])
                    ->inc('amount_player_1_times',$betAmount['amount_player_1_times'])
                    ->inc('withhold_player_1_times',$betAmount['withhold_player_1_times'])
                    ->inc('amount_player_1_banker',$betAmount['amount_player_1_banker'])
                    ->inc('amount_player_1_banker_times',$betAmount['amount_player_1_banker_times'])
                    ->inc('withhold_player_1_banker_times',$betAmount['withhold_player_1_banker_times'])
                    ->inc('amount_player_2',$betAmount['amount_player_2'])
                    ->inc('amount_player_2_times',$betAmount['amount_player_2_times'])
                    ->inc('withhold_player_2_times',$betAmount['withhold_player_2_times'])
                    ->inc('amount_player_2_banker',$betAmount['amount_player_2_banker'])
                    ->inc('amount_player_2_banker_times',$betAmount['amount_player_2_banker_times'])
                    ->inc('withhold_player_2_banker_times',$betAmount['withhold_player_2_banker_times'])
                    ->inc('amount_player_3',$betAmount['amount_player_3'])
                    ->inc('amount_player_3_times',$betAmount['amount_player_3_times'])
                    ->inc('withhold_player_3_times',$betAmount['withhold_player_3_times'])
                    ->inc('amount_player_3_banker',$betAmount['amount_player_3_banker'])
                    ->inc('amount_player_3_banker_times',$betAmount['amount_player_3_banker_times'])
                    ->inc('withhold_player_3_banker_times',$betAmount['withhold_player_3_banker_times'])
                    ->update();
            } elseif ($tableInfo['game_id'] == 6){
                $beforeAmountString = $numberTabInfo['toning_amount'];
                $beforeAmountArray = string_to_array($beforeAmountString);
                $afterAmountArray = ToningUtil::amountInc($beforeAmountArray, $betAmount);
                NumberTab::where('id',$numberTabInfo['id'])->update(['toning_amount' => array_to_string($afterAmountArray)]);
            } elseif ($tableInfo['game_id'] == 7){
                $beforeAmountString = $numberTabInfo['dice_amount'];
                $beforeAmountArray = string_to_array($beforeAmountString);
                $afterAmountArray = DiceUtil::amountInc($beforeAmountArray, $betAmount);
                NumberTab::where('id',$numberTabInfo['id'])->update(['dice_amount' => array_to_string($afterAmountArray)]);
            } elseif ($tableInfo['game_id'] == 8){
                $beforeAmountString = $numberTabInfo[$rouletteType];
                $beforeAmountArray = string_to_array($beforeAmountString);
                $afterAmountArray = RouletteUtil::amountInc($beforeAmountArray, $betAmount);
                NumberTab::where('id',$numberTabInfo['id'])->update([ $rouletteType => array_to_string($afterAmountArray)]);
            }
            $amount = array_sum($betAmount);
            $totalAmount = array_sum($betTotalAmount);
            User::where('id',$userInfo['id'])->dec('money',$amount)->update();
            if($prevBetInfo){
                $bet = ['id' => $prevBetInfo['id'], 'amount' => $totalAmount, 'money_after_bet' => $userInfo['money'] - $amount];
                if ($tableInfo['game_id'] == 6){
                    $bet['toning_amount'] = array_to_string($betTotalAmount);
                } elseif($tableInfo['game_id'] == 7){
                    $bet['dice_amount'] = array_to_string($betTotalAmount);
                } elseif($tableInfo['game_id'] == 8){
                    $bet[$rouletteType] = array_to_string($betTotalAmount);
                } else {
                    $bet = array_merge($bet,$betTotalAmount);
                }
                $bet['seat_num'] = $seat_num;
                $bet['manager_id'] = $userInfo['manager_id'];
                self::where(['id' => $prevBetInfo['id']])->update($bet);
            }else{
                $bet = array(
                    'user_id' => $userInfo['id'],
                    'agent_parent_id_path' => $userInfo['agent_parent_id_path'],
                    'username' => $userInfo['username'],
                    'nickname' => $userInfo['nickname'],
                    'table_id' => $tableInfo['id'],
                    'boot_id' => $numberTabInfo['boot_id'],
                    'boot_num' => $numberTabInfo['boot_num'],
                    'number_tab_id' => $numberTabInfo['id'],
                    'number' => $numberTabInfo['number'],
                    'game_id' => $tableInfo['game_id'],
                    'game_name' => $tableInfo['game_name'],
                    'table_name' => $tableInfo['table_name'],
                    'sumday_id' => $numberTabInfo['sumday_id'],
                    'day' => $numberTabInfo['day'],
                    'amount' => $totalAmount,
                    'money_before_bet' => $userInfo['money'],
                    'money_after_bet' => $userInfo['money'] - $amount,
                    'unify_time' => $numberTabInfo['unify_time'],
                    'create_time' => $time,
                    'baccarat_type' => $baccaratType,
                    'seat_num' => $seat_num,
                    'manager_id' => $userInfo['manager_id']
                );
                if ($tableInfo['game_id'] == 6){
                    $bet['toning_amount'] = array_to_string($betTotalAmount);
                } elseif ($tableInfo['game_id'] == 7){
                    $bet['dice_amount'] = array_to_string($betTotalAmount);
                } elseif ($tableInfo['game_id'] == 8){
                    $bet[$rouletteType] = array_to_string($betTotalAmount);
                } else {
                    $bet = array_merge($bet,$betTotalAmount);
                }
                self::create($bet);
            }
            Db::commit();
            return true;
        } catch (\Exception $e){
            Db::rollback();
            return false;
        }
    }
    /**
     * TODO openingBet AllGame
     * @param array $tableInfo          桌子信息
     * @param array $betInfo            注单信息
     * @param array $userInfo           用户信息
     * @param array $numberTabInfo      铺信息
     * @param float $amount             下注总数
     * @param float $winTotal           赢钱金额
     * @param float $rebate             洗码量
     * @param float $withholdAmount     翻倍下注数
     * @return array
     */
    public static function openingBet(
        array $tableInfo,
        array $betInfo,
        array $userInfo,
        array $numberTabInfo,
        float $amount,
        float $winTotal,
        float $rebate,
        float $withholdAmount = 0
    ): array
    {
        $time = time();
        Db::startTrans();
        try {
            // 更新user表余额
            $money = $userInfo['money'] + $winTotal + $amount + $withholdAmount;
            $updateMoney = round(($winTotal + $amount + $withholdAmount),2);
            User::where(['id' => $userInfo['id']])->inc('money',$updateMoney)->update();
            // 更新bet表
            if ($numberTabInfo['game_id'] == 1 || $numberTabInfo['game_id'] == 2){
                $betUpdate = ['result' => $numberTabInfo['result'], 'win_total' => $winTotal, 'end_money' => $money, 'is_end' => 1];
            } elseif ($numberTabInfo['game_id'] == 6){
                $betUpdate = ['toning_result' => $numberTabInfo['toning_result'], 'win_total' => $winTotal, 'end_money' => $money, 'is_end' => 1];
            } elseif ($numberTabInfo['game_id'] == 7){
                $betUpdate = ['dice_result' => $numberTabInfo['dice_result'], 'win_total' => $winTotal, 'end_money' => $money, 'is_end' => 1];
            }  elseif ($numberTabInfo['game_id'] == 8){
                $betUpdate = ['roulette_result' => $numberTabInfo['roulette_result'], 'win_total' => $winTotal, 'end_money' => $money, 'is_end' => 1];
            }else {
                $betUpdate = ['win_total' => $winTotal, 'end_money' => $money, 'is_end' => 1];
            }
            if (in_array($tableInfo['game_id'],[4,5])){
                $betUpdate['position_first'] = $betInfo['position_first'];
                $betUpdate['result_player_1'] = $betInfo['result_player_1'];
                $betUpdate['result_player_2'] = $betInfo['result_player_2'];
                $betUpdate['result_player_3'] = $betInfo['result_player_3'];
                $betUpdate['result_banker'] = $betInfo['result_banker'];
                $betUpdate['win_player_1'] = $betInfo['win_player_1'];
                $betUpdate['win_player_2'] = $betInfo['win_player_2'];
                $betUpdate['win_player_3'] = $betInfo['win_player_3'];
                $betUpdate['times_player_1'] = $betInfo['times_player_1'];
                $betUpdate['times_player_2'] = $betInfo['times_player_2'];
                $betUpdate['times_player_3'] = $betInfo['times_player_3'];
            }
            self::where(['id' => $betInfo['id']])->update($betUpdate);
            /* 处理洗码及占股 */
            $agent = explode(',', $userInfo['agent_parent_id_path']);
            $generalAgent = User::get(intval($agent[0]));
            if($numberTabInfo['game_id'] == 5){
                $betXimalv = $generalAgent['agent_ximalv_tc'];
            }elseif($numberTabInfo['game_id'] == 4){
                $betXimalv = $generalAgent['agent_ximalv_nn'];
            }elseif($numberTabInfo['game_id'] == 2){
                $betXimalv = $generalAgent['agent_ximalv_dt'];
            }else{
                $betXimalv = $generalAgent['agent_ximalv'];
            }
            $betMaliang = round(($rebate * $betXimalv) / 100,2);
            krsort($agent);
            $nextCs = 0;
            $nextMaliang = 0;
            $nextZhanGulv = 0;
            $nextRebate = 0;
            foreach($agent as $key => $value){
                $userPathInfo = User::get($value);
                if($userPathInfo){
                    $maliang = 0;
                    if($numberTabInfo['game_id'] == 5){
                        $ximalv = $userPathInfo['agent_ximalv_tc'];
                    }elseif($numberTabInfo['game_id'] == 4){
                        $ximalv = $userPathInfo['agent_ximalv_nn'];
                    }elseif($numberTabInfo['game_id'] == 2){
                        $ximalv = $userPathInfo['agent_ximalv_dt'];
                    }else{
                        $ximalv = $userPathInfo['agent_ximalv'];
                    }
                    $type = $key == 0 ? 1 : 0;
                    $netZhangulv = round(($userPathInfo['agent_cs'] / 100 - $nextZhanGulv),2);
                    if($tableInfo['is_xima'] == 1 && $rebate > 0){
                        $maliang = round(($rebate * $ximalv) / 100,2);
                        $netMaliang = $maliang - $nextMaliang;
                        $shareMaliang = $betMaliang * $netZhangulv;
                        $percentMaliang = round(($userPathInfo['agent_cs'] / 100) * $betMaliang, 2);
                        if($userPathInfo['share_xima'] == 2){
                            $nextLevelMaliang = $maliang - $percentMaliang;
                        }else{
                            $nextLevelMaliang = $maliang;
                        }
                        $maliangTrue = $netMaliang - $shareMaliang;
                        //判断是否即时结算洗吗
                        $insertXima = array(
                            'agent_parent_id_path' => $userInfo['agent_parent_id_path'],
                            'user_id' => $value,
                            'bet_user_id' => $userInfo['id'],
                            'bet_id' => $betInfo['id'],
                            'game_id' => $betInfo['game_id'],
                            'table_id' => $betInfo['table_id'],
                            'game_name' => $betInfo['game_name'],
                            'table_name' => $betInfo['table_name'],
                            'boot_num' => $betInfo['boot_num'],
                            'number' => $betInfo['number'],
                            'sumday_id' => $betInfo['sumday_id'],
                            'day' => $betInfo['day'],
                            'number_tab_id' => $betInfo['number_tab_id'],
                            'boot_id' => $betInfo['boot_id'],
                            'ximaliang' => $rebate,
                            'ximalv' => $ximalv,
                            'maliang' => $maliang,
                            'maliang_true' => $maliangTrue,
                            'total' => $amount,
                            'win_total' => $winTotal,
                            'create_time' => $time,
                            'unify_time' => $betInfo['unify_time'],
                            'type' => $type,
                            'net_maliang' => $netMaliang,
                            'bet_maliang' => $betMaliang,
                            'agent_cs' => $userPathInfo['agent_cs'],
                            'net_agent_cs' => $netZhangulv,
                            'share_maliang' => $shareMaliang,
                            'percent_maliang' => $percentMaliang,
                            'next_level_maliang' => $nextLevelMaliang,
                        );
                        if($generalAgent['now_checkout_xima'] == 1 && $betInfo['user_id'] == $userPathInfo['id'] && $userPathInfo['agent'] == 0){
                            // 判断上级余额扣为负数
                            $parentInfo = User::where(['id' => $userPathInfo['agent_parent_id']])->find();
                            if(SETTLE_MONEY_EXCEED_PARENT_MONTY == 1 || $maliang <= $parentInfo['money']){
                                // 洗码表记录状态
                                $insertXima['is_checkout'] = 1;
                                $insertXima['checkout_time'] = $time;

                                // 增加用户余额
                                User::where(['id' => $userPathInfo['id']])->inc('money',$maliang)->update();
                                $money = $money + $maliangTrue;

                                // 添加用户上分记录
                                $userScoreData = [
                                    'type' => 2,
                                    'amount' => $maliang,
                                    'mode' => 1,
                                    'agent_or_admin' => 4,
                                    'controller_type' => '系统即时结算',
                                    'user_id' => $userPathInfo['id'],
                                    'user_type' => $userPathInfo['agent'],
                                    'user_agent_level' => $userPathInfo['agent_level'],
                                    'username_for' => $userPathInfo['username'],
                                    'nickname_for' => $userPathInfo['nickname'],
                                    'user_parent_id' => $userPathInfo['agent_parent_id'],
                                    'create_time' => $time,
                                    'old_money' => $userPathInfo['money'],
                                    'new_money' => $userPathInfo['money'] + $maliang,
                                    'controller_old_money' => $parentInfo['money'],
                                    'controller_new_money' => $parentInfo['money'] - $maliang,
                                    'controller_system' => 4,
                                ];
                                Recharge::create($userScoreData);

                                // 扣除上级余额
                                User::where(['id' => $parentInfo['id']])->dec('money',$maliang)->update();

                                // 添加用户上分记录
                                $userScoreData = [
                                    'type' => 2,
                                    'amount' => $maliang,
                                    'mode' => 2,
                                    'agent_or_admin' => 4,
                                    'controller_type' => '系统即时结算',
                                    'user_id' => $parentInfo['id'],
                                    'user_type' => $parentInfo['agent'],
                                    'user_agent_level' => $parentInfo['agent_level'],
                                    'username_for' => $parentInfo['username'],
                                    'nickname_for' => $parentInfo['nickname'],
                                    'user_parent_id' => $parentInfo['agent_parent_id'],
                                    'create_time' => $time,
                                    'old_money' => $parentInfo['money'],
                                    'new_money' => $parentInfo['money'] - $maliang,
                                    'controller_old_money' => $parentInfo['money'],
                                    'controller_new_money' => $parentInfo['money'] - $maliang,
                                    'controller_system' => 4,
                                ];
                                Recharge::create($userScoreData);

                                // 添加洗码结算记录
                                $ximaLogData = [
                                    'user_id' => $userPathInfo['id'],
                                    'username' => $userPathInfo['username'],
                                    'admin_or_agent' => 4,
                                    'ximaliang' => $rebate,
                                    'maliang' => $maliang,
                                    'agent_ximalv' => $userPathInfo['agent_ximalv'].'/'.$userPathInfo['agent_ximalv_dt'].'/'.$userPathInfo['agent_ximalv_nn'].'/'.$userPathInfo['agent_ximalv_tc'],
                                    'create_time' => $time,
                                    'old_money' => $userPathInfo['money'],
                                    'new_money' => $userPathInfo['money'] + $maliang,
                                    'type' => 1,  // 洗码上分
                                ];
                                XimaLog::create($ximaLogData);
                            }

                        }
                        Xima::create($insertXima);
                        $nextMaliang = $netMaliang + $nextMaliang;
                    }
                    //计算占股
                    $shareAmount = to_number(round(($userPathInfo['agent_cs'] * $winTotal) / 100,2));
                    $shareAmountTrue = to_number(round(($netZhangulv * $winTotal),2));
                    $netCs = $shareAmount - $nextCs;
                    $insertCs = array(
                        'agent_parent_id_path' => $userInfo['agent_parent_id_path'],
                        'user_id' => $value,
                        'bet_user_id' => $userInfo['id'],
                        'bet_id' => $betInfo['id'],
                        'game_id' => $betInfo['game_id'],
                        'table_id' => $betInfo['table_id'],
                        'game_name' => $betInfo['game_name'],
                        'table_name' => $betInfo['table_name'],
                        'boot_num' => $betInfo['boot_num'],
                        'number' => $betInfo['number'],
                        'number_tab_id' => $betInfo['number_tab_id'],
                        'boot_id' => $betInfo['boot_id'],
                        'sumday_id' => $betInfo['sumday_id'],
                        'day' => $betInfo['day'],
                        'share_amount' => $shareAmount,
                        'share_amount_true' => $shareAmountTrue,
                        'share_percent' => $userPathInfo['agent_cs'],
                        'total' => $amount,
                        'win_total' => $winTotal,
                        'create_time' => $time,
                        'unify_time' => $betInfo['unify_time'],
                        'type' => $type,
                        'net_cs' => $netCs,
                        'maliang' => $maliang,
                        'share_maliang' => $shareMaliang ?? 0,
                        'net_maliang' => $netMaliang ?? 0,
                    );
                    Cs::create($insertCs);
                    $nextZhanGulv = $netZhangulv + $nextZhanGulv;
                    $nextCs = $netCs + $nextCs;

                    // 计算返水
                    $rebateRate = $userPathInfo['rebate_rate'];
                    if($generalAgent['agent_type'] == 1){
                        $rebateAmount = ($amount * $rebateRate) / 100;
                        $rebateAmountActual = $rebateAmount - $nextRebate;
                        $insertRebate = array(
                            'agent_parent_id_path' => $userInfo['agent_parent_id_path'],
                            'user_id' => $value,
                            'bet_user_id' => $userInfo['id'],
                            'bet_id' => $betInfo['id'],
                            'game_id' => $betInfo['game_id'],
                            'table_id' => $betInfo['table_id'],
                            'game_name' => $betInfo['game_name'],
                            'table_name' => $betInfo['table_name'],
                            'boot_num' => $betInfo['boot_num'],
                            'number' => $betInfo['number'],
                            'sumday_id' => $betInfo['sumday_id'],
                            'day' => $betInfo['day'],
                            'number_tab_id' => $betInfo['number_tab_id'],
                            'boot_id' => $betInfo['boot_id'],
                            'amount' => $amount,
                            'rebate_amount' => $rebateAmount,
                            'rebate_amount_actual' => $rebateAmountActual,
                            'rebate_rate' => $rebateRate,
                            'create_time' => $time,
                            'unify_time' => $betInfo['unify_time'],
                        );
                        Rebate::create($insertRebate);
                        $nextRebate = $rebateAmountActual + $nextRebate;
                    }
                }
            }
            // 提交事务
            Db::commit();
            return ['status' => true, 'msg' => 'opening_success', 'money' => $money];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['status' => false, 'msg' => 'opening_fail'];
        }
    }
    /**
     * TODO cancelBet AllGame
     * @param array $tableInfo
     * @param array $numberTabInfo
     * @param array $userInfo
     * @param array $prevBetInfo
     * @return array
     */
    public static function cancelBet(array $tableInfo, array $numberTabInfo, array $userInfo, array $prevBetInfo): array{
        Db::startTrans();
        try {
            if($tableInfo['game_id'] == 1){
                $updateNumberTab = array(
                    'banker_amount' => $numberTabInfo['banker_amount'] - $prevBetInfo['banker_amount'],
                    'player_amount' => $numberTabInfo['player_amount'] - $prevBetInfo['player_amount'],
                    'tie_amount' => $numberTabInfo['tie_amount'] - $prevBetInfo['tie_amount'],
                    'banker_pair_amount' => $numberTabInfo['banker_pair_amount'] - $prevBetInfo['banker_pair_amount'],
                    'player_pair_amount' => $numberTabInfo['player_pair_amount'] - $prevBetInfo['player_pair_amount'],
                    'luck_six_amount' => $numberTabInfo['luck_six_amount'] - $prevBetInfo['luck_six_amount'],
                    'big_amount' => $numberTabInfo['big_amount'] - $prevBetInfo['big_amount'],
                    'small_amount' => $numberTabInfo['player_pair_amount'] - $prevBetInfo['small_amount']
                );
            }elseif($tableInfo['game_id'] == 2){
                $updateNumberTab = array(
                    'banker_amount' => $numberTabInfo['banker_amount'] - $prevBetInfo['banker_amount'],
                    'player_amount' => $numberTabInfo['player_amount'] - $prevBetInfo['player_amount'],
                    'tie_amount' => $numberTabInfo['tie_amount'] - $prevBetInfo['tie_amount'],
                );
            }elseif($tableInfo['game_id'] == 4 || $tableInfo['game_id'] == 5){
                $updateNumberTab = array(
                    'amount_player_1' => $numberTabInfo['amount_player_1'] - $prevBetInfo['amount_player_1'],
                    'amount_player_1_times' => $numberTabInfo['amount_player_1_times'] - $prevBetInfo['amount_player_1_times'],
                    'withhold_player_1_times' => $numberTabInfo['withhold_player_1_times'] - $prevBetInfo['withhold_player_1_times'],
                    'amount_player_1_banker' => $numberTabInfo['amount_player_1_banker'] - $prevBetInfo['amount_player_1_banker'],
                    'amount_player_1_banker_times' => $numberTabInfo['amount_player_1_banker_times'] - $prevBetInfo['amount_player_1_banker_times'],
                    'withhold_player_1_banker_times' => $numberTabInfo['withhold_player_1_banker_times'] - $prevBetInfo['withhold_player_1_banker_times'],

                    'amount_player_2' => $numberTabInfo['amount_player_2'] - $prevBetInfo['amount_player_2'],
                    'amount_player_2_times' => $numberTabInfo['amount_player_2_times'] - $prevBetInfo['amount_player_2_times'],
                    'withhold_player_2_times' => $numberTabInfo['withhold_player_2_times'] - $prevBetInfo['withhold_player_2_times'],
                    'amount_player_2_banker' => $numberTabInfo['amount_player_2_banker'] - $prevBetInfo['amount_player_2_banker'],
                    'amount_player_2_banker_times' => $numberTabInfo['amount_player_2_banker_times'] - $prevBetInfo['amount_player_2_banker_times'],
                    'withhold_player_2_banker_times' => $numberTabInfo['withhold_player_2_banker_times'] - $prevBetInfo['withhold_player_2_banker_times'],

                    'amount_player_3' => $numberTabInfo['amount_player_3'] - $prevBetInfo['amount_player_3'],
                    'amount_player_3_times' => $numberTabInfo['amount_player_3_times'] - $prevBetInfo['amount_player_3_times'],
                    'withhold_player_3_times' => $numberTabInfo['withhold_player_3_times'] - $prevBetInfo['withhold_player_3_times'],
                    'amount_player_3_banker' => $numberTabInfo['amount_player_3_banker'] - $prevBetInfo['amount_player_3_banker'],
                    'amount_player_3_banker_times' => $numberTabInfo['amount_player_3_banker_times'] - $prevBetInfo['amount_player_3_banker_times'],
                    'withhold_player_3_banker_times' => $numberTabInfo['withhold_player_3_banker_times'] - $prevBetInfo['withhold_player_3_banker_times'],
                );
            }
            NumberTab::where(['id' => $numberTabInfo['id']])->update($updateNumberTab);
            //删除bet表下注记录，并且更新会员余分
            Bet::where(['table_id' => $tableInfo['id'], 'number_tab_id' => $numberTabInfo['id'], 'user_id' => $userInfo['id']])->delete();
            if($tableInfo['game_id'] == 4){
                $returnMoney = round(($prevBetInfo['withhold_amount'] + $prevBetInfo['amount']), 2);
            }else{
                $returnMoney = $prevBetInfo['amount'];
            }
            User::where(['id' => $userInfo['id']])->inc('money',$returnMoney)->update();
            $newMoney = round(($userInfo['money'] + $returnMoney), 2);
            Db::commit();
            return ['status' => true, 'table_id' =>  $tableInfo['id'], 'user_id' => $userInfo['id'], 'manager_id' => $userInfo['manager_id'],'msg' => 'cancel_bet_success', 'money' => $newMoney];
        } catch (\Exception $e) {
            Db::rollback();
            return ['status' => false, 'msg' => 'cannot_cancel_bet'];
        }
    }
}
