<?php


namespace App\Services;

use App\Constants\StepStatus;
use App\Models\Config;
use App\Models\Game;
use App\Models\Room;
use App\Models\RoomUser;
use App\Models\User;
use App\Models\UserGame;
use App\Models\Wallet;
use Telegram\Bot\Api;
use Telegram\Bot\Exceptions\TelegramSDKException;
use Illuminate\Support\Facades\Cache;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

//房间服务
class RoomService
{

    public static function model(): string
    {
        return Room::class;
    }

    public static function enum(): string
    {
        return '';
    }

    public static function getWhere(array $search = []): array
    {
        $where = [];
        if (isset($search['id']) && !empty($search['id'])) {
            $where[] = ['id', '=', $search['id']];
        }


        if (isset($search['member_id']) && !empty($search['member_id'])) {
            $where[] = ['member_id', '=', $search['member_id']];
        }

        if (isset($search['room_id']) && !empty($search['room_id'])) {
            if(isset($search['like_room_id']) && $search['like_room_id'] == true){
                $where[] = ['room_id', 'like', '%' . $search['room_id'] . '%'];

            }else{
                $where[] = ['room_id', '=', $search['room_id']];

            }
        }
        if (isset($search['old_room_id']) && !empty($search['old_room_id'])) {
            $where[] = ['old_room_id', '=', $search['old_room_id']];
        }
        if (isset($search['base_score']) && !empty($search['base_score'])) {
            $where[] = ['base_score', '=', $search['base_score']];
        }

        if (isset($search['not_status']) && $search['not_status'] != '') {
            $where[] = ['status', '<>', $search['not_status']];
        }

        if (isset($search['status']) && $search['status'] != '') {
            $where[] = ['status', '=', $search['status']];
        }


        return $where;
    }

    public static function findOne(array $search): ?Room
    {
        return self::model()::where(self::getWhere($search))->first();
    }

    public static function findAll(array $search = [])
    {
        return self::model()::where(self::getWhere($search))->get();
    }

    public static function paginate(array $search = [])
    {
        $limit = isset($search['limit']) ? $search['limit'] : 10;
        $paginator = self::model()::where(self::getWhere($search))
            ->orderBy('created_at', 'desc')
            ->paginate($limit);
        return ['total' => $paginator->total(), 'data' => $paginator->items()];
    }


    private $telegram;

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

    public static function getGameIdMessage($chatId, $gameName, $messageId)
    {
        $text = "请设置游戏ID\n";
        $keyboard = [];
        $ug = UserGame::where('member_id', $chatId)
            ->where('game_name', $gameName)->first();
        if ($ug) {
            $text = "游戏ID：{$ug->game_id}\n";
            $text .= "-------------------\n";
            $text .= "请确认或直接输入新的游戏ID\n";
            $keyboard[] = [['text' => '确认', 'callback_data' => "inputGameID@@{$ug->game_id}"]];
        }
        $text .= "❓如何获取我的ID\n";
        $text .= "1.登录微信小程序：如 财神十三张\n";
        $text .= "2.登录成功后，点击用户头像，查看我的资料\n";
        $text .= "3.复制对应的ID\n";
        $data = [
            'chat_id' => $chatId,
            'text' => $text
        ];
        if ($messageId) {
            $data['message_id'] = $messageId;
            Cache::put("{$chatId}_GAME_ID_MESSAGE_ID", $messageId);
        }

        if ($keyboard) {
            $data['reply_markup'] = json_encode(['inline_keyboard' => $keyboard]);
        }
        return $data;
    }

    //提前开始游戏
    public function start($chatId, $roomId, $messageId)
    {
        $room = Room::where('room_id', $roomId)->first();
        if ($room->status != 1) {
            return [['chat_id' => $chatId, 'text' => '已经开始，无需重复开始', 'message_id' => $messageId]];
        }

        $list = RoomUser::where('room_id', $roomId)->get();
        if (count($list) < 2) {
            return [['chat_id' => $chatId, 'text' => '最少需要2人才可以开始游戏']];
        }
        $readyCount = RoomUser::where('room_id', $roomId)->where('status', 1)->count();
        if ($readyCount != count($list)) {
            return [['chat_id' => $chatId, 'text' => '还有人员未准备，请等待所有人员准备']];
        }

        $room->status = 2;// 游戏中
        $room->save();
        RoomUser::where('room_id', $roomId)->update(['status' => 2]);//游戏中

        
        foreach ($list as $item) {
            $text = "✅ 房主提前开始游戏 \n";
            $text .= "房号 {$room->room_id} \n";
            $text .= "‼️请回到微信小程序搜索《{$room->game_name}》\n输入房间号({$room->room_id})加入游戏\n";

            $arr[] = [
                'chat_id' => $item->member_id,
                'text' => $text
            ];
            if ($item->member_id == $chatId) {
                $arr[] = $this->gameHome($roomId, $item->member_id, $messageId);
            } else {
                $arr[] = $this->gameHome($roomId, $item->member_id);
            }

        }
        return $arr;

    }

    //返回游戏首页
    public function gameHome($roomId, $chatId, $messageId = null)
    {
        $ru = RoomUser::where('member_id', $chatId)
            ->where('room_id', $roomId)->first();
        if (!$ru->game_id) {
            $room = Room::where('room_id', $roomId)->first();
            $data = RoomService::getGameIdMessage($chatId, $room->game_name, $messageId);
            Cache::put(get_step_key($chatId), StepStatus::INPUT_GAME_ID);
            return $data;
        }


        $room = Room::where('room_id', $roomId)->first();
        $data = $this->getGameInfo($room, $chatId, $room->member_id == $chatId);
        $data['chat_id'] = $chatId;
        if ($messageId != null) $data['message_id'] = $messageId;
        Cache::delete(get_step_key($chatId));
        return $data;
    }

    //获取最终的房间信息和确认按钮
    private function getCreateButton($room, $chatId)
    {
        $text = "房间信息\n";
        $text .= "🗂 {$room->game_name}   {$room->participants}人   {$room->rounds}局\n";
        $text .= "房间号：{$room->room_id}\n";
        $text .= "底分：{$room->base_score} USDT\n";
        $text .= "中途加入：".($room->midway?'允许':'不允许')." \n";
        $text .= "\n";
        $keyboard[] = [
            ['text' => '创建', 'callback_data' => 'room@@done'],
            ['text' => '❌取消', 'callback_data' => "games@@cancel"]
        ];

        return [
            'chat_id' => $chatId,
            'text' => $text,
            'reply_markup' => json_encode(['inline_keyboard' => $keyboard])
        ];
    }

    /**
     * 获取游戏房间信息和房间的操作按钮
     * @param $roomId string 房间ID
     * @param $isHouseOwner bool 是否是房主
     *
     */
    public function getGameInfo($room, $chatId, $isHouseOwner, $text = '')
    {
        if($isHouseOwner){
            $text .= "游戏：{$room->game_name}   {$room->rounds}局  房号：{$room->room_id} \n";
        }else{
            $text .= "游戏：{$room->game_name}   {$room->rounds}局 \n";

        }
        $text .= "底分：{$room->base_score} USDT\n";
        $text .= "中途加入：".($room->midway?'允许':'不允许')." \n";
        $text .= "人数：{$room->participants}人\n";
        $text .= "{$room->introduction}\n";
        $text .= "\n";
        $text .= "----------------------------------------------\n";
        $text .= "\n";
        $text .= "‼️1.开始游戏前，非房主请点击准备，房主等待\n大家准备后，点击开始游戏。\n";
        $text .= "‼️2.游戏结束后，请务必上传双方和第三方的战\n绩截图。如出现争议，平台将以三方截图为依据\n进行审核，以确保比赛的公平与公正\n";
        // $text .= "‼️3.请回到微信小程序搜索《{$room->game_name}》\n输入房间号({$room->room_id})加入游戏\n";
        $keyboard = $this->getGameKeyboard($room->room_id, $chatId, $isHouseOwner);
        return [
            'text' => $text,
            'reply_markup' => json_encode(['inline_keyboard' => $keyboard])
        ];
    }


    //获取选择底分的按钮列表
    private function getChooseBaseScoreMsg()
    {
        $config = Config::where('field', 'base_score')->first();
        $baseScore = json_decode($config->val, true);
        $keyboard = [];
        foreach ($baseScore as $item) {
            if (count($keyboard) == 0) {
                $keyboard = [[
                    ['text' => "💵 {$item} USDT", 'callback_data' => "roomMin@@" . $item],
                ]];
            } else {
                if (count($keyboard[count($keyboard) - 1]) >= 3) $keyboard[] = [];
                $keyboard[count($keyboard) - 1][] = ['text' => "💵 {$item} USDT", 'callback_data' => "roomMin@@" . $item];
            }
        }
        return $keyboard;
    }

    private function getGameKeyboard($roomId, $chatId, $isHouseOwner)
    {
        $keyboard = [
            [
                ['text' => '准备', 'callback_data' => "games@@ready{$roomId}"],
                ['text' => '人员/状态', 'callback_data' => "games@@status{$roomId}"],
            ],
        ];
        $ru = RoomUser::where('room_id', $roomId)->where('member_id', $chatId)
            ->first();
        if ($ru->status != 0) {
            $keyboard[0][0]['text'] = "✅ 已准备";
            $keyboard[0][0]['callback_data'] = "games@@readyS";
        }
        $room = Room::where('room_id', $roomId)->first();
        if ($room->status == 2) {
            if (in_array($ru->status, [2, 3])) {
                $keyboard[] = [['text' => '结算游戏', 'callback_data' => "games@@settle{$roomId}"]];
            } else if (in_array($ru->status, [0, 1])) {
                $keyboard[] = [['text' => '退出', 'callback_data' => "games@@exit{$roomId}"]];
            }
        } else if (in_array($room->status, [0, 1])) {
            if ($isHouseOwner) {
                $keyboard[] = [
                    ['text' => '解散', 'callback_data' => "games@@Disband{$roomId}"],
                    ['text' => '开始游戏', 'callback_data' => "games@@start{$roomId}"],
                ];
            } else {
                $keyboard[] = [['text' => '退出', 'callback_data' => "games@@exit{$roomId}"]];
            }
        }
        return $keyboard;
    }


    //人员状态
    public function userStatus($roomId, $chatId, $messageId)
    {
        $list = RoomUser::where('room_id', $roomId)
            ->orderBy('id')
            ->get();
        if (count($list) == 0) {
            return [
                'chat_id' => $chatId,
                'text' => '房间不存在，请先创建房间'
            ];
        }
        $status = ['待准备', '已准备', '游戏中', '待结算', '已结算'];
        $text = "编号      角色          状态          游戏ID\n";

        foreach ($list as $index => $item) {
            $no = $index + 1;
            $gameId = $item->game_id;
            if (!$gameId) $gameId = '-------';
            if ($no == 1) {
                $text .= "{$no}            房主          {$status[$item->status]}      {$gameId}\n";
//                $text .= "{$no}\t\t{$item->game_id}\t\t{$status[$item->status]}\t\t房主\n";
            } else {
                $text .= "{$no}            玩家          {$status[$item->status]}      {$gameId}\n";
//                $text .= "{$no}\t\t{$item->game_id}\t\t{$status[$item->status]}\t\t玩家\n";
            }
        }

        $keyboard = [
            [
                ['text' => '返回', 'callback_data' => "games@@home{$roomId}"],
            ],
        ];
        return [
            'chat_id' => $chatId,
            'text' => $text,
            'parse_mode' => 'Markdown',
            'message_id' => $messageId,
            'reply_markup' => json_encode(['inline_keyboard' => $keyboard])

        ];
    }

    //准备
    public function ready($roomId, $chatId, $messageId)
    {
        $ru = RoomUser::whereIn('status', [0, 1, 2, 3])
            ->where('member_id', $chatId)
            ->where('room_id', $roomId)
            ->first();
        if (!$ru) {
            return [[
                'chat_id' => $chatId,
                'text' => "❌您还没有选择房间，请先通过在线房间进入房间"
            ]];
        }
        if (in_array($ru->status, [2, 3])) {
            return [[
                'chat_id' => $chatId,
                'text' => "❌您已在游戏中，无需准备"
            ]];
        }
        Cache::put(get_step_key($chatId), StepStatus::INPUT_GAME_ID);
        if (!$ru->game_id) {
            $room = Room::where('room_id', $roomId)->first();
            $data = RoomService::getGameIdMessage($chatId, $room->game_name, $messageId);
            return [$data];
        }


       
        $room = Room::where('room_id', $roomId)->first();
        $ru->status = 1;
        $arr = [];
        if ($room->status == 2) {
            $ru->status = 2;
            $text = "✅ 游戏已开始 \n";
            $text .= "房号 {$room->room_id} \n";
            $text .= "‼️请回到微信小程序搜索《{$room->game_name}》\n输入房间号({$room->room_id})加入游戏\n";
            $arr[] = [
                'chat_id' => $chatId,
                'text' => $text
            ];
        }
        $ru->save();
        $ready = RoomUser::where('room_id', $roomId)->where('status', 1)->count();
        

        $data = $this->getGameInfo($room, $chatId, $room->member_id == $chatId);
        $data['chat_id'] = $chatId;
        $data['message_id'] = $messageId;
        $arr[] = $data;
        if ($room->participants == $ready) {
            $list = RoomUser::where('room_id', $roomId)->get();
            $room->status = 2;// 游戏中
            $room->save();
            RoomUser::where('room_id', $roomId)->update(['status' => 2]);//游戏中
            foreach ($list as $item) {
                $text = "✅ 所有人员都已准备，自动开始游戏 \n";
                $text .= "房号 {$room->room_id} \n";
                $text .= "‼️请回到微信小程序搜索《{$room->game_name}》\n输入房间号({$room->room_id})加入游戏\n";
                $arr[] = [
                    'chat_id' => $item->member_id,
                    'text' => $text
                ];
                if ($item->member_id == $chatId) {
                    $arr[] = $this->gameHome($roomId, $item->member_id, $messageId);
                } else {
                    $arr[] = $this->gameHome($roomId, $item->member_id);
                }

            }
        }
        return $arr;
    }


    //玩家加入房间
    public function join($chatId, $roomId, $messageId = null)
    {
        $room = Room::where('room_id', $roomId)->first();
        if (!$room) {
            return [[
                'chat_id' => $chatId,
                'text' => '❌ 房间已关闭，请重新选择房间！'
            ]]; 
        }

        if ($room->status !== 1 && $room->status !== 2) {
            return [[
                'chat_id' => $chatId,
                'text' => '❌ 房间已开始游戏，请重新选择房间！'
            ]];
        }

        if($room->status == 2 && !$room->midway){
            return [[
                'chat_id' => $chatId,
                'text' => '❌ 房间已开始游戏，不允许中途加入！'
            ]];

        }
        $wallet = Wallet::where('member_id', $chatId)->first();
        $zuiDi = $room->base_score * 100;
        if ($wallet->available_balance < $zuiDi) {
            return [[
                'chat_id' => $chatId,
                'text' => "❌您选择的是：{$room->base_score}USDT的房间，最低余额：{$zuiDi}USDT\n请重新选择或充值余额！"
            ]];
        }


        $ru = RoomUser::whereIn('status', [0, 1, 2, 3])
            ->where('member_id', $chatId)
            ->first();
        if ($ru) {
            if ($room->join_count >= $room->participants && $ru->member_id != $chatId) {
                return [[
                    'chat_id' => $chatId,
                    'text' => '❌加入失败，房间人数已满'
                ]];
            }


            $text = '';
            if ($room->room_id !== $ru->room_id) {
                $text .= "❌加入失败，您已经加入了其他房间，\n以下是您加入的房间信息\n";
                $text .= "\n";
                $text .= "------------------------------\n";
                $text .= "\n";
                $room = Room::where('room_id', $ru->room_id)->first();
            }
            $data = $this->getGameInfo($room, $chatId, $room->member_id == $chatId, $text);
            $data['chat_id'] = $chatId;
            $data['message_id'] = $messageId;
            return [$data];
        }
        $user = User::where('member_id', $chatId)->first();
        $ru = new RoomUser();
        $ru->room_id = $room->room_id;
        $ru->member_id = $chatId;
        $ru->first_name = $user->first_name;
        $ru->status = 0;
        $ru->save();
        $room->join_count += 1;
        $room->save();
        $arr = [];
        $list = RoomUser::where('room_id', $ru->room_id)->where('member_id', '<>', $chatId)->get();
        foreach ($list as $item) {
            $arr[] = [
                'chat_id' => $item->member_id,
                'text' => "新用户进入房间",
            ];
            if ($room->join_count == $room->participants) {
                $arr[] = [
                    'chat_id' => $item->member_id,
                    'text' => "房间已满员，请所有玩家准备",
                ];
            }
        }
        $data = RoomService::getGameIdMessage($chatId, $room->game_name, $messageId);
        Cache::put(get_step_key($chatId), StepStatus::INPUT_GAME_ID);
        $arr[] = $data;
        return $arr;
    }

    /**
     * 取消创建房间
     * @param $chatId
     * @throws TelegramSDKException
     */
    public function cancel($chatId, $messageId)
    {
        Room::where('status', 0)
            ->where('member_id', $chatId)->delete();
        return [
            'chat_id' => $chatId,
            'text' => '🚫游戏创建流程已取消',
            'message_id' => $messageId
        ];
    }

    public function exit($data, $chatId, $messageId)
    {
        $roomId = preg_replace('/^games@@exit/', '', $data);
        $roomId = intval($roomId);

        $room = Room::where('room_id', $roomId)->first();
        if (!$room) return ['chat_id' => $chatId, 'text' => '房间已解散，无需退出'];

        $ru = RoomUser::where('room_id', $roomId)
            ->where('member_id', $chatId)->first();
        if (!$ru) {
            return ['chat_id' => $chatId, 'text' => '不在房间内，无需退出'];
        }

        if ($ru->member_id == $room->member_id) {
            return ['chat_id' => $chatId, 'text' => '房主不可退出房间'];
        }

        if (!in_array($room->status, [1, 2]) || !in_array($ru->status, [0, 1])) {
            return ['chat_id' => $chatId, 'text' => '游戏已开局，退出失败'];
        }
        $ru->delete();
        $room->join_count -= 1;
        $room->save();


        $data = (new OnLineService())->getList($chatId, null, 1);
        $data['message_id'] = $messageId;
        return $data;
//        return [
//            'chat_id' => $chatId,
//            'text' => "已退出房间",
//            'message_id' => $messageId
//        ];
    }

    /**
     * 解散房间
     * @return array
     */
    public function disband($roomId, $chatId, $messageId)
    {
        $room = Room::whereIn('status', [0, 1, 2, 3])
            ->where('member_id', $chatId)
            ->where('room_id', $roomId)
            ->first();
        if (!$room) {
            return [[
                'chat_id' => $chatId,
                'text' => '房间不存在，请先创建房间 /room',
                'message_id' => $messageId
            ]];
        } else {
            if (in_array($room->status, [2, 3])) {
                return [[
                    'chat_id' => $chatId,
                    'text' => '游戏已开始，不可解散房间'
                ]];
            }

            $list = RoomUser::where('room_id', $room->room_id)->get();
            $arr = [];
            foreach ($list as $item) {
                $a = [
                    'chat_id' => $item->member_id,
                    'text' => "❌房主已解散房间",
                ];
                if ($item->member_id == $room->member_id) {
                    $a['message_id'] = $messageId;
                }
                $arr[] = $a;
            }
            $room->delete();
            RoomUser::where('room_id', $room->room_id)->delete();
            return $arr;
        }
    }


    /**
     * 设置游戏ID
     * @param $chatId string 用户的tg ID
     * @param $array array 设置房间号的前缀【房间号】
     * @throws TelegramSDKException
     */
    public function setGameID($chatId, $gameId, $messageId)
    {
        if (!preg_match('/^\d+$/', $gameId)) return [['chat_id' => $chatId, 'text' => '输入错误，请发送游戏ID', 'reply_to_message_id' => $messageId]];
        $ru = RoomUser::where('member_id', $chatId)
            ->where('status', 0)->first();
        if (!$ru) return [["chat_id" => $chatId, 'text' => '设置失败，没有房间', 'reply_to_message_id' => $messageId]];
        $room = Room::where('room_id', $ru->room_id)->whereIn('status', [0, 1, 2])->first();
        if (!$room) return [["chat_id" => $chatId, 'text' => '设置失败，没有房间', 'reply_to_message_id' => $messageId]];

        $ru->game_id = $gameId;
        $ru->save();
        if ($room->status != 2) {
            $room->status = 1;
            $room->save();
        }


        UserGame::updateOrCreate(
            ['member_id' => $chatId, 'game_name' => $room->game_name],
            ['game_id' => $gameId]
        );

        $notice = null;
        $text = "";
        if ($chatId == $room->member_id) {
            $notice = ChannelService::createRoomNotice($room->room_id);
            $text = "✅ 房间创建成功\n";
            $text .= "\n";
        }
        $messageId1 = Cache::get("{$chatId}_GAME_ID_MESSAGE_ID", $messageId);
        Cache::delete("{$chatId}_GAME_ID_MESSAGE_ID");
        $data = $this->getGameInfo($room, $chatId, $room->member_id == $chatId, $text);
        $data['chat_id'] = $chatId;
        if ($messageId1) $data['message_id'] = $messageId1;
        Cache::delete(get_step_key($chatId));
        if ($notice) return [$data, $notice];
        return [$data];
    }


    /** 确认创建房间
     * @param $chatId
     * @return array
     */
    public function done($chatId, $messageId)
    {
        $room = Room::where('status', 0)->where('member_id', $chatId)->first();
        if (!$room) return [['chat_id' => $chatId, 'text' => '房间不存在，请先创建房间 /room', 'message_id' => $messageId]];
        $text = "";
        if ($room->room_id == '') $text = '请设置房间号';
        if ($room->base_score == 0) $text = '请选择底分';
        if ($room->participants == 0 || $room->rounds == 0) $text = '请设置人数/局数';
        if ($text) return [['chat_id' => $chatId, 'text' => $text]];

        $user = User::where('member_id', $chatId)->first();
        $ru = new RoomUser();
        $ru->room_id = $room->room_id;
        $ru->member_id = $chatId;
        $ru->status = 0;
        $ru->first_name = $user->first_name;
        $ru->save();
        $room->join_count += 1;
        $room->save();
        $data = RoomService::getGameIdMessage($chatId, $room->game_name, $messageId);
        Cache::put(get_step_key($chatId), StepStatus::INPUT_GAME_ID);
        Cache::delete("{$chatId}_BASE_SCORE");
        return [$data];
    }

    //设置游戏介绍
    public function setIntroduction($chatId, $introduction, $messageId)
    {
        $room = Room::where('status', 0)->where('member_id', $chatId)->first();
        if (!$room) return ['chat_id' => $chatId, 'text' => '设置失败，没有正在创建的房间', 'reply_to_message_id' => $messageId];
        $room->introduction = $introduction;
        $room->save();

        Cache::delete(get_step_key($chatId));
        $messageId1 = Cache::get("{$chatId}_CREATE_ROOM_MESSAGE_ID");
        $res = $this->getCreateButton($room, $chatId);
        $res['message_id'] = $messageId1;
        return $res;
    }


    /**
     * 设置人数和局数
     * @param $chatId string 用户的tg ID
     * @param $array array 设置房间号的前缀【房间号】
     * @throws TelegramSDKException
     */
    public function setNumberOfGames($chatId, $array, $messageId)
    {
        $room = Room::where('status', 0)->where('member_id', $chatId)->first();
        if (!$room) return ['chat_id' => $chatId, 'text' => '设置失败，没有正在创建的房间', 'reply_to_message_id' => $messageId];
        if (count($array) != 2) return ['chat_id' => $chatId, 'text' => '设置失败，请发送游戏人数', 'reply_to_message_id' => $messageId];
        $array[0] = intval($array[0]);
        $array[1] = intval($array[1]);

        if (!is_int($array[1]) || $array[1] < 1) {
            return ['chat_id' => $chatId, 'text' => '设置失败，请发送游戏局数', 'reply_to_message_id' => $messageId];
        }
        if (!is_int($array[0]) || $array[0] < 2) {
            return ['chat_id' => $chatId, 'text' => '设置失败，请发送游戏人数', 'reply_to_message_id' => $messageId];
        }
        $room->participants = $array[0];
        $room->rounds = $array[1];
        $room->save();


        // $text = "{$room->game_name}   {$room->participants}人   {$room->rounds}局\n";
        // $text .= "房间号：{$room->room_id}\n";
        // $text .= "底分：{$room->base_score} USDT\n";
        // $text .= "中途加入：".($room->midway?'允许':'不允许')." \n";
        // $text .= "-------------------\n";
        // $text .= "请输入游戏介绍\n";
        // $messageId1 = Cache::get("{$chatId}_CREATE_ROOM_MESSAGE_ID");
        // Cache::put(get_step_key($chatId), StepStatus::INPUT_GAME_INTRODUCTION);
        // Cache::put("{$chatId}_CREATE_ROOM_MESSAGE_ID", $messageId1);
        // return [
        //     'chat_id' => $chatId,
        //     'text' => $text,
        //     'message_id' => $messageId1,
        //     'reply_markup' => json_encode(['inline_keyboard' => [[['text' => '❌取消', 'callback_data' => "games@@cancel"]]]])
        // ];
        Cache::delete(get_step_key($chatId));
        $messageId1 = Cache::get("{$chatId}_CREATE_ROOM_MESSAGE_ID");
        $res = $this->getCreateButton($room, $chatId);
        $res['message_id'] = $messageId1;
        return $res;
    }


    /**
     * 设置房间号
     * @param $chatId string 用户的tg ID
     * @param $roomId string 房间号
     * @throws TelegramSDKException
     */
    public function setNum($chatId, $roomId, $messageId)
    {
        if (!preg_match('/^\d+$/', $roomId)) return ['chat_id' => $chatId, 'text' => '房间号错误', 'reply_to_message_id' => $messageId];
        $room = Room::where('status', 0)->where('member_id', $chatId)->first();
        if (!$room) return ['chat_id' => $chatId, 'text' => "禁止设置，没有正在创建的房间"];
        $isRoom = Room::where('room_id', $roomId)
            ->where('room_id', '<>', $roomId)
            ->first();
        if ($isRoom) return ['chat_id' => $chatId, 'text' => '房间号已存在，请检查房间号', 'reply_to_message_id' => $messageId];
        $room->room_id = $roomId;
        $room->old_room_id = $roomId;
        $room->save();


        Cache::put(get_step_key($chatId), StepStatus::INPUT_ROOM_NUM);
        $text = "游戏：{$room->game_name}\n";
        $text .= "底分：{$room->base_score} USDT\n";
        $text .= "中途加入：".($room->midway?'允许':'不允许')." \n";
        $text .= "房间号：$roomId\n";
        $text .= "-------------------\n";
        $text .= "请输入游戏人数和局数\n";
        $text .= "例如：4人5局\n";
        $text .= "那么请发送：4/5\n";
        $messageId1 = Cache::get("{$chatId}_CREATE_ROOM_MESSAGE_ID");
        return [
            'chat_id' => $chatId,
            'text' => $text,
            'message_id' => $messageId1,
            'reply_markup' => json_encode(['inline_keyboard' => [[['text' => '❌取消', 'callback_data' => "games@@cancel"]]]])
        ];
    }


    public function setGameName($chatId, $gameName, $messageId)
    {
        $room = Room::where('status', 0)->where('member_id', $chatId)->first();
        if (!$room) {
            return ['chat_id' => $chatId, 'text' => "禁止设置，没有正在创建的房间", 'reply_to_message_id' => $messageId];
        }
        $room->game_name = $gameName;
        $room->save();
        Cache::put(get_step_key($chatId), StepStatus::INPUT_MIDWAY);
        $text = "游戏：{$room->game_name}\n";
        $text .= "底分：{$room->base_score} USDT\n";
        $text .= "-------------------\n";
        $text .= "请选择是否允许中途加入游戏\n";
        $messageId1 = Cache::get("{$chatId}_CREATE_ROOM_MESSAGE_ID");
        return [
            'chat_id' => $chatId,
            'text' => $text,
            'message_id' => $messageId1,
            'reply_markup' => json_encode(['inline_keyboard' => [[
                ['text' => '✅ 允许', 'callback_data' => "setGameMidway@@1"],
                ['text' => '❌ 不允许', 'callback_data' => "setGameMidway@@0"]
            ], [['text' => '❌取消', 'callback_data' => "games@@cancel"]]]])
        ];
    }

    /**
     * 设置游戏是否允许中途加入
     * @param $chatId 用户TG ID
     * @param $midway   中途加入 1允许 0 不允许
     * @param $messageId 消息ID
     * @throws TelegramSDKException
     */
    public function setGameMidway($chatId, $midway, $messageId)
    {

        $room = Room::where('status', 0)->where('member_id', $chatId)->first();
        if (!$room) {
            return ['chat_id' => $chatId, 'text' => "禁止设置，没有正在创建的房间", 'reply_to_message_id' => $messageId];
        }
        $room->midway = $midway;
        $room->save();
        Cache::put(get_step_key($chatId), StepStatus::INPUT_ROOM_ID);
        $text = "游戏：{$room->game_name}\n";
        $text .= "底分：{$room->base_score} USDT\n";
        $text .= "中途加入：".($room->midway?'允许':'不允许')." \n";
        $text .= "-------------------\n";
        $text .= "请发送三方游戏的房间号码";
        $messageId1 = Cache::get("{$chatId}_CREATE_ROOM_MESSAGE_ID");
        return [
            'chat_id' => $chatId,
            'text' => $text,
            'message_id' => $messageId1,
            'reply_markup' => json_encode(['inline_keyboard' => [[['text' => '❌取消', 'callback_data' => "games@@cancel"]]]])
        ];
    }


    /**
     * 选择房间低分
     * @param $chatId
     * @throws TelegramSDKException
     */
    public function setMin($data, $chatId, $messageId)
    {
        $roomMin = preg_replace('/^roomMin@@/', '', $data);
        $roomMin = intval($roomMin);
        $user = User::where('member_id', $chatId)->first();
        $zuiDi = $roomMin * 100;

        $wallet = Wallet::where('member_id', $chatId)->first();

        if ($wallet->available_balance < $zuiDi) {
            $text = "👤 {$user->first_name}（{$user->member_id}）\n";
            $text .= "\n";
            $text .= "💰钱包余额\n";
            $temp = floatval($wallet->available_balance);
            $text .= "USDT：{$temp}\n";
            $text .= "\n";
            $text .= "您创建的是{$roomMin}USDT的房间，最低余额{$zuiDi}USDT，请重新选择或充值余额后再创建房间！\n";
            return ['chat_id' => $chatId, 'text' => $text];
        } else {
            $room = Room::where('status', 0)->where('member_id', $chatId)->first();
            if (!$room) {
                return ['chat_id' => $chatId, 'text' => "禁止设置，没有正在创建的房间"];
            }
            $room->base_score = $roomMin;
            $room->save();
            $text = "底分：{$roomMin} USDT\n";
            $text .= "-------------------\n";
            $text .= "请选择游戏";
            $games = Game::all();
            $keyboard = [];
            foreach ($games as $index => $item) {
                if ($index % 2 == 0) {
                    $keyboard[] = [['text' => $item['game_name'], 'callback_data' => "inputGameName@@{$item['game_name']}"]];
                } else {
                    $keyboard[count($keyboard) - 1][] = ['text' => $item['game_name'], 'callback_data' => "inputGameName@@{$item['game_name']}"];
                }
            }

            if (count($keyboard[count($keyboard) - 1]) > 1) {
                $keyboard[] = [['text' => '❌取消', 'callback_data' => "games@@cancel"]];
            } else {
                $keyboard[count($keyboard) - 1][] = ['text' => '❌取消', 'callback_data' => "games@@cancel"];
            }

//            Cache::put(get_step_key($chatId), StepStatus::INPUT_GAME_NAME);
            Cache::put("{$chatId}_CREATE_ROOM_MESSAGE_ID", $messageId);
            return [
                'chat_id' => $chatId,
                'text' => $text,
                'message_id' => $messageId,
                'reply_markup' => json_encode(['inline_keyboard' => $keyboard])
            ];
        }
    }


    /**
     * 创建房间
     * @param $chatId
     * @throws TelegramSDKException
     */
    public function create($chatId)
    {
        $room = Room::whereIn('status', [0, 1, 2, 4])
            ->where('member_id', $chatId)->first();
        $ru = RoomUser::where('member_id', $chatId)
            ->whereIn('status', [0, 1, 2, 3])->first();
        if (($room && $room->status !== 0) || $ru) {
            return ['chat_id' => $chatId, 'text' => "您有未结算对局，禁止创建房间"];
        }
        if (!$room) {
            $room = new Room();
            $room->member_id = $chatId;
            $room->game_name = '';
            $room->save();
        }
        $keyboard = $this->getChooseBaseScoreMsg();
        $keyboard[] = [['text' => '❌取消', 'callback_data' => "games@@cancel"]];
        return [
            'chat_id' => $chatId,
            'text' => "👇请选择你房间底分",
            'reply_markup' => json_encode(['inline_keyboard' => $keyboard])
        ];
    }

    /**
     * 重置房间号
     * @param $roomId string 房间号
     */
    public static function resetRoomId($roomId)
    {
        $num = self::model()::where('old_room_id', $roomId)->count();
        $room = Room::where('room_id', $roomId)->first();
        $newRoomId = $roomId . '_' . $num;
        if ($room) {
            $room->room_id = $newRoomId;
            $room->save();
        }
        RoomUser::where('room_id', $roomId)->update(['room_id' => $newRoomId]);
        return $newRoomId;
    }

    /**
     * @description: 结算通知
     * @return {*}
     */    
   public static function noticeSettle()
    {
        try {
            $time = Carbon::now()->subMinutes(20)->format('Y-m-d H:i:s');

            $roomList = self::model()::where('status', 2)
                ->where('settle_status', 0)
                ->where('updated_at', '<', $time)
                ->get();

            $telegram = new Api(config('services.telegram.token'));

            foreach ($roomList as $room) {
                try {
                    $list = RoomUser::where('room_id', $room->room_id)
                        ->where('status', 2)
                        ->get();

                    if ($list->isEmpty()) continue;

                    $text = "❗️房间号：{$room->room_id} \n";
                    $text .= "‼️您有待结算的游戏，请及时进行结算。\n";

                    foreach ($list as $item) {
                        try {
                            $keyboard = [[
                                ['text' => '结算游戏', 'callback_data' => "games@@settle{$room->room_id}"]
                            ]];

                            $message = [
                                'chat_id' => $item->member_id,
                                'text' => $text,
                                'reply_markup' => json_encode(['inline_keyboard' => $keyboard])
                            ];

                            $telegram->sendMessage($message);



                        } catch (\Exception $e) {
                            Log::error("发送消息失败：房间 {$room->room_id}, 用户 {$item->member_id}, 错误：" . $e->getMessage());
                            continue; // 跳过当前用户
                        }
                    }
                } catch (\Exception $e) {
                    Log::error("处理房间 {$room->room_id} 失败：" . $e->getMessage());
                    continue; // 跳过当前房间
                }

                $room->settle_status = 1; // 已通知
                $room->save();
            }

        } catch (\Exception $e) {
            Log::error("noticeSettle 整体执行失败：" . $e->getMessage());
        }
    }

}