<?php


namespace app\models\process;


use app\models\bet\Bet;
use app\models\bet\Cs;
use app\models\bet\Rebate;
use app\models\bet\Xima;
use app\models\bet\XimaLog;
use app\models\user\Recharge;
use app\models\user\User;
use freedom\basic\BaseModel;
use freedom\traits\ModelTrait;
use freedom\utils\RedisUtil;
use think\facade\Db;
use think\facade\Env;

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

    use ModelTrait;

    /**
     * TODO 获取已经完毕的局
     * @param int $bootId
     * @param string $field
     * @return array
     */
    public static function getByBootIdDone(int $bootId, string $field): array
    {
        $select = self::where(['boot_id' => $bootId, 'bet_status' => 3])->field($field)->order('start_time ASC,id ASC')->select();
        if ($select) return $select->toArray();
        else return [];
    }

    /**
     * TODO 根据靴获取最后一局
     * @param array $bootInfo
     * @return array
     */
    public static function getByBootIdOrderByIdDesc(array $bootInfo): array
    {
        $find = self::where(['boot_id' => $bootInfo['id'], 'is_add' => 0])->order('id DESC')->find();
        if ($find) return $find->toArray();
        else return [];
    }

    /**
     * TODO 根据桌子获取最后一局
     * @param array $tableInfo
     * @return array
     */
    public static function getByTableIdOrderByIdDesc(array $tableInfo): array
    {
        $find = self::where(['table_id' => $tableInfo['id'], 'is_add' => 0])->order('id DESC')->find();
        if ($find) return $find->toArray();
        else return [];
    }
    /**
     * TODO 根据桌子获取最后两局
     * @param array $tableInfo
     * @return array
     */
    public static function getByTableIdOrderByIdDesc_two(array $tableInfo): array
    {
        $find = self::where(['table_id' => $tableInfo['id'], 'is_add' => 0])->order('id DESC')->limit(2)->select();
        if ($find) return $find->toArray();
        else return [];
    }

    /**
     * TODO 根据bootInfo创建新一局
     * @param array $bootInfo
     * @return array
     */
    public static function addByBoot(array $bootInfo): array
    {
        $insert = array(
            'table_id' => $bootInfo['table_id'],
            'table_name' => $bootInfo['table_name'],
            'game_id' => $bootInfo['game_id'],
            'game_name' => $bootInfo['game_name'],
            'sumday_id' => $bootInfo['sumday_id'],
            'day' => $bootInfo['day'],
            'boot_id' => $bootInfo['id'],
            'boot_num' => $bootInfo['boot_num'],
            'number' => 1,
            'start_time' => time(),
            'unify_time' => time(),
            'bet_status' => 0,
            'rob_status' => 0
        );
        $newNumberTab = self::create($insert);
        return $newNumberTab->toArray();
    }

    /**
     * TODO 开始倒计时
     * @param int $numberTabId
     * @return array
     */
    public static function startBet(int $numberTabId): array
    {
        $numberTabInfo = self::get(['id' => $numberTabId]);
        if (!$numberTabInfo) return ['status' => false, 'msg' => 'start_bet_fail'];
        if ($numberTabInfo['bet_status'] != 0) return ['status' => false, 'msg' => 'start_bet_error'];
        self::where(['id' => $numberTabInfo['id']])->update(['bet_status' => 1, 'bet_start_time' => time()]);
        $numberTabInfo['bet_status'] = 1;
        $numberTabInfo['bet_start_time'] = time();
        return ['status' => true, 'data' => $numberTabInfo];
    }

    /**
     * TODO 结束倒计时
     * @param int $numberTabId
     * @return array
     */
    public static function endBet(int $numberTabId): array
    {
        $numberTabInfo = self::get(['id' => $numberTabId]);
        if (!$numberTabInfo) return ['status' => false, 'msg' => 'end_bet_fail'];
        if ($numberTabInfo['bet_status'] != 1) return ['status' => false, 'msg' => 'end_bet_error'];
        self::where(['id' => $numberTabInfo['id']])->update(['bet_status' => 2, 'bet_end_time' => time()]);
        $numberTabInfo['bet_status'] = 2;
        $numberTabInfo['bet_start_time'] = time();
        return ['status' => true, 'data' => $numberTabInfo];
    }

    /**
     * TODO 开始倒计时(ROB)
     * @param int $numberTabId
     * @return array
     */
    public static function startRob(int $numberTabId): array
    {
        $numberTabInfo = self::get(['id' => $numberTabId]);
        if (!$numberTabInfo) return ['status' => false, 'msg' => 'start_rob_fail'];
        if ($numberTabInfo['rob_status'] != 0) return ['status' => false, 'msg' => 'start_rob_error'];
        self::where(['id' => $numberTabInfo['id']])->update(['rob_status' => 1, 'rob_start_time' => time()]);
        $numberTabInfo['rob_status'] = 1;
        $numberTabInfo['rob_start_time'] = time();
        return ['status' => true, 'data' => $numberTabInfo];
    }

    /**
     * TODO 结束倒计时(ROB)
     * @param int $numberTabId
     * @return array
     */
    public static function endRob(int $numberTabId): array
    {
        $numberTabInfo = self::get(['id' => $numberTabId]);
        if (!$numberTabInfo) return ['status' => false, 'msg' => 'end_rob_fail'];
        if ($numberTabInfo['rob_status'] != 1) return ['status' => false, 'msg' => 'end_rob_error'];
        self::where(['id' => $numberTabInfo['id']])->update(['rob_status' => 2, 'rob_end_time' => time()]);
        $numberTabInfo['rob_status'] = 2;
        $numberTabInfo['rob_start_time'] = time();
        return ['status' => true, 'data' => $numberTabInfo];
    }

    /**
     * TODO 开始下一局 AllGame
     * @param array $lastNumberTab
     * @param array $update
     * @param array $tableInfo
     * @return array
     */
    public static function next(array $lastNumberTab, array $update,array $tableInfo): array
    {
        Db::startTrans();
        try {
            self::where(['id' => $lastNumberTab['id']])->update($update);
            $seat_json = '';
            if($tableInfo['bet_type'] == 2){
                $seat_arr = [];
                $seat_json = json_encode($seat_arr);
            }
            $insert = array(
                'table_id' => $lastNumberTab['table_id'],
                'table_name' => $lastNumberTab['table_name'],
                'game_id' => $lastNumberTab['game_id'],
                'game_name' => $lastNumberTab['game_name'],
                'sumday_id' => $lastNumberTab['sumday_id'],
                'day' => $lastNumberTab['day'],
                'boot_id' => $lastNumberTab['boot_id'],
                'boot_num' => $lastNumberTab['boot_num'],
                'number' => $lastNumberTab['number'] + 1,
                'start_time' => time(),
                'unify_time' => time(),
                'bet_status' => 0,
                'rob_status' => 0,
                'seat_json' => $seat_json
            );
            $newNumberTab = self::create($insert);
            Bet::where(['number_tab_id' => $lastNumberTab['id']])->update(['is_end' => 1]);
            //更新Boot表的汇总
            if ($lastNumberTab['game_id'] == 1 || $lastNumberTab['game_id'] == 2){
                switch ($update['result']){
                    case 1 :
                        Boot::where(['id' => $lastNumberTab['boot_id']])->inc('banker_count');
                        break;
                    case 2 :
                        Boot::where(['id' => $lastNumberTab['boot_id']])->inc('player_count');
                        break;
                    case 3 :
                        Boot::where(['id' => $lastNumberTab['boot_id']])->inc('tie_count');
                        break;
                }
            }
            if ($lastNumberTab['game_id'] == 1){
                switch ($update['pair']){
                    case 1 :
                        Boot::where(['id' => $lastNumberTab['boot_id']])->inc('banker_pair_count');
                        break;
                    case 2 :
                        Boot::where(['id' => $lastNumberTab['boot_id']])->inc('player_pair_count');
                        break;
                    case 3 :
                        Boot::where(['id' => $lastNumberTab['boot_id']])->inc('banker_pair_count');
                        Boot::where(['id' => $lastNumberTab['boot_id']])->inc('player_pair_count');
                        break;
                }
            }
            if ($lastNumberTab['game_id'] == 6){
                Boot::where(['id' => $lastNumberTab['boot_id']])->update(['toning_count' => $lastNumberTab['toning_count']]);
            }
            if ($lastNumberTab['game_id'] == 7){
                Boot::where(['id' => $lastNumberTab['boot_id']])->update(['dice_count' => $lastNumberTab['dice_count']]);
            }
            if ($lastNumberTab['game_id'] == 8){
                Boot::where(['id' => $lastNumberTab['boot_id']])->update(['roulette_count' => $lastNumberTab['roulette_count']]);
            }
            Db::commit();
            return $newNumberTab->toArray();
        } catch (\Exception $e) {
            pre($e->getMessage());
            Db::rollback();
            return [];
        }
    }

    /**
     * TODO 作废
     * @param array $numberTabInfo
     * @return bool;
     */
    public static function resetNumberTab(array $numberTabInfo): bool
    {
        Db::startTrans();
        try {
            $bets = Bet::getByNumberTabIdValid($numberTabInfo['id']);
            \think\facade\Log::write('resetNumberTab bets count: ' . count($bets), 'info');
            foreach ($bets AS $v) {
                $user = User::get($v['user_id']);
                if ($v['game_id'] == 4 || $v['game_id'] == 5){
                    $userMoney = round(($v['withhold_amount'] + $v['amount'] + $user['money']),2);
                }else{
                    $userMoney = round(($user['money'] + $v['amount']),2);
                }
                User::where(['id' => $v['user_id']])->update(['money' => $userMoney]);
                Bet::where(['id' => $v['id']])->update(['status' => 2]);
            }
            //更改局数据
            $updateNumberTab = array(
                'bet_status' => 0,
                'bet_start_time' => 0,
                'bet_end_time' => 0,
                'rob_status' => 0,
                'rob_start_time' => 0,
                'rob_end_time' => 0,
                'rob_banker_id' => 0,
                'rob_banker_username' => '',
            );
            if($numberTabInfo['game_id'] == 4 || $numberTabInfo['game_id'] == 5){
                $updateNumberTab['amount_player_1'] = 0;
                $updateNumberTab['amount_player_1_times'] = 0;
                $updateNumberTab['withhold_player_1_times'] = 0;
                $updateNumberTab['amount_player_1_banker'] = 0;
                $updateNumberTab['amount_player_1_banker_times'] = 0;
                $updateNumberTab['withhold_player_1_banker_times'] = 0;
                $updateNumberTab['amount_player_2'] = 0;
                $updateNumberTab['amount_player_2_times'] = 0;
                $updateNumberTab['withhold_player_2_times'] = 0;
                $updateNumberTab['amount_player_2_banker'] = 0;
                $updateNumberTab['amount_player_2_banker_times'] = 0;
                $updateNumberTab['withhold_player_2_banker_times'] = 0;
                $updateNumberTab['amount_player_3'] = 0;
                $updateNumberTab['amount_player_3_times'] = 0;
                $updateNumberTab['withhold_player_3_times'] = 0;
                $updateNumberTab['amount_player_3_banker'] = 0;
                $updateNumberTab['amount_player_3_banker_times'] = 0;
                $updateNumberTab['withhold_player_3_banker_times'] = 0;
            }else if($numberTabInfo['game_id'] == 2){
                $updateNumberTab['banker_amount'] = 0;
                $updateNumberTab['player_amount'] = 0;
                $updateNumberTab['tie_amount'] = 0;
            }else if($numberTabInfo['game_id'] == 1){
                $updateNumberTab['banker_amount'] = 0;
                $updateNumberTab['player_amount'] = 0;
                $updateNumberTab['tie_amount'] = 0;
                $updateNumberTab['banker_pair_amount'] = 0;
                $updateNumberTab['player_pair_amount'] = 0;
                $updateNumberTab['luck_six_amount'] = 0;
                $updateNumberTab['big_amount'] = 0;
                $updateNumberTab['small_amount'] = 0;
            }else if($numberTabInfo['game_id'] == 6){
                $updateNumberTab['toning_result'] = '';
            }else if($numberTabInfo['game_id'] == 7){
                $updateNumberTab['dice_amount'] = '';
            }else if($numberTabInfo['game_id'] == 8){
                $updateNumberTab['roulette_european_amount'] = '';
                $updateNumberTab['roulette_french_amount'] = '';
            }
            self::where(['id' => $numberTabInfo['id']])->update($updateNumberTab);
            //记录系统日志
            $retreatedLog = array(
                'mode' => 2,
                'type' => 3,
                'create_time' => time(),
                'gamei_id' => $numberTabInfo['game_id'],
                'table_id' => $numberTabInfo['table_id'],
                'table_name' => $numberTabInfo['table_name'],
                'boot_id' => $numberTabInfo['boot_id'],
                'boot_num' => $numberTabInfo['boot_num'],
                'number_tab_id' => $numberTabInfo['id'],
                'number' => $numberTabInfo['number']
            );
            RetreatedLog::create($retreatedLog);
            //清理redis的卡牌
            if ($numberTabInfo['game_id'] == 1 || $numberTabInfo['game_id'] == 2){
                RedisUtil::deleteCardPosition($numberTabInfo['id']);
            } else {
                RedisUtil::delete('card_'.$numberTabInfo['id']);
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            \think\facade\Log::write('resetNumberTab exception: ' . $e->getMessage(), 'error');
            Db::rollback();
            return false;
        }
    }

    public static function resetBaccarat(array $event,array $numberTabInfo,array $tableInfo): bool
    {
        Db::startTrans();
        try {
            /* 处理洗码及占股 */
            //扣除洗码
            $time = time();
            $ximas = Xima::getByNumberTabIdValid($numberTabInfo['id']);
            foreach ($ximas as $ximaVal){
                $ximaUserInfo = User::get($ximaVal['user_id']);
                if($ximaVal['is_checkout'] == 1){
                    $parentPathInfo = User::get($ximaUserInfo['agent_parent_id']);
                    User::where(['id' => $ximaUserInfo['id']])->dec('money',$ximaVal['maliang'])->update();
                    // 扣除上级余额
                    if($ximaUserInfo['agent_parent_id']){
                        User::where(['id' => $parentPathInfo['id']])->inc('money',$ximaVal['maliang'])->update();
                    }
                }
                Xima::del($ximaVal['id']);
            }
            //扣除返水
            $rebates = Rebate::getByNumberTabIdValid($numberTabInfo['id']);
            foreach ($rebates as $rebateVal){
                $rebateUserInfo = User::get($rebateVal['user_id']);
                if($rebateVal['is_checkout'] == 1 && $rebateVal['rebate_amount_actual'] > 0){
                    User::where(['id' => $rebateUserInfo['id']])->dec('money',$rebateVal['rebate_amount_actual'])->update();
                }
                Rebate::del($rebateVal['id']);
            }
            //扣除占股
            $css = Cs::getByNumberTabIdValid($numberTabInfo['id']);
            foreach ($css as $csVal){
                Cs::del($csVal['id']);
            }

            $bets = Bet::getByNumberTabIdValid($numberTabInfo['id']);
            foreach ($bets AS $v) {
                $user = User::get($v['user_id']);
                $winMoney = 0;
                $ximaliang = 0;
                $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'];
                //双边洗码
                if($user['type_xima'] == 1){
                    $ximaliang = abs($v['banker_amount'] - $v['player_amount']);
                }

                if($event['opening'] == 1){
                    // 庄赢
                    if ($v['banker_amount'] > 0){
                        if ($v['baccarat_type'] == 1){
                            if ($event['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 + $user['price_banker']),2) + $winMoney;
                        }
                    }
                    // 单边洗码
                    if($user['type_xima'] == 2){
                        $ximaliang = $v['player_amount'];
                    }
                }elseif($event['opening'] == 2){
                    // 闲赢
                    if($v['player_amount'] > 0){
                        $winMoney = $v['player_amount'] * (1 + $user['price_player']) + $winMoney;
                    }
                    // 单边洗码
                    if($user['type_xima'] == 2){
                        $ximaliang = $v['banker_amount'];
                    }
                }elseif($event['opening'] == 3) {
                    // 和赢
                    if($v['tie_amount'] > 0){
                        $winMoney = $v['tie_amount'] * (1 + $user['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($event['pair'] == 3){
                    // 计算庄对下注的赢钱金额
                    if ($v['banker_pair_amount'] > 0) {
                        $winMoney = $v['banker_pair_amount'] * (1 + $user['price_pair']) + $winMoney;
                    }
                    //计算闲对下注的赢钱金额
                    if ($v['player_pair_amount'] > 0) {
                        $winMoney = $v['player_pair_amount'] * (1 + $user['price_pair']) + $winMoney;
                    }
                }elseif($event['pair'] == 1){
                    if ($v['banker_pair_amount'] > 0) {
                        $winMoney = $v['banker_pair_amount'] * (1 + $user['price_pair']) + $winMoney;
                    }
                }elseif($event['pair'] == 2){
                    if ($v['player_pair_amount'] > 0) {
                        $winMoney = $v['player_pair_amount'] * (1 + $user['price_pair']) + $winMoney;
                    }
                }
                // 计算最终赢钱金额
                $winTotal = $winMoney - $amount;
                $userMoney = $user['money'] - $v['win_total'] + $winTotal;
                User::where(['id' => $v['user_id']])->update(['money' => $userMoney]);
                $updateBet = array(
                    'result' => $event['opening'],
                    'pair' => $event['pair'],
                    'end_money' => $v['money_after_bet'] + $winTotal,
                    'win_total' => $winTotal,
                    'is_edit' => 1,
                );
                Bet::where(['id' => $v['id']])->update($updateBet);
                /* 处理洗码及占股 */
                $agent = explode(',', $user['agent_parent_id_path']);
                $generalAgent = User::get(intval($agent[0]));
                $betXimalv = $generalAgent['agent_ximalv'];
                $betMaliang = round(($ximaliang * $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;
                        $ximalv = $userPathInfo['agent_ximalv'];
                        $type = $key == 0 ? 1 : 0;
                        $netZhangulv = round(($userPathInfo['agent_cs'] / 100 - $nextZhanGulv),2);
                        if($tableInfo['is_xima'] == 1 && $ximaliang > 0){
                            $maliang = round(($ximaliang * $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' => $user['agent_parent_id_path'],
                                'user_id' => $value,
                                'bet_user_id' => $user['id'],
                                'bet_id' => $v['id'],
                                'game_id' => $v['game_id'],
                                'table_id' => $v['table_id'],
                                'game_name' => $v['game_name'],
                                'table_name' => $v['table_name'],
                                'boot_num' => $v['boot_num'],
                                'number' => $v['number'],
                                'sumday_id' => $v['sumday_id'],
                                'day' => $v['day'],
                                'number_tab_id' => $v['number_tab_id'],
                                'boot_id' => $v['boot_id'],
                                'ximaliang' => $ximaliang,
                                'ximalv' => $ximalv,
                                'maliang' => $maliang,
                                'maliang_true' => $maliangTrue,
                                'total' => $amount,
                                'win_total' => $winTotal,
                                'create_time' => $time,
                                'unify_time' => $v['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 && $v['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();

                                    // 添加用户上分记录
                                    $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' => $ximaliang,
                                        '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' => $user['agent_parent_id_path'],
                            'user_id' => $value,
                            'bet_user_id' => $user['id'],
                            'bet_id' => $v['id'],
                            'game_id' => $v['game_id'],
                            'table_id' => $v['table_id'],
                            'game_name' => $v['game_name'],
                            'table_name' => $v['table_name'],
                            'boot_num' => $v['boot_num'],
                            'number' => $v['number'],
                            'number_tab_id' => $v['number_tab_id'],
                            'boot_id' => $v['boot_id'],
                            'sumday_id' => $v['sumday_id'],
                            'day' => $v['day'],
                            'share_amount' => $shareAmount,
                            'share_amount_true' => $shareAmountTrue,
                            'share_percent' => $userPathInfo['agent_cs'],
                            'total' => $amount,
                            'win_total' => $winTotal,
                            'create_time' => $time,
                            'unify_time' => $v['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' => $user['agent_parent_id_path'],
                                'user_id' => $value,
                                'bet_user_id' => $user['id'],
                                'bet_id' => $v['id'],
                                'game_id' => $v['game_id'],
                                'table_id' => $v['table_id'],
                                'game_name' => $v['game_name'],
                                'table_name' => $v['table_name'],
                                'boot_num' => $v['boot_num'],
                                'number' => $v['number'],
                                'sumday_id' => $v['sumday_id'],
                                'day' => $v['day'],
                                'number_tab_id' => $v['number_tab_id'],
                                'boot_id' => $v['boot_id'],
                                'amount' => $amount,
                                'rebate_amount' => $rebateAmount,
                                'rebate_amount_actual' => $rebateAmountActual,
                                'rebate_rate' => $rebateRate,
                                'create_time' => $time,
                                'unify_time' => $v['unify_time'],
                            );
                            Rebate::create($insertRebate);
                            $nextRebate = $rebateAmountActual + $nextRebate;
                        }
                    }
                }
            }
            $updateNumberTab = array(
                'result' => $event['opening'],
                'result_before_edit' => $numberTabInfo['result'],
                'pair' => $event['pair'],
                'pair_before_edit' => $numberTabInfo['pair'],
            );

            NumberTab::where(['id' => $numberTabInfo['id']])->update($updateNumberTab);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }

    public static function resetDt(array $event,array $numberTabInfo,array $tableInfo): bool
    {
        Db::startTrans();
        try {
            /* 处理洗码及占股 */
            //扣除洗码
            $time = time();
            $ximas = Xima::getByNumberTabIdValid($numberTabInfo['id']);
            foreach ($ximas as $ximaVal){
                $ximaUserInfo = User::get($ximaVal['user_id']);
                if($ximaVal['is_checkout'] == 1){
                    $parentPathInfo = User::get($ximaUserInfo['agent_parent_id']);
                    User::where(['id' => $ximaUserInfo['id']])->dec('money',$ximaVal['maliang'])->update();
                    // 扣除上级余额
                    if($ximaUserInfo['agent_parent_id']){
                        User::where(['id' => $parentPathInfo['id']])->inc('money',$ximaVal['maliang'])->update();
                    }
                }
                Xima::del($ximaVal['id']);
            }
            //扣除返水
            $rebates = Rebate::getByNumberTabIdValid($numberTabInfo['id']);
            foreach ($rebates as $rebateVal){
                $rebateUserInfo = User::get($rebateVal['user_id']);
                if($rebateVal['is_checkout'] == 1 && $rebateVal['rebate_amount_actual'] > 0){
                    User::where(['id' => $rebateUserInfo['id']])->dec('money',$rebateVal['rebate_amount_actual'])->update();
                }
                Rebate::del($rebateVal['id']);
            }
            //扣除占股
            $css = Cs::getByNumberTabIdValid($numberTabInfo['id']);
            foreach ($css as $csVal){
                Cs::del($csVal['id']);
            }

            $bets = Bet::getByNumberTabIdValid($numberTabInfo['id']);
            foreach ($bets AS $v) {
                $user = User::get($v['user_id']);
                $winMoney = 0;
                $ximaliang = 0;
                $amount = $v['banker_amount'] + $v['player_amount'] + $v['tie_amount'];
                //双边洗码
                if($user['type_xima'] == 1){
                    $ximaliang = abs($v['banker_amount'] - $v['player_amount']);
                }

                if($event['opening'] == 1){
                    // 庄赢
                    if ($v['banker_amount'] > 0){
                        $winMoney = round($v['banker_amount'] * (1 + $user['price_dragon']),2) + $winMoney;
                    }
                    // 单边洗码
                    if($user['type_xima'] == 2){
                        $ximaliang = $v['player_amount'];
                    }
                }elseif($event['opening'] == 2){
                    // 闲赢
                    if($v['player_amount'] > 0){
                        $winMoney = $v['player_amount'] * (1 + $user['price_tiger']) + $winMoney;
                    }
                    // 单边洗码
                    if($user['type_xima'] == 2){
                        $ximaliang = $v['banker_amount'];
                    }
                }elseif($event['opening'] == 3) {
                    // 和赢
                    if (Env::get('system.dt_half') == 1) {
                        $winMoney = round(($v['banker_amount'] + $v['player_amount']) / 2, 2) + $winMoney;
                    } else {
                        $winMoney = $v['banker_amount'] + $v['player_amount'] + $winMoney;
                    }
                    $ximaliang = 0;
                    if ($v['tie_amount'] > 0) {
                        $winMoney = $v['tie_amount'] * (1 + $user['price_tie_dt']) + $winMoney;
                    }
                }
                // 计算最终赢钱金额
                $winTotal = $winMoney - $amount;
//                if($v['win_total'] > 0){
//                    $userMoney = $user['money'] - $v['win_total'] + $winTotal;
//                }elseif($v['win_total'] < 0){
                    $userMoney = $user['money'] - $v['win_total'] + $winTotal;
//                }else{
//                    $userMoney = $user['money'] + $winTotal;
//                }
                User::where(['id' => $v['user_id']])->update(['money' => $userMoney]);
                $updateBet = array(
                    'result' => $event['opening'],
                    'end_money' => $v['money_after_bet'] + $winTotal,
                    'win_total' => $winTotal,
                    'is_edit' => 1,
                );
                Bet::where(['id' => $v['id']])->update($updateBet);
                /* 处理洗码及占股 */
                $agent = explode(',', $user['agent_parent_id_path']);
                $generalAgent = User::get(intval($agent[0]));
                $betXimalv = $generalAgent['agent_ximalv_dt'];
                $betMaliang = round(($ximaliang * $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;
                        $ximalv = $userPathInfo['agent_ximalv_dt'];
                        $type = $key == 0 ? 1 : 0;
                        $netZhangulv = round(($userPathInfo['agent_cs'] / 100 - $nextZhanGulv),2);
                        if($tableInfo['is_xima'] == 1 && $ximaliang > 0){
                            $maliang = round(($ximaliang * $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' => $user['agent_parent_id_path'],
                                'user_id' => $value,
                                'bet_user_id' => $user['id'],
                                'bet_id' => $v['id'],
                                'game_id' => $v['game_id'],
                                'table_id' => $v['table_id'],
                                'game_name' => $v['game_name'],
                                'table_name' => $v['table_name'],
                                'boot_num' => $v['boot_num'],
                                'number' => $v['number'],
                                'sumday_id' => $v['sumday_id'],
                                'day' => $v['day'],
                                'number_tab_id' => $v['number_tab_id'],
                                'boot_id' => $v['boot_id'],
                                'ximaliang' => $ximaliang,
                                'ximalv' => $ximalv,
                                'maliang' => $maliang,
                                'maliang_true' => $maliangTrue,
                                'total' => $amount,
                                'win_total' => $winTotal,
                                'create_time' => $time,
                                'unify_time' => $v['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 && $v['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();

                                    // 添加用户上分记录
                                    $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' => $ximaliang,
                                        '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' => $user['agent_parent_id_path'],
                            'user_id' => $value,
                            'bet_user_id' => $user['id'],
                            'bet_id' => $v['id'],
                            'game_id' => $v['game_id'],
                            'table_id' => $v['table_id'],
                            'game_name' => $v['game_name'],
                            'table_name' => $v['table_name'],
                            'boot_num' => $v['boot_num'],
                            'number' => $v['number'],
                            'number_tab_id' => $v['number_tab_id'],
                            'boot_id' => $v['boot_id'],
                            'sumday_id' => $v['sumday_id'],
                            'day' => $v['day'],
                            'share_amount' => $shareAmount,
                            'share_amount_true' => $shareAmountTrue,
                            'share_percent' => $userPathInfo['agent_cs'],
                            'total' => $amount,
                            'win_total' => $winTotal,
                            'create_time' => $time,
                            'unify_time' => $v['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' => $user['agent_parent_id_path'],
                                'user_id' => $value,
                                'bet_user_id' => $user['id'],
                                'bet_id' => $v['id'],
                                'game_id' => $v['game_id'],
                                'table_id' => $v['table_id'],
                                'game_name' => $v['game_name'],
                                'table_name' => $v['table_name'],
                                'boot_num' => $v['boot_num'],
                                'number' => $v['number'],
                                'sumday_id' => $v['sumday_id'],
                                'day' => $v['day'],
                                'number_tab_id' => $v['number_tab_id'],
                                'boot_id' => $v['boot_id'],
                                'amount' => $amount,
                                'rebate_amount' => $rebateAmount,
                                'rebate_amount_actual' => $rebateAmountActual,
                                'rebate_rate' => $rebateRate,
                                'create_time' => $time,
                                'unify_time' => $v['unify_time'],
                            );
                            Rebate::create($insertRebate);
                            $nextRebate = $rebateAmountActual + $nextRebate;
                        }
                    }
                }
            }
            $updateNumberTab = array(
                'result' => $event['opening'],
                'result_before_edit' => $numberTabInfo['result'],
            );

            NumberTab::where(['id' => $numberTabInfo['id']])->update($updateNumberTab);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }
}