<?php

namespace App\Http\Controllers\api;

use App\Constants\StepStatus;
use App\Constants\Util;
use App\Exceptions\MessageException;
use App\Http\Controllers\Controller;
use App\Models\Message;
use App\Models\User;
use App\Services\OnLineService;
use App\Services\RecordService;
use App\Services\RoomService;
use App\Services\SettlementService;
use App\Services\TopUpService;
use App\Services\TutorialService;
use App\Services\UserService;
use App\Services\WalletService;
use App\Services\WithdrawService;   
use App\Services\BalanceLogService;   
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Telegram\Bot\Api;
use Telegram\Bot\Exceptions\TelegramSDKException;
use Illuminate\Support\Facades\Log;
use App\Models\Config;
use App\Services\GameplayRuleService;
use App\Services\BetService;
use App\Services\IssueService;

class TelegramWebHook extends Controller
{
    protected $telegram;

    public function __construct(Api $telegram)
    {
        $this->telegram = $telegram;
    }

    public function handle(Request $request)
    {
        Log::error('Telegram 日志写入测试: ' . json_encode([$request->ip()], JSON_UNESCAPED_UNICODE));
        // try {
            $m = new Message();
            $m->json = $request->ip();
            $m->save();
            $telegram = new Api(config('services.telegram.token'));
        // } catch (TelegramSDKException $e) {
        //     return response()->json(['status' => 'ok']);
        // }
        $update = $telegram->getWebhookUpdate(); // 获取更新数据
        $update->callbackQuery;
        if ($update->has('callback_query')) {
            $json['type'] = 'callback_query';
            $callbackQuery = $update->callbackQuery;
            $json['update'] = $callbackQuery;
            $message = $callbackQuery->message;
            $from = $callbackQuery->from;
            $data = $callbackQuery->data; // 获取 callback_data
            $callbackId = $callbackQuery->id; // 获取 callback_query 的 ID
            $m = new Message();
            $m->json = $data;
            $m->save();
            Util::delCache($message->chat->id);
            Log::error('Telegram 回调数据(JSON): ' . json_encode($update, JSON_UNESCAPED_UNICODE));

             DB::beginTransaction();
            try {
                $chatId = $message->chat->id;
                $firstName = $message->chat->firstName;
                $messageId = $message->messageId;
                if (!$from->isBot) {
                    $chatId = $from->id;
                    $firstName = $from->firstName;
                }

                $user = User::where('member_id', $chatId)->first();
                if (!$user) {
                    $user = new User();
                    $user->member_id = $chatId;
                }
                $user->first_name = $firstName;
                $user->save();
                //给每个用户生成一个专属的USDT钱包
                WalletService::getUserWallet($chatId);

                
                // 查看余额弹窗
                if($data === 'balanceAlert'){
                    $alertText = WalletService::getBalance($chatId)['text'];
                    WalletService::alertNotice($callbackId , $alertText);
                }
                // 今日流水弹窗
                if($data === 'todayFlowAlert'){
                    $alertText = BalanceLogService::getTodayFlowing($chatId)['text'];
                    BalanceLogService::alertNotice($callbackId , $alertText);
                }
                // 近期注单弹窗
                if($data === 'betsAlert'){
                    $alertText = BetService::recentlyRecord($chatId);
                    BetService::alertNotice($callbackId , $alertText);
                }

                                //点击充值按钮
                if ($data === 'topup@@topup') {
                    $telegram->deleteMessage([
                        'chat_id' => $chatId,
                        'message_id' => $messageId,
                    ]);
                    $topService = new TopUpService();
                    $res = $topService->scan($chatId, $messageId);
                    $telegram->sendPhoto($res);
                }

                //点击充值的账单按钮
                if ($data === 'topup@@bill') {
                    $res = (new TopUpService())->bill($chatId, $firstName, $messageId);
                    $telegram->editMessageText($res);


//                    $text = "📅 请输入查询日期\n";
//                    $date = date('Y-m-d');
//                    $text .= "例如您要查询的日期 {$date}\n";
//                    $text .= "那么请发送：【充值账单】{$date}\n";
//                    $telegram->sendMessage([
//                        'chat_id' => $chatId,
//                        'text' => $text
//                    ]);
                }

                                //点击我已付款按钮
                //手动充值(后台审核后到账)
                if ($data === 'topUp@@pay2') {
                    $telegram->deleteMessage([
                        'chat_id' => $chatId,
                        'message_id' => $messageId
                    ]);
                    $res = TopUpService::pay2($chatId);
                    $telegram->sendMessage($res);
                } //
                //自动充值
                elseif ($data === 'topUp@@pay') {
                    $telegram->deleteMessage([
                        'chat_id' => $chatId,
                        'message_id' => $messageId
                    ]);
                    $topService = new TopUpService();
                    $res = $topService->done($chatId);
                    $telegram->sendMessage($res);
                }

                //充值账单，下一页
                $pattern = "/^topUpBillNextPage@@\d+$/";
                if (preg_match($pattern, $data)) {
                    $page = preg_replace('/^topUpBillNextPage@@/', '', $data);
                    $page = intval($page);
                    $res = (new TopUpService())->bill($chatId, $firstName, $messageId, $page);
                    $telegram->editMessageText($res);
                }

                

                //提现账单，下一页
                $pattern = "/^withdrawBillNextPage@@\d+$/";
                if (preg_match($pattern, $data)) {
                    $page = preg_replace('/^withdrawBillNextPage@@/', '', $data);
                    $page = intval($page);
                    $res = (new WithdrawService())->bill($chatId, $firstName, $messageId, $page);
                    $telegram->editMessageText($res);
                }

                //近期注单，下一页
                $pattern = "/^betRecordNextPage@@\d+$/";
                if (preg_match($pattern, $data)) {
                    $page = preg_replace('/^betRecordNextPage@@/', '', $data);
                    $page = intval($page);
                    $res = BetService::record($chatId ,$messageId ,$page );
                    $telegram->editMessageText($res);
                }
                 DB::commit();
            } //
            catch (MessageException $e) {
                DB::rollBack();
                $msg = $e->getMessage();
                $msg = json_decode($msg, true);
                $telegram->sendMessage($msg);
            } //
            catch (TelegramSDKException $e) {
                DB::rollBack();
                $m = new Message();
                $m->json = $e->getMessage();
                $m->save();
                $telegram->sendMessage([
                    'chat_id' => $chatId,
                    'text' => '‼️‼️系统发生了错误，请联系客服'
                ]);
            }//
            catch (\Exception $e) {
                DB::rollBack();
                $m = new Message();
                $m->json = json_encode([
                    'line' => $e->getLine(),
                    'message' => $e->getMessage()
                ]);
                $m->save();
                $telegram->sendMessage([
                    'chat_id' => $chatId,
                    'text' => '‼️‼️系统发生了错误，请联系客服'
                ]);
            }

        }else {
            $update = $request->all();
            Log::error('Telegram 文字消息回复: ' . json_encode($update, JSON_UNESCAPED_UNICODE));
            if (isset($update['message'])) {
                $message = $update['message'];
                $chatId = $message['chat']['id'];
                $messageId = $message['message_id'];
                DB::beginTransaction();
                try {
                    $m = new Message();
                    $m->json = json_encode($update);
                    $m->save();

                    $returnMsg = $this->processChatMessage($chatId, $messageId, $message, $message['from']);
                    if($returnMsg){
                        $this->telegram->sendMessage($returnMsg);
                    }
                    DB::commit();
                } 
                 catch (MessageException $e) {
                    DB::rollBack();
                    $msg = $e->getMessage();
                    $msg = json_decode($msg, true);
                    $telegram->sendMessage($msg);
                } //
                catch (TelegramSDKException $e) {
                    DB::rollBack();
                    $m = new Message();
                    $m->json = $e->getMessage();
                    $m->save();
                    $telegram->sendMessage([
                        'chat_id' => $chatId,
                        'text' => '‼️‼️系统发生了错误，请联系客服'
                    ]);
                }//
                catch (\Exception $e) {
                    DB::rollBack();
                    $m = new Message();
                    $m->json = json_encode([
                        'line' => $e->getLine(),
                        'message' => $e->getMessage()
                    ]);
                    $m->save();
                    Log::error('Telegram 处理消息异常: ' . $e->getMessage());
                    $telegram->sendMessage([
                        'chat_id' => $chatId,
                        'text' => '‼️‼️系统发生了错误，请联系客服'
                    ]);
                }
            }

        }
        return response()->json(['status' => 'ok']);
    }

    /**
     * @description: 处理聊天消息
     * @param {*} $chatId
     * @param {*} $messageId
     * @param {*} $message
     * @param {*} $from
     * @return {*}
     */    
    public function processChatMessage($chatId, $messageId, $message, $from)
    {
        $returnMsg = [];
        //用户发送图片,结算截图
        if (isset($message['photo'])) {
            $stepStatus = Cache::get(get_step_key($chatId), -1);
            $stepStatus = intval($stepStatus);
            // //结算截图
            // if ($stepStatus === StepStatus::INPUT_IMAGE) {
            //     $photo = $message['photo'][count($message['photo']) - 1];
            //     $res = (new SettlementService())->photo($photo, $chatId);
            //     if ($res) $telegram->sendMessage($res);
            // }//
            // //充值截图
            // else if ($stepStatus === StepStatus::INPUT_TOP_UP_IMAGE) {
            //     $photo = $message['photo'][count($message['photo']) - 1];
            //     $res = TopUpService::photo($chatId, $photo);
            //     if (isset($res['message_id'])) $telegram->editMessageText($res);
            //     else $telegram->sendMessage($res);
            // }

        } //用户发送了消息
        else if (isset($message['text'])) {
            $text = $message['text'];
            if ($message['chat']['type'] === 'private') {
                switch ($text) {
                    case "/start":
                        Util::delCache($chatId);
                        $user = User::where('member_id', $chatId)->first();
                        if (!$user) {
                            $user = new User();
                            $user->member_id = $chatId;
                        }
                        $user->first_name = $message['chat']['first_name'];
                        $user->save();
                        //给每个用户生成一个专属的USDT钱包
                        WalletService::getUserWallet($chatId);

                        $username = config('services.telegram.username');
                        $this->setReplyKeyboard($chatId);
                        break;
                    case "近期注单":
                        Util::delCache($chatId);
                        $returnMsg = BetService::record($chatId);
                        // $this->telegram->sendMessage([
                        //     'chat_id' => $chatId,
                        //     'text' => $text
                        // ]);
                        break;
                    case "今日流水":
                        Util::delCache($chatId);
                        $returnMsg = BalanceLogService::getTodayFlowing($chatId);
                        // $this->telegram->sendMessage($result);
                        break;
                    case "联系客服":
                        Util::delCache($chatId);
                        $receivingAddress = Config::where('field', 'receiving_address')->first()->val;
                        $serviceAccount = Config::where('field', 'service_account')->first()->val;
                        $text = "官方唯一上分地址：\n";
                        $text .= "USDT: \n";
                        $text .= "{$receivingAddress}\n\n\n";
                        $text .= "‼️特别注意‼️特别注意‼️\n";
                        $text .= "‼️近期骗子肆意妄为，猖狂狡诈。经常冒充我方财务，管理人员以各种手段行使诈骗之术。多数为要求转账/提供验证码等。任何主动私聊您的都是非奸即盗。望各位老板谨记，预防受骗！\n";
                        $text .= "‼️本群管理以及财务绝不会主动私聊客户。请各位老板务必认准群内带标识管理账号，转账前务必核对是否官方账号以及地址。任何一切不是官方行为的受骗上当，本群概不负责，谢谢！\n";
                        $text .= "‼️为了您的资金安全，下分更换地址请提前告知财务，并使用原地址进行转账或录屏进行身份核实，核实为本人操作后才可进行更换地址下分\n";
                        $text .= "‼️如查分金额与实际转账金额不同，请重新喊查。玩家重复查3次以上错误金额则视为恶意捣乱，将不退还转账金额！\n";
                        $text .= "‼️如因为人为失误问题，到账金额与玩家实际转账金额不符，到账后的一切下注视为无效。\n";
                        $text .= "‼️本群不接待以任何形式刷水的水军，一经发现玩家存在刷水行为将扣除历史所有返水、彩金。并冻结分数一个月，每天仅可下分账户余额10%。不纠结，不解释，请各大水军自行绕道。\n";
                        $keyboard = [];
                        $keyboard[] = [['text' => '✅ 唯一客服', 'callback_data' => "", 'url' => "https://t.me/{$serviceAccount}"]];
                        $returnMsg = [
                            'chat_id' => $chatId,
                            'text' => $text,
                            'reply_markup' => json_encode(['inline_keyboard' => $keyboard])
                        ];
                        break;
                    case "开奖历史":
                        Util::delCache($chatId);
                        IssueService::currentLotteryResults($chatId);
                        break;
                    case "当期下注":
                        Util::delCache($chatId);
                        $returnMsg = BetService::currentBet($chatId);
                        break;
                    case "查看余额":
                        Util::delCache($chatId);
                        $returnMsg = WalletService::getBalance($chatId);

                        // $this->telegram->sendMessage($result);
                        break;
                    case "投注大群":
                        Util::delCache($chatId);

                        $bettingGroup = Config::where('field', 'betting_group')->first()->val;

                        $text = "👇👇👇点击下方按钮进群投注👇👇👇\n";
                        $keyboard = [];
                        $keyboard[] = [['text' => '✅ 投注群', 'callback_data' => "", 'url' => "https://t.me/{$bettingGroup}"]];
                        $returnMsg = [
                            'chat_id' => $chatId,
                            'text' => $text,
                            'reply_markup' => json_encode(['inline_keyboard' => $keyboard])
                        ];
                        break;
                    default:

                        $returnMsg = BetService::bet($chatId,$text,$messageId);
                        // $this->telegram->sendMessage($returnMsg);
                }

                return $returnMsg;
            }
        }
    }

    /**
     * @description: 设置 start 回复菜单
     * @param {*} $chatId
     * @return {*}
     */    
    public function setReplyKeyboard($chatId)
    {
        $telegram = new Api(config('services.telegram.token'));

        $keyboard = [
            ['近期注单', '今日流水', '联系客服'], // 第一排按钮
            ['开奖历史', '当期下注', '查看余额'],    // 第二排按钮
            ['投注大群']
        ];

        $replyMarkup = [
            'keyboard' => $keyboard,
            'resize_keyboard' => true,    // 自适应大小
            'one_time_keyboard' => false, // 保持显示，不会点击后收起
        ];

        $telegram->sendMessage([
            'chat_id' => $chatId,
            'text' => '你好，请选择功能菜单',
            'reply_markup' => json_encode($replyMarkup),
        ]);
    }


    public function handleMessage(Request $request)
    {

        $telegram = new Api(config('services.telegram.token'));
        $update = $telegram->getWebhookUpdate(); // 获取更新数据
        $update->callbackQuery;
        if ($update->has('callback_query')) {

            $json['type'] = 'callback_query';
            $callbackQuery = $update->callbackQuery;
            $json['update'] = $callbackQuery;
            $message = $callbackQuery->message;
            $from = $callbackQuery->from;
            $data = $callbackQuery->data; // 获取 callback_data
            $callbackId = $callbackQuery->id; // 获取 callback_query 的 ID
            $m = new Message();
            $m->json = $data;
            $m->save();
            Util::delCache($message->chat->id);
            DB::beginTransaction();
            try {
                $chatId = $message->chat->id;
                $firstName = $message->chat->firstName;
                $messageId = $message->messageId;
                if (!$from->isBot) {
                    $chatId = $from->id;
                    $firstName = $from->firstName;
                }

                $user = User::where('member_id', $chatId)->first();
                if (!$user) {
                    $user = new User();
                    $user->member_id = $chatId;
                }
                $user->first_name = $firstName;
                $user->save();
                //给每个用户生成一个专属的USDT钱包
                WalletService::getUserWallet($chatId);

                // 查看余额弹窗
                if($data === 'balanceAlert'){
                    Log::error('查看余额弹窗 balanceAlert: ' . $callbackId);
                    // $alertText = WalletService::getBalance($chatId)['text'];
                    WalletService::alertNotice($callbackId , '您好，您的余额为：');
                }

                //取消创建游戏
                if ($data === "games@@cancel") {
                    $roomService = new RoomService($telegram);
                    $res = $roomService->cancel($chatId, $messageId);
                    $telegram->editMessageText($res);
                }

                if ($data === 'withdrawAddress@@done') {
                    $res = WithdrawService::done($chatId, $messageId, $firstName);
                    $telegram->editMessageText($res);
                }

                //选择提现地址
                $pattern = "/^withdrawAddress@@choose\d+$/";
                if (preg_match($pattern, $data)) {
                    $id = preg_replace('/^withdrawAddress@@choose/', '', $data);
                    $res = WithdrawService::chooseAddress($chatId, $firstName, $messageId, $id);
                    $telegram->editMessageText($res);
                }

                //删除地址
                $pattern = "/^withdrawAddress@@del\d+$/";
                if (preg_match($pattern, $data)) {
                    $id = preg_replace('/^withdrawAddress@@del/', '', $data);
                    $res = WithdrawService::delAddress($chatId, $id, $messageId);
                    $telegram->editMessageText($res);
                }
                //地址详情
                $pattern = "/^withdrawAddress@@detail\d+$/";
                if (preg_match($pattern, $data)) {
                    $id = preg_replace('/^withdrawAddress@@detail/', '', $data);
                    $res = WithdrawService::addressDetails($chatId, $messageId, $id);
                    $telegram->editMessageText($res);
                }
                //教程帮助
                $pattern = "/^Tutorial@@\d+$/";
                if (preg_match($pattern, $data)) {
                    $index = preg_replace('/^Tutorial@@/', '', $data);
                    $res = TutorialService::help($chatId, $index, $messageId);
                    $telegram->editMessageText($res);
                }
                if ($data === 'Tutorial@@home') {
                    $res = (new TutorialService())->index($chatId);
                    $res['message_id'] = $messageId;
                    $telegram->editMessageText($res);
                }


                //游戏房间首页
                $pattern = "/^games@@home\d+$/";
                if (preg_match($pattern, $data)) {
                    $roomId = preg_replace('/^games@@home/', '', $data);
                    $res = (new RoomService($telegram))->gameHome($roomId, $chatId, $messageId);
                    $m = new Message();
                    $m->json = json_encode($res);
                    $m->save();
                    $telegram->editMessageText($res);
                }

                //选择游戏
                $pattern = "/^inputGameName@@.+$/";
                if (preg_match($pattern, $data)) {
                    $gameName = preg_replace('/^inputGameName@@/', '', $data);
                    $roomService = new RoomService($telegram);
                    $res = $roomService->setGameName($chatId, $gameName, $messageId);
                    if (isset($res['message_id'])) $telegram->editMessageText($res);
                    else $telegram->sendMessage($res);
                }

                //选择中途加入
                $pattern = "/^setGameMidway@@.+$/";
                if (preg_match($pattern, $data)) {
                    $midway = preg_replace('/^setGameMidway@@/', '', $data);
                    $roomService = new RoomService($telegram);
                    $res = $roomService->setGameMidway($chatId, $midway, $messageId);
                    if (isset($res['message_id'])) $telegram->editMessageText($res);
                    else $telegram->sendMessage($res);
                }

                //确认游戏ID
                $pattern = "/^inputGameID@@\d+$/";
                if (preg_match($pattern, $data)) {
                    $gameId = preg_replace('/^inputGameID@@/', '', $data);
                    $rs = new RoomService($telegram);
                    $res = $rs->setGameID($chatId, $gameId, $messageId);
                    foreach ($res as $r) {
                        if (isset($r['message_id'])) {
                            $telegram->editMessageText($r);
                        } else {
                            $telegram->sendMessage($r);
                        }
                    }

                }

                //房间低分
                $pattern = '/^roomMin@@.*/';
                if (preg_match($pattern, $data)) {
                    $roomService = new RoomService($telegram);
                    $res = $roomService->setMin($data, $chatId, $messageId);
                    if (isset($res['message_id'])) {
                        $telegram->editMessageText($res);
                    } else {
                        $telegram->sendMessage($res);
                    }
                }

                //删除本条数据
                if ($data === 'del@@message') {
                    $telegram->deleteMessage([
                        'chat_id' => $chatId,
                        'message_id' => $messageId,
                    ]);
                }

                //确认创建房间
                if ($data === 'room@@done') {
                    $roomService = new RoomService($telegram);
                    $res = $roomService->done($chatId, $messageId);
                    foreach ($res as $r) {
                        if (isset($r['message_id'])) {
                            $telegram->editMessageText($r);
                        } else {
                            $telegram->sendMessage($r);
                        }
                    }


                }

                //客服帮助
                if ($data === "/tutorial") {
                    $res = (new TutorialService())->index($chatId);
                    $telegram->sendMessage($res);
                }

                //点击提现按钮
                if ($data === "withdraw@@apply") {
                    $res = (new WithdrawService())->apply($chatId, $messageId);
                    $telegram->editMessageText($res);
                }

                //地址管理
                if ($data === 'withdraw@@address') {
                    $res = WithdrawService::getAddress($chatId, $messageId);
                    $telegram->editMessageText($res);
                }

                //点击充值按钮
                if ($data === 'topup@@topup') {
                    $telegram->deleteMessage([
                        'chat_id' => $chatId,
                        'message_id' => $messageId,
                    ]);
                    $topService = new TopUpService();
                    $res = $topService->scan($chatId, $messageId);
                    $telegram->sendPhoto($res);
                }

                //点击充值的账单按钮
                if ($data === 'topup@@bill') {
                    $res = (new TopUpService())->bill($chatId, $firstName, $messageId);
                    $telegram->editMessageText($res);


//                    $text = "📅 请输入查询日期\n";
//                    $date = date('Y-m-d');
//                    $text .= "例如您要查询的日期 {$date}\n";
//                    $text .= "那么请发送：【充值账单】{$date}\n";
//                    $telegram->sendMessage([
//                        'chat_id' => $chatId,
//                        'text' => $text
//                    ]);
                }

                //关闭本条消息
                if ($data === 'message@@close') {
                    $telegram->deleteMessage([
                        'chat_id' => $chatId,
                        'message_id' => $messageId
                    ]);
                }

                if ($data === 'withdrawAddress@@add') {
                    $res = WithdrawService::addAddress($chatId, $messageId);
                    $telegram->editMessageText($res);
                }

                //提现管理
                if ($data === "withdraw@@home") {
                    $res = WithdrawService::index($chatId, $firstName, $messageId);
                    $telegram->editMessageText($res);
                }

                //点击提现的账单按钮
                if ($data === "withdraw@@bill") {
                    $res = (new WithdrawService())->bill($chatId, $firstName, $messageId);
                    $telegram->editMessageText($res);
//                    $telegram->sendMessage($res);
//                    $text = "📅 请输入查询日期\n";
//                    $date = date('Y-m-d');
//                    $text .= "例如您要查询的日期 {$date}\n";
//                    $text .= "那么请发送：【提现账单】{$date}\n";
//                    $telegram->sendMessage([
//                        'chat_id' => $chatId,
//                        'text' => $text
//                    ]);
                }

                //充值首页
                if ($data === "topUp@@home" || $data === "topUp@@home1") {
                    $res = (new TopUpService())->index($chatId, $firstName, $messageId);
                    if ($data === "topUp@@home1") {
                        $telegram->deleteMessage([
                            'chat_id' => $chatId,
                            'message_id' => $messageId
                        ]);
                        $telegram->sendMessage($res);
                    } else {
                        $telegram->editMessageText($res);
                    }
                }


                //点击我已付款按钮
                //手动充值(后台审核后到账)
                if ($data === 'topUp@@pay2') {
                    $telegram->deleteMessage([
                        'chat_id' => $chatId,
                        'message_id' => $messageId
                    ]);
                    $res = TopUpService::pay2($chatId);
                    $telegram->sendMessage($res);
                } //
                //自动充值
                elseif ($data === 'topUp@@pay') {
                    $telegram->deleteMessage([
                        'chat_id' => $chatId,
                        'message_id' => $messageId
                    ]);
                    $topService = new TopUpService();
                    $res = $topService->done($chatId);
                    $telegram->sendMessage($res);
                }

                //充值账单，下一页
                $pattern = "/^topUpBillNextPage@@\d+$/";
                if (preg_match($pattern, $data)) {
                    $page = preg_replace('/^topUpBillNextPage@@/', '', $data);
                    $page = intval($page);
                    $res = (new TopUpService())->bill($chatId, $firstName, $messageId, $page);
                    $telegram->editMessageText($res);
                }

                

                //提现账单，下一页
                $pattern = "/^withdrawBillNextPage@@\d+$/";
                if (preg_match($pattern, $data)) {
                    $page = preg_replace('/^withdrawBillNextPage@@/', '', $data);
                    $page = intval($page);
                    $res = (new WithdrawService())->bill($chatId, $firstName, $messageId, $page);
                    $telegram->editMessageText($res);
                }

                //提前开始游戏
                $pattern = "/^games@@start\d+$/";
                if (preg_match($pattern, $data)) {
                    $roomId = preg_replace('/^games@@start/', '', $data);
                    $roomService = new RoomService($telegram);
                    $res = $roomService->start($chatId, $roomId, $messageId);
                    foreach ($res as $r) {
                        if (isset($r['message_id'])) {
                            $telegram->editMessageText($r);
                        } else {
                            $telegram->sendMessage($r);
                        }
                    }
                }

                //解散房间
                $pattern = "/^games@@Disband\d+$/";
                if (preg_match($pattern, $data)) {
                    $roomService = new RoomService($telegram);
                    $roomId = preg_replace('/^games@@Disband/', '', $data);
                    $res = $roomService->disband($roomId, $chatId, $messageId);
                    foreach ($res as $r) {
                        if (isset($r['message_id'])) {
                            $telegram->editMessageText($r);
                        } else {
                            $telegram->sendMessage($r);
                        }
                    }
                }

                //退出房间
                $pattern = "/^games@@exit\d+$/";
                if (preg_match($pattern, $data)) {
                    $roomService = new RoomService($telegram);
                    $res = $roomService->exit($data, $chatId, $messageId);
                    if (isset($res['message_id'])) $telegram->editMessageText($res);
                    else $telegram->sendMessage($res);
                }

                //人员/状态
                $pattern = "/^games@@status\d+$/";
                if (preg_match($pattern, $data)) {
                    $roomId = preg_replace('/^games@@status/', '', $data);
                    $roomService = new RoomService($telegram);
                    $res = $roomService->userStatus($roomId, $chatId, $messageId);
                    if (isset($res['message_id'])) $telegram->editMessageText($res);
                    else $telegram->sendMessage($res);
                }

                //准备
                $pattern = "/^games@@ready\d+$/";
                if (preg_match($pattern, $data)) {
                    $roomId = preg_replace('/^games@@ready/', '', $data);
                    $res = (new RoomService($telegram))->ready($roomId, $chatId, $messageId);
                    foreach ($res as $r) {
                        if (isset($r['message_id'])) {
                            $telegram->editMessageText($r);
                        } else {
                            $telegram->sendMessage($r);
                        }
                    }
                }

                //结算游戏
                $pattern = "/^games@@settle\d+$/";
                if (preg_match($pattern, $data)) {
                    $roomId = preg_replace('/^games@@settle/', '', $data);
                    $res = (new SettlementService())->settle($roomId, $chatId, $messageId);
                    if (isset($res['message_id'])) $telegram->editMessageText($res);
                    else $telegram->sendMessage($res);
                }

                //在线房间，下一页
                $pattern = "/^onlineNextPage@@\d+$/";
                if (preg_match($pattern, $data)) {
                    $page = preg_replace('/^onlineNextPage@@/', '', $data);
                    $page = intval($page);
                    $res = (new OnLineService())->getList($chatId, $messageId, $page);
                    $telegram->editMessageText($res);
                }

                //我的战绩，下一页
                $pattern = "/^recordNextPage@@\d+$/";
                if (preg_match($pattern, $data)) {
                    $page = preg_replace('/^recordNextPage@@/', '', $data);
                    $page = intval($page);
                    $res = (new RecordService())->getList($chatId, $firstName, $messageId, $page);
                    $telegram->editMessageText($res);
                }

                //加入房间
                $pattern = "/^join@@\d+$/";
                if (preg_match($pattern, $data)) {
                    $roomId = preg_replace('/^join@@/', '', $data);
                    $res = (new RoomService($telegram))->join($chatId, $roomId, $messageId);
                    foreach ($res as $r) {
                        if (isset($r['message_id'])) {
                            $telegram->editMessageText($r);
                        } else {
                            $telegram->sendMessage($r);
                        }
                    }
                }

                //输入房间号加入房间
                if ($data === 'join@@room') {
                    $res = OnLineService::joinRoom($chatId, $messageId);
                    $telegram->editMessageText($res);
                }

                //通过频道加入房间
                $pattern = "/^channelJoin@@\d+$/";
                if (preg_match($pattern, $data)) {
                    $roomId = preg_replace('/^channelJoin@@/', '', $data);
                    $res = (new RoomService($telegram))->join($from->id, $roomId);
                    foreach ($res as $r) {
                        if (isset($r['message_id'])) {
                            $telegram->editMessageText($r);
                        } else {
                            $telegram->sendMessage($r);
                        }
                    }
                }


                DB::commit();
            } //
            catch (MessageException $e) {
                DB::rollBack();
                $msg = $e->getMessage();
                $msg = json_decode($msg, true);
                $telegram->sendMessage($msg);
            } //
            catch (TelegramSDKException $e) {
                DB::rollBack();
                $m = new Message();
                $m->json = $e->getMessage();
                $m->save();
                $telegram->sendMessage([
                    'chat_id' => $chatId,
                    'text' => '‼️‼️系统发生了错误，请联系客服'
                ]);
            }//
            catch (\Exception $e) {
                DB::rollBack();
                $m = new Message();
                $m->json = json_encode([
                    'line' => $e->getLine(),
                    'message' => $e->getMessage()
                ]);
                $m->save();
                $telegram->sendMessage([
                    'chat_id' => $chatId,
                    'text' => '‼️‼️系统发生了错误，请联系客服'
                ]);
            }
        } //
        else {
            $update = $request->all();
            if (isset($update['message'])) {
                $message = $update['message'];
                $chatId = $message['chat']['id'];
                $messageId = $message['message_id'];
                DB::beginTransaction();
                try {
                    $m = new Message();
                    $m->json = json_encode($update);
                    $m->save();

                    $user = User::where('member_id', $chatId)->first();
                    if (!$user) {
                        $user = new User();
                        $user->member_id = $chatId;
                    }
                    $user->first_name = $message['chat']['first_name'];
                    $user->save();
                    //给每个用户生成一个专属的USDT钱包
                    WalletService::getUserWallet($chatId);


                    //用户发送图片,结算截图
                    if (isset($message['photo'])) {
                        $stepStatus = Cache::get(get_step_key($chatId), -1);
                        $stepStatus = intval($stepStatus);
                        //结算截图
                        if ($stepStatus === StepStatus::INPUT_IMAGE) {
                            $photo = $message['photo'][count($message['photo']) - 1];
                            $res = (new SettlementService())->photo($photo, $chatId);
                            if ($res) $telegram->sendMessage($res);
                        }//
                        //充值截图
                        else if ($stepStatus === StepStatus::INPUT_TOP_UP_IMAGE) {
                            $photo = $message['photo'][count($message['photo']) - 1];
                            $res = TopUpService::photo($chatId, $photo);
                            if (isset($res['message_id'])) $telegram->editMessageText($res);
                            else $telegram->sendMessage($res);
                        }

                    } //用户发送了消息
                    else if (isset($message['text'])) {
                        $text = $message['text'];
                        if ($message['chat']['type'] === 'private') {
                            switch ($text) {
                                //教程帮助
                                case "/tutorial":
                                    Util::delCache($chatId);
                                    $res = (new TutorialService())->index($chatId);
                                    $telegram->sendMessage($res);
                                    break;
                                //提现管理
                                case "/withdraw":
                                    Util::delCache($chatId);
                                    $res = WithdrawService::index($chatId, $message['chat']['first_name']);
                                    $telegram->sendMessage($res);
                                    break;
                                //我的战绩
                                case "/record":
                                    Util::delCache($chatId);
                                    $res = (new RecordService())->getList($chatId, $message['chat']['first_name']);
                                    $telegram->sendMessage($res);
                                    break;
                                //充值管理
                                case "/topup":
                                    Util::delCache($chatId);
                                    $res = (new TopUpService())->index($chatId, $message['chat']['first_name']);
                                    $telegram->sendMessage($res);
                                    break;
                                //在线房间
                                case"/online":
                                    Util::delCache($chatId);
                                    $data = (new OnLineService())->getList($chatId, null, 1);
                                    $telegram->sendMessage($data);
                                    break;
                                //创建房间
                                case "/room":
                                    Util::delCache($chatId);
                                    $roomService = new RoomService($telegram);
                                    $res = $roomService->create($chatId);
                                    $telegram->sendMessage($res);
                                    break;
                                case "/start":
                                    Util::delCache($chatId);
                                    $user = User::where('member_id', $chatId)->first();
                                    if (!$user) {
                                        $user = new User();
                                        $user->member_id = $chatId;
                                    }
                                    $user->first_name = $message['chat']['first_name'];
                                    $user->save();
                                    //给每个用户生成一个专属的USDT钱包
                                    WalletService::getUserWallet($chatId);

                                    $username = config('services.telegram.username');
                                    $telegram->sendMessage(['chat_id' => $chatId, 'text' => "🎉欢迎使用 @{$username}"]);
                                    break;
                                default:
                                    $stepStatus = Cache::get(get_step_key($chatId), -1);
                                    $stepStatus = intval($stepStatus);
                                    switch ($stepStatus) {
                                        case StepStatus::INPUT_GAME_INTRODUCTION:
                                            $res = (new RoomService($telegram))->setIntroduction($chatId, $text, $messageId);
                                            if (isset($res['message_id'])) $telegram->editMessageText($res);
                                            else $telegram->sendMessage($res);
                                            break;
                                        case StepStatus::INPUT_TOP_UP_MONEY:
                                            $res = TopUpService::inputAmount($chatId, $text, $messageId);
                                            if (isset($res['message_id'])) $telegram->editMessageText($res);
                                            else $telegram->sendMessage($res);
                                            break;
                                        case StepStatus::INPUT_JOIN_ROOM_ID:
                                            $res = OnLineService::join($chatId, $text, $messageId);
                                            foreach ($res as $r) {
                                                if (isset($r['message_id'])) $telegram->editMessageText($r);
                                                else $telegram->sendMessage($r);
                                            }
                                            break;
                                        case StepStatus::INPUT_ADDRESS_ALIAS:
                                            $res = WithdrawService::inputAlias($chatId, $text, $messageId);
                                            $telegram->sendMessage($res);
                                            break;
                                        case StepStatus::INPUT_ADDRESS_TRC20:
                                            $res = WithdrawService::inputAddress($chatId, $text, $messageId);
                                            $telegram->sendMessage($res);
                                            break;
                                        case StepStatus::INPUT_WITHDRAW_MONEY:
                                            $res = (new WithdrawService())->inputAmount($chatId, $text, $messageId);
                                            foreach ($res as $r) $telegram->sendMessage($r);
                                            break;
                                        case StepStatus::INPUT_TOP_UP_IMAGE:
                                            $telegram->sendMessage([
                                                'chat_id' => $chatId,
                                                'text' => "输入错误，请上传充值截图！",
                                                'reply_to_message_id' => $messageId
                                            ]);
                                            break;
                                        case StepStatus::INPUT_IMAGE:
                                            $telegram->sendMessage([
                                                'chat_id' => $chatId,
                                                'text' => "输入错误，请上传战绩截图！",
                                                'reply_to_message_id' => $messageId
                                            ]);
                                            break;
                                        //输入结算分数
                                        case StepStatus::INPUT_SCORE:
                                            $res = (new SettlementService())->submitSettle($chatId, $text, $messageId);
                                            foreach ($res['data'] as $r) $telegram->sendMessage($r);
                                            break;
                                        //输入游戏名称
                                        case StepStatus::INPUT_GAME_NAME:
                                            $gameName = $text;
                                            $roomService = new RoomService($telegram);
                                            $res = $roomService->setGameName($chatId, $gameName, $messageId);
                                            if (isset($res['message_id'])) $telegram->editMessageText($res);
                                            else $telegram->sendMessage($res);
                                            break;
                                        //输入房间号
                                        case StepStatus::INPUT_ROOM_ID:
                                            $roomId = $text;
                                            $roomService = new RoomService($telegram);
                                            $res = $roomService->setNum($chatId, $roomId, $messageId);
                                            if (isset($res['message_id'])) $telegram->editMessageText($res);
                                            else $telegram->sendMessage($res);
                                            break;
                                        //输入是否允许中途加入
                                        case StepStatus::INPUT_MIDWAY:
                                            $midway = $text;
                                            $roomService = new RoomService($telegram);
                                            $res = $roomService->setGameMidway($chatId, $midway, $messageId);
                                            if (isset($res['message_id'])) $telegram->editMessageText($res);
                                            else $telegram->sendMessage($res);
                                            break;
                                        //输入 人数/局数
                                        case StepStatus::INPUT_ROOM_NUM:
                                            $array = explode('/', $text);
                                            $roomService = new RoomService($telegram);
                                            $res = $roomService->setNumberOfGames($chatId, $array, $messageId);
                                            if (isset($res['message_id'])) $telegram->editMessageText($res);
                                            else $telegram->sendMessage($res);
                                            break;
                                        //输入 游戏ID
                                        case StepStatus::INPUT_GAME_ID:
                                            $gameId = $text;
                                            $rs = new RoomService($telegram);
                                            $res = $rs->setGameID($chatId, $gameId, $messageId);
                                            foreach ($res as $r) {
                                                if (isset($r['message_id'])) $telegram->editMessageText($r);
                                                else $telegram->sendMessage($r);
                                            }

                                            break;
                                            break;
                                        default:
                                            Util::delCache($chatId);
                                            $res = (new TutorialService())->index($chatId);
                                            $telegram->sendMessage($res);
                                            break;
                                    }
                                    break;
                            }
                        }
                    }
                    DB::commit();
                } //
                catch (MessageException $e) {
                    DB::rollBack();
                    $m = new Message();
                    $m->json = $e->getMessage();
                    $m->save();
                    try {
                        $msg = $e->getMessage();
                        $msg = json_decode($msg, true);
                        $telegram->sendMessage($msg);
                    } catch (TelegramSDKException $e) {
                    }
                } //
                catch (TelegramSDKException $e) {
                    DB::rollBack();
                    $m = new Message();
                    $m->json = $e->getMessage();
                    $m->save();
                    $telegram->sendMessage([
                        'chat_id' => $chatId,
                        'text' => '‼️‼️系统发生了错误，请联系客服'
                    ]);
                }//
                catch (\Exception $e) {
                    DB::rollBack();
                    $m = new Message();
                    $m->json = $e->getMessage();
                    $m->save();
                    $telegram->sendMessage([
                        'chat_id' => $chatId,
                        'text' => '‼️‼️系统发生了错误，请联系客服'
                    ]);
                }
            }

        }
        return response()->json(['status' => 'ok']);
    }
}