<?php


namespace App\Services;


use App\Constants\StepStatus;
use App\Exceptions\MessageException;
use App\Models\BalanceLog;
use App\Models\Config;
use App\Models\Room;
use App\Models\RoomUser;
use App\Models\User;
use App\Models\Wallet;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Telegram\Bot\Api;

//结算相关
class SettlementService
{
    private $telegram;

    public function __construct()
    {
        $this->telegram = new Api(config('services.telegram.token'));
    }


    //用户提交结算数据
    public function submitSettle($chatId, $score, $messageId = null)
    {
        if (!preg_match('/^-?\d+$/', $score)) {
            return [
                'status' => false,
                'data' => [[
                    'chat_id' => $chatId,
                    'text' => '输入错误，请发送结算分数',
                    'reply_to_message_id' => $messageId
                ]]
            ];
        }
        $score = intval($score);
        $ru = RoomUser::whereIn('status', [2, 3])
            ->where('member_id', $chatId)->first();
        if (!$ru) {
            return [
                'status' => false,
                'data' => [['chat_id' => $chatId, 'text' => '没有待结算的对局']]
            ];
        }
        $ru->status = 3;
        $ru->score = $score;
        $ru->save();

        $list = RoomUser::where('status', 3)
            ->where('room_id', $ru->room_id)
            ->orderBy('score', 'desc')->get();
        $count = RoomUser::where('room_id', $ru->room_id)->count();


        if (count($list) == $count) {
            $totalAmount = RoomUser::where('status', 3)
                ->where('room_id', $ru->room_id)->sum('score');
            if ($totalAmount != 0) {
                $text = "❌经过系统结算，盈利额与亏损\n";
                $text .= "额度无法匹配，无法进行结算，\n";
                $text .= "请检查战绩是否正确，如果错误\n";
                $text .= "请重新输入正确的战绩！\n\n";
                $text .= "您输入的战绩如下：\n";
                $arr = [];
                foreach ($list as $item) {
                    $str = $text . "--------------------------------\n";
                    $str .= "房间号：{$item->room_id}\n";
                    $str .= "用户：{$item->game_id}\n";
                    $str .= "战绩：{$item->score}\n";
                    $arr[] = [
                        'chat_id' => $item->member_id,
                        'text' => $str
                    ];
                }
                return ['status' => false, 'data' => $arr];
            }


            //抽佣比例
            $brokerage = Config::where('field', 'brokerage')->first();
            $brokerage = $brokerage->val;

            $room = Room::where('room_id', $ru->room_id)->first();
            $room->status = 3;
            $room->save();
            $maxScore = 0;

            foreach ($list as $index => $item) {
                $a = bcmul($item->score, $room->base_score, 0);
                if ($index == 0) $maxScore = $item->score;
                //最赢着
                if ($item->score == $maxScore) {
                    $item->brokerage = bcmul($a, $brokerage, 10);
                    $item->real_score = bcsub($a, $item->brokerage, 10);
                }//
                //其余人员
                else {
                    $item->brokerage = 0;
                    $item->real_score = $a;
                }
                $item->status = 4;
                $item->save();


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


//                $user = User::where('member_id', $item->member_id)->first();
                $usdt = bcadd($available_balance, $item->real_score, 10);
                if ($usdt < 0) {
                    $ttt = floatval($available_balance);
                    $rr = "❌结算失败\n";
                    $rr .= "您的余额不足\n\n";
                    $rr .= "钱包余额：{$ttt} USDT\n";
                    $ttt = floatval($item->real_score);
                    $rr .= "结算金额：{$ttt} USDT\n";
                    $rr .= "请充值后重新进行结算";
                    $keyboard = [[
                        ['text' => '➕充值', 'callback_data' => "topup@@topup"],
                    ]];
                    $errorMsg = json_encode([
                        'chat_id' => $item->member_id,
                        'text' => $rr,
                        'reply_markup' => json_encode(['inline_keyboard' => $keyboard])
                    ]);
                    throw new MessageException($errorMsg, 400);
                }
                $wallet->available_balance = $usdt;
                $wallet->save();

                $newRoomId = RoomService::resetRoomId($item->room_id);

                BalanceLogService::addLog($item->member_id, $item->real_score, $available_balance, $wallet->available_balance, '结算', $item->id, '', $newRoomId);


            }
            $arr = [];
            foreach ($list as $item) {
                $text = "✅ 所有用户已经上传并且输入战绩结果，系统计算完毕！如果有纠纷，余额已变动，请及时联系在线客服\n";
                $text .= "🗂 {$room->game_name}   {$room->participants}人   {$room->rounds}局\n";
                $text .= "房间号：{$room->room_id}\n";
                $text .= "底分：{$room->base_score} USDT\n";
                $text .= "-------------------------------------\n";
                foreach ($list as $item1) {
                    $text .= "用户：{$item1->first_name}（{$item1->game_id}）\n";
                    $text .= "战绩：{$item1->score}\n";
                    $temp = floatval($item1->real_score);
                    $text .= "盈亏：{$temp} USDT\n";
                    $temp = floatval($item1->brokerage);
                    if ($temp > 0) $text .= "抽佣：{$temp} USDT\n";
                    $text .= "-------------------------------------\n";
                }
                $arr[] = [
                    'chat_id' => $item->member_id,
                    'text' => $text
                ];
            }


            return ['status' => true, 'data' => $arr];

        }
        $keyboard = [[
            ['text' => '返回', 'callback_data' => "games@@home{$ru->room_id}"],
        ]];
        $score = $score >= 0 ? "+{$score}" : $score;
        Cache::delete(get_step_key($chatId));
        return ['status' => false, 'data' => [[
            'chat_id' => $chatId,
            'text' => "🏆用户（ID:{$chatId}）已上传战绩，并输入结果：\n{$score}。请等待其余用户完成上传，系统将在所有\n人输入后进行结算。",
            'reply_markup' => json_encode(['inline_keyboard' => $keyboard])
        ]]];

    }

    //用户点击结算游戏
    public function settle($roomId, $chatId, $messageId)
    {
        $ru = RoomUser::where('room_id', $roomId)
            ->whereIn('status', [2, 3])
            ->where('member_id', $chatId)->first();
        if (!$ru) return ['chat_id' => $chatId, 'text' => '❌游戏未开始或已结束', 'message_id' => $messageId];
        $keyboard = [[
            ['text' => '返回', 'callback_data' => "games@@home{$roomId}"],
        ]];
        Cache::put(get_step_key($chatId), StepStatus::INPUT_IMAGE);
        return [
            'chat_id' => $chatId,
            'text' => "‼️ 请务必上传战绩截图！如出现纠纷，系统将以截图\n作为处理依据。若未上传战绩截图，产生的纠纷责任\n将由您自行承担。",
//            'message_id' => $messageId,
//            'reply_markup' => json_encode(['inline_keyboard' => $keyboard])
        ];
    }


    //用户发送结算截图
    public function photo($photo, $chatId)
    {
        $file = $this->telegram->getFile(['file_id' => $photo['file_id']]);
        $filePath = $file->getFilePath();
        $token = config('services.telegram.token');
        $file_url = "https://api.telegram.org/file/bot{$token}/{$filePath}";
        $file_info = pathinfo($file_url);
        $roomUser = RoomUser::whereIn('status', [2, 3])
            ->where('member_id', $chatId)->first();
        if ($roomUser) {
            $roomId = $roomUser->room_id;
            $save_path = storage_path("app/public/images/{$roomId}/");
            if (!is_dir($save_path)) {
                mkdir($save_path, 0777, true);
            }
            $fileName = "{$chatId}.{$file_info['extension']}";
            $save_path .= $fileName;
            file_put_contents($save_path, file_get_contents($file_url));
            $path = Storage::url("images/{$roomId}/" . $fileName);
            $roomUser->screenshot = $path;
            $roomUser->save();

            $text = "✅ 已收到您的战绩截图。请根据结果输入战绩分数：\n";
            $text .= "如果盈利 10，输入 10\n";
            $text .= "如果亏损 10，输入 -10\n";
            $text .= "系统将在所有人输入战绩后进行结算。";
            Cache::put(get_step_key($chatId), StepStatus::INPUT_SCORE);
            $keyboard = [[
                ['text' => '返回', 'callback_data' => "games@@home{$roomId}"],
            ]];
            return [
                'chat_id' => $chatId,
                'text' => $text,
//                'reply_markup' => json_encode(['inline_keyboard' => $keyboard])
            ];
        }
        return false;
    }
}