<?php


namespace App\Services;


use App\Constants\StepStatus;
use App\Models\Room;
use App\Models\RoomUser;
use App\Models\User;
use App\Models\Wallet;
use Illuminate\Support\Facades\Cache;

class OnLineService
{

    static function join($chatId, $roomId, $messageId)
    {
        $room = Room::where('room_id', $roomId)->first();
        if (!$room) {
            return [[
                'chat_id' => $chatId,
                'text' => '❌ 房间不存在，请重新输入！',
                'reply_to_message_id' => $messageId
            ]];
        }
        if ($room->status !== 1 && $room->status != 2) {
            return [[
                'chat_id' => $chatId,
                'text' => '❌ 房间已开始游戏，请重新输入！',
                'reply_to_message_id' => $messageId
            ]];
        }

        if($room->status == 2 && !$room->midway){
            return [[
                'chat_id' => $chatId,
                'text' => '❌ 房间已开始游戏，不允许中途加入！',
                'reply_to_message_id' => $messageId
            ]];
        }
        $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请重新输入或充值余额！",
                'reply_to_message_id' => $messageId
            ]];
        }
        if ($room->join_count >= $room->participants) {
            return [[
                'chat_id' => $chatId,
                'text' => '❌加入失败，房间人数已满'
            ]];
        }
        $ru = RoomUser::where('member_id', $chatId)
            ->whereIn('status', [0, 1, 2, 3])
            ->first();
        if ($ru) {
            $keyboard = [
                [
                    ['text' => '进入房间', 'callback_data' => "games@@home{$ru->room_id}"],
                ],
            ];
            return [[
                'chat_id' => $chatId,
                'text' => "您已加入房间，请进入房间继续游戏",
                'reply_markup' => json_encode(['inline_keyboard' => $keyboard])
            ]];
        }

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

        unset($data['message_id']);
        $arr[] = $data;
        Cache::put(get_step_key($chatId), StepStatus::INPUT_GAME_ID);
        return $arr;
    }

    static function joinRoom($chatId, $messageId)
    {
        Cache::put(get_step_key($chatId), StepStatus::INPUT_JOIN_ROOM_ID);
        return [
            'chat_id' => $chatId,
            'message_id' => $messageId,
            'text' => '请发送您要加入的房间号'
        ];
    }

    public function getList($chatId, $messageId = null, $page = 1, $limit = 8)
    {
        Cache::delete("{$chatId}_CREATE_ROOM_MESSAGE_ID");
        $ru = RoomUser::where('member_id', $chatId)
            ->whereIn('status', [0, 1, 2, 3])
            ->first();
        if ($ru) {
            $keyboard = [
                [
                    ['text' => '进入房间', 'callback_data' => "games@@home{$ru->room_id}"],
                ],
            ];
            return [
                'chat_id' => $chatId,
                'text' => "您已加入房间，请进入房间继续游戏",
                'message_id' => $messageId,
                'reply_markup' => json_encode(['inline_keyboard' => $keyboard])
            ];
        }

        $res = Room::where('status', 1)
            ->forPage($page, $limit)->get();
        $count = Room::where('status', 1)->count();
//        if ($count > 0) {
        $keyboard = [];
        foreach ($res as $item) {
            $keyboard[] = [
                ['text' => "{$item->game_name}  人数:{$item->join_count}/$item->participants  局数:{$item->rounds}局  底分:{$item->base_score}USDT", 'callback_data' => "join@@{$item->room_id}"]
            ];
        }
        $dPage = false;
        if ($page > 1) {
            $dPage = true;
            $keyboard[] = [
                ['text' => "👆上一页", 'callback_data' => "onlineNextPage@@" . ($page - 1)]
            ];
        }
        $allPage = ceil($count / $limit);
        if ($allPage > $page) {
            $dPage = true;
            if ($page > 1) {
                $keyboard[count($keyboard) - 1][] = ['text' => "👇下一页", 'callback_data' => "onlineNextPage@@" . ($page + 1)];
            } else {
                $keyboard[] = [
                    ['text' => "👇下一页", 'callback_data' => "onlineNextPage@@" . ($page + 1)]
                ];
            }
        }
        if ($dPage) {

            if (count($keyboard[count($keyboard) - 1]) >= 2) {
                $keyboard[count($keyboard) - 1][] = ['text' => '输入房间号', 'callback_data' => 'join@@room'];
                $keyboard[count($keyboard) - 1][] = ['text' => "🔙返回", 'callback_data' => "del@@message"];
            } else {
                $keyboard[] = [
                    ['text' => '输入房间号', 'callback_data' => 'join@@room'],
                    ['text' => "🔙返回", 'callback_data' => "del@@message"],
                ];
            }
        } else {
            $keyboard[] = [
                ['text' => '输入房间号', 'callback_data' => 'join@@room'],
                ['text' => "🔙返回", 'callback_data' => "del@@message"],
            ];
        }


        $data = [
            'chat_id' => $chatId,
            'text' => "👇选择以下在线房间，加入后可参与游戏！",
            'message_id' => $messageId,
            'reply_markup' => json_encode(['inline_keyboard' => $keyboard])
        ];
        return $data;
//        }

    }
}