<?php

namespace App\Http\Controllers\api;

use App\Constants\StepStatus;
use App\Constants\Util;
use App\Services\LogService;
use App\Services\PublicService;
use App\Services\QianBaoWithdrawService;
use App\Services\SanJinRechargeService;
use App\Services\SecretService;
use App\Services\SettlementService;
use App\Services\TopUpService;
use App\Services\UserService;
use App\Services\WalletService;
use App\Services\WithdrawService;
use App\Services\BalanceLogService;
use Exception;
use Illuminate\Http\JsonResponse;
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\Services\BetService;
use App\Services\IssueService;
use App\Services\KeyboardService;
use Telegram\Bot\FileUpload\InputFile;

class TelegramWebHook extends BaseController
{
    protected Api $telegram;

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

    /**
     * @throws TelegramSDKException
     */
    public function handle(Request $request): JsonResponse
    {
        $telegram = new Api(config('services.telegram.token'));

        try {
            $update = $telegram->getWebhookUpdate(); // 获取更新数据
            $update->callbackQuery;
            if ($update->has('callback_query')) {
                $callbackQuery = $update->callbackQuery;
                $message = $callbackQuery->message;
                $from = $callbackQuery->from;
                $data = $callbackQuery->data; // 获取 callback_data
                $callbackId = $callbackQuery->id; // 获取 callback_query 的 ID
                Util::delCache($message->chat->id);
                DB::beginTransaction();
                try {
                    $messageId = $message->messageId;
                    list($chatId, $firstName, $username) = PublicService::getChatInfo($message, $from);
                    //用户注册和初始化用户钱包
                    $user = PublicService::index($chatId, $username, $firstName);
                    App::setLocale($user->language);
                    PublicService::init($telegram, $data, $chatId, $firstName, $messageId);
                    WalletService::init($telegram, $data, $chatId, $firstName, $messageId, $callbackId);
                    TopUpService::init($telegram, $data, $chatId, $firstName, $messageId);
                    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);
                    WithdrawService::init($telegram, $data, $chatId, $firstName, $messageId);
                    BetService::init($telegram, $data, $chatId, $firstName, $messageId, $callbackId);
                    BalanceLogService::init($telegram, $data, $chatId, $firstName, $messageId, $callbackId);
                    IssueService::init($telegram, $data, $chatId, $firstName, $messageId);
                    DB::commit();
                } //
                catch (TelegramSDKException|Exception $e) {
                    DB::rollBack();
                    LogService::error($e);
                    $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 {
                        $returnMsg = $this->processChatMessage($chatId, $messageId, $message, $message['from']);
                        if (!empty($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 (TelegramSDKException $e) {
                        DB::rollBack();
                        LogService::error($e);
                        $telegram->sendMessage(['chat_id' => $chatId, 'text' => '‼️‼️系统发生了错误，请联系客服']);
                    }//
                    catch (Exception $e) {
                        DB::rollBack();
                        LogService::error($e);
                        $telegram->sendMessage(['chat_id' => $chatId, 'text' => '‼️‼️系统发生了错误，请联系客服']);
                    }
                }
            }
        } //
        catch (Exception $e) {
            LogService::error($e);
            if (!empty($chatId)) {
                $telegram->sendMessage(['chat_id' => $chatId, 'text' => '‼️‼️系统发生了错误，请联系客服']);
            }
        }
        return response()->json(['status' => 'ok']);
    }

    /**
     * @description: 处理聊天消息
     * @param {*} $chatId
     * @param {*} $messageId
     * @param {*} $message
     * @param {*} $from
     * @throws TelegramSDKException
     */
    public function processChatMessage($chatId, $messageId, $message, $from)
    {
        //用户发送图片,结算截图
        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];
                return (new SettlementService())->photo($photo, $chatId);
            }//
            //充值截图
            else if ($stepStatus === StepStatus::INPUT_TOP_UP_IMAGE) {
                $photo = $message['photo'][count($message['photo']) - 1];
                return TopUpService::photo($chatId, $photo);
            } else {
                return [];
            }

        } //用户发送了消息
        else if (isset($message['text'])) {
            $text = $message['text'];
            $username = "";
            if (isset($message['chat']['username'])) $username = $message['chat']['username'];
            $user = PublicService::index($chatId, $username, $message['chat']['first_name']);
            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);
                        self::setReplyKeyboard($chatId, $user->language);
                        break;
                    default:
                        //关键字回复
                        $res = KeyboardService::getKeyWordReply($chatId, $text);
                        if (!empty($res)) return $res;
                        $stepStatus = intval(Cache::get(get_step_key($chatId), -1));
                        $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)) $res = WithdrawService::onMessage($chatId, $text, $messageId, $stepStatus);
                        if (empty($res)) $res = TopUpService::onMessage($chatId, $text, $messageId, $stepStatus);
                        if (empty($res)) $res = BetService::onMessage($chatId, $text, $messageId, $stepStatus);
                        if (!empty($res)) return $res;
                        return BetService::bet($chatId, $text, $messageId);
                }
                return $returnMsg;
            }
        }
        return [];
    }

    /**
     * @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); // 重新索引数组

        }

        $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),
            ]);
        }


    }
}