<?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\QianBaoWithdrawService;
use App\Services\SanJinRechargeService;
use App\Services\RecordService;
use App\Services\RoomService;
use App\Services\SecretService;
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 Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
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;
use App\Services\KeyboardService;
use Google\Service\Dfareporting\Language;
use Telegram\Bot\FileUpload\InputFile;

class TelegramWebHook extends BaseController
{
    protected Api $telegram;

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

    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();
                App::setLocale($user->language);

                //给每个用户生成一个专属的USDT钱包
                WalletService::getUserWallet($chatId);


                QianBaoWithdrawService::init($telegram, $data, $chatId, $firstName, $messageId);
                SanJinRechargeService::init($telegram, $data, $chatId, $firstName, $messageId);
                SecretService::init($telegram, $data, $chatId, $firstName, $messageId);
                UserService::init($telegram, $data, $chatId, $firstName, $messageId);


                // 查看余额弹窗
                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') {
                    Cache::put('message_id_bet_record_' . $chatId, 0, 600);
                    $alertText = BetService::recentlyRecord($chatId);
                    BetService::alertNotice($callbackId, $alertText);
                }

                //选择充值地址
                if ($data === "topUp@@TRC20" || $data === "topUp@@ERC20") {
                    $type = preg_replace('/^topUp@@/', '', $data);
                    $topService = new TopUpService();
                    $res = $topService->scan($chatId, $messageId, $type);
                    $telegram->deleteMessage([
                        'chat_id' => $chatId,
                        'message_id' => $messageId,
                    ]);
                    $telegram->sendPhoto($res);
                }

                //点击充值按钮
                if ($data === 'topup@@topup') {

                    $res = TopUpService::chooseAddress($chatId, $messageId);
                    $telegram->editMessageText($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);
                }

                //充值首页
                if ($data === "topUp@@home" || $data === "topUp@@home1") {
                    $returnMsg = WalletService::getBalance($chatId);
                    if ($returnMsg) {
                        if ($data === "topUp@@home1") {
                            $telegram->deleteMessage([
                                'chat_id' => $chatId,
                                'message_id' => $messageId
                            ]);
                            $this->telegram->sendMessage($returnMsg);
                        } else {
                            $returnMsg['message_id'] = $messageId;
                            $telegram->editMessageText($returnMsg);
                        }

                    }

                    // $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 === "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 === '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);
                    $telegram->deleteMessage([
                        'chat_id' => $chatId,
                        'message_id' => $messageId
                    ]);
                    $returnMsg = WalletService::getBalance($chatId);
                    if ($returnMsg) {
                        $this->telegram->sendMessage($returnMsg);
                    }
                }

                //点击提现的账单按钮
                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 === 'withdrawAddress@@done') {
                    $res = WithdrawService::done($chatId, $messageId, $firstName);
                    $telegram->editMessageText($res);
                }

                // 今日汇率
                if ($data === 'todayExchangeRate@@rate') {
                    $res = BetService::todayExchangeRate($chatId);
                    // $telegram->sendMessage($res);
                }

                //查看开奖历史图片
                $pattern = "/^showLotteryHistory@@\d+$/";
                if (preg_match($pattern, $data)) {
                    $id = preg_replace('/^showLotteryHistory@@/', '', $data);
                    $res = IssueService::sendLotteryImage($chatId, $id);
                }

                //选择投注记录
                $pattern = "/^betRecordType@@\d+$/";
                if (preg_match($pattern, $data)) {
                    $type = preg_replace('/^betRecordType@@/', '', $data);
                    Cache::put('message_id_bet_record_' . $chatId, intval($type), 600);
                    $telegram->deleteMessage([
                        'chat_id' => $chatId,
                        'message_id' => $messageId,
                    ]);
                    $returnMsg = BetService::record($chatId);
                    $telegram->sendMessage($returnMsg);
                }


                //选择提现地址
                $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 = "/^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 = "/^FlowingHistoryPage@@\d+$/";
                if (preg_match($pattern, $data)) {
                    $page = preg_replace('/^FlowingHistoryPage@@/', '', $data);
                    $page = intval($page);
                    $returnMsg = BalanceLogService::getFlowingHistory($chatId, $messageId, $page);
                    $telegram->editMessageText($returnMsg);
                }


                //提现账单，下一页
                $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) {
                        if (isset($returnMsg['image']) && $returnMsg['image'] != '') {
                            KeyboardService::sendMessage($returnMsg['chat_id'], $returnMsg['text'] ?? '', $returnMsg['keyboard'] ?? [], $returnMsg['image'] ?? '');
                        } else if (isset($returnMsg['photo']) && $returnMsg['photo'] != '') {
                            $this->telegram->sendPhoto($returnMsg);
                        } else {
                            $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);
                return $res;
                // if (isset($res['message_id'])) $telegram->editMessageText($res);
                // else $telegram->sendMessage($res);
            }

        } //用户发送了消息
        else if (isset($message['text'])) {
            $text = $message['text'];

            $user = User::where('member_id', $chatId)->first();
            if (!$user) {
                $user = new User();
                $user->member_id = $chatId;
            }
            $user->first_name = $message['chat']['first_name'];
            if (isset($message['chat']['username'])) {
                $user->username = $message['chat']['username'];
            }
            $user->save();
            App::setLocale($user->language);
            if ($message['chat']['type'] === 'private') {

                // 校验开始菜单事件
                $returnMsg = KeyboardService::checkStart($chatId,$text);
                if($returnMsg){
                    return $returnMsg;
                }


                switch ($text) {
                    case "/start":
                        Util::delCache($chatId);
                        //给每个用户生成一个专属的USDT钱包
                        WalletService::getUserWallet($chatId);
                        self::setReplyKeyboard($chatId,$user->language);
                        break;
                    // case lang("近期注单"):
                    // case lang('"✅近期注单"'):
                    //     Util::delCache($chatId);
                    //     $returnMsg = BetService::record($chatId);
                    //     break;
                    // case lang("今日流水"):
                    // case lang("🔍今日流水"):
                    //     Util::delCache($chatId);
                    //     $returnMsg = BalanceLogService::getTodayFlowing($chatId);
                    //     // $this->telegram->sendMessage($result);
                    //     break;
                    // case lang("流水列表"):
                    // case lang("🔍流水列表"):
                    //     Util::delCache($chatId);
                    //     $returnMsg = BalanceLogService::getFlowingHistory($chatId);
                    //     // $this->telegram->sendMessage($result);
                    //     break;
                    // case lang("联系客服"):
                    //     Util::delCache($chatId);
                    //     $receivingAddress = Config::where('field', 'receiving_address')->first()->val;
                    //     $serviceCustomer = Config::where('field', 'service_customer')->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/{$serviceCustomer}"]];
                    //     $returnMsg = [
                    //         'chat_id' => $chatId,
                    //         'text' => $text,
                    //         'reply_markup' => json_encode(['inline_keyboard' => $keyboard])
                    //     ];
                    //     break;
                    // case lang("开奖历史"):
                    // case lang("📝开奖历史"):
                    //     Util::delCache($chatId);
                    //     IssueService::currentLotteryResults($chatId);
                    //     break;
                    // case lang("当期下注"):
                    // case lang("🔥当期下注"):
                    // case lang("🔥本期下注"):
                    //     Util::delCache($chatId);
                    //     $returnMsg = BetService::currentBet($chatId);
                    //     break;
                    // case lang("选择语言"):
                    //     Util::delCache($chatId);
                    //     $returnMsg = UserService::getLanguages($chatId);
                    //     break;
                    // case lang("查看余额"):
                    // case lang("💰查看余额"):
                    //     Util::delCache($chatId);
                    //     $returnMsg = WalletService::getBalance($chatId);
                    //     break;
                    // case lang("投注大群"):
                    //     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:
                        // 关键字回复
                        $keyboardText = KeyboardService::findOne(['button' => $text]);
                        if ($keyboardText) {
                            $keyboard = [];
                            if ($keyboardText['buttons']) {
                                $keyboard = json_decode($keyboardText['buttons'], true);
                            }
                            Util::delCache($chatId);
                            $res = [
                                'chat_id' => $chatId,
                                'text' => $keyboardText['reply'],
                                // 'reply_to_message_id' => $messageId
                            ];
                            if ($keyboard) {
                                $res['reply_markup'] = json_encode(['inline_keyboard' => $keyboard]);
                            }
                            if ($keyboardText['image']) {
                                $res['photo'] = InputFile::create(url($keyboardText['image']));
                                unset($res['text']);
                                $res['caption'] = $text;
                                $res['protect_content'] = true;  // 防止转发

                            }

                            return $res;
                            break;
                        }

                        $stepStatus = Cache::get(get_step_key($chatId), -1);
                        $stepStatus = intval($stepStatus);
                        $res = QianBaoWithdrawService::onMessage($chatId, $text, $messageId, $stepStatus);
                        if (empty($res)) {
                            $res = SanJinRechargeService::onMessage($chatId, $text, $messageId, $stepStatus);
                        }
                        if (empty($res)) {
                            $res = SecretService::onMessage($chatId, $text, $messageId, $stepStatus);
                        }
                        if (!empty($res)) return $res;
                        switch ($stepStatus) {
                            case StepStatus::INPUT_TOP_UP_MONEY:
                                $res = TopUpService::inputAmount($chatId, $text, $messageId);
                                return $res;
                                break;
                            case StepStatus::INPUT_WITHDRAW_MONEY:
                                $res = (new WithdrawService())->inputAmount($chatId, $text, $messageId);
                                return $res[0];
                                break;

                            case StepStatus::INPUT_ADDRESS_TRC20:
                                $res = WithdrawService::inputAddress($chatId, $text, $messageId);
                                return $res;
                                break;
                            case StepStatus::INPUT_ADDRESS_ALIAS:
                                $res = WithdrawService::inputAlias($chatId, $text, $messageId);
                                return $res;
                                break;

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

                return $returnMsg;
            }
        }
    }

    /**
     * @description: 设置 start 回复菜单
     * @param {*} $chatId
     * @throws TelegramSDKException
     */
    public static function setReplyKeyboard($chatId,$language = 'en'):void
    {
        $replyInfo = KeyboardService::findOne(['button' => '开始使用','language'=>$language]);
        if(empty($replyInfo)){
            $replyInfo = KeyboardService::findOne(['button' => '开始使用','language'=>'en']);
        }
        $telegram = new Api(config('services.telegram.token'));

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

        if ($replyInfo && $replyInfo->buttons) {
            $keyboard = [];
            $buttons = json_decode($replyInfo->buttons, true);

            foreach ($buttons as $rowIndex => $row) {
                if (!empty($row)) {
                    foreach ($row as $buttonIndex => $button) {
                        // $keyboard[$rowIndex][$buttonIndex] = lang($button['text']);
                        $keyboard[$rowIndex][$buttonIndex] = $button['text'];
                    }
                }

            }
            $keyboard = array_values($keyboard); // 重新索引数组
            Log::error('自定义开始使用按钮: ' . json_encode($keyboard));

        }

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

        if ($replyInfo) {
            $image = '';
            if ($replyInfo->image) {
                $image = url($replyInfo->image);

            }

            if ($image != '') {
                $botMsg['photo'] = InputFile::create($image);
                $botMsg['caption'] = lang($replyInfo->reply);
                $botMsg['protect_content'] = true;  // 防止转发
                KeyboardService::telegram()->sendPhoto($botMsg);
            } else {
                $botMsg['text'] = lang($replyInfo->reply);

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


    }
}