<?php

namespace App\Services;


//充值服务
use App\Constants\StepStatus;
use App\Models\BalanceLog;
use App\Models\Config;
use App\Models\Recharge;
use App\Models\Wallet;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Telegram\Bot\Api;
use Telegram\Bot\FileUpload\InputFile;
use Telegram\Bot\Exceptions\TelegramSDKException;

class TopUpService
{

    /**
     * 到账通知
     * @param $memberId string 要通知的TgID
     * @param $text string 通知内容
     * @return bool 是否发送成功
     */
    public static function notifyTransferSuccess($memberId, $text)
    {
        try {
            $telegram = new Api(config('services.telegram.token'));
            $telegram->sendMessage(['chat_id' => $memberId, 'text' => $text]);
        } catch (TelegramSDKException $e) {
            return false;
        }
        return true;
    }

    public function bill($chatId, $firstName, $messageId = null, $page = 1, $limit = 5)
    {
        RechargeService::syncUsdtRechargeRecords($chatId);
        $list = BalanceLog::where('member_id', $chatId)
//            ->where('change_type', '充值')
            ->orderBy('created_at', 'desc')
            ->forPage($page, $limit)
            ->get();

        $count = BalanceLog::where('member_id', $chatId)
//            ->where('change_type', '充值')
            ->count();

        $text = "👤 {$firstName}({$chatId})    钱包充值记录\n\n";
        foreach ($list as $item) {


            $amount = floatval($item->amount);
            $amount = $amount < 0 ? ("➖ " . ($amount * -1)) : "➕ $amount";
            $balance = floatval($item->after_balance);
            $text .= "-------------------------------------\n";
            $text .= "{$amount} USDT\n余额：{$balance} \n";
            $text .= "类别：{$item->change_type}\n";
            if ($item->remark) {
                $text .= "说明：{$item->remark}\n";
            }
            $text .= "日期：{$item->created_at}\n";
        }

        if ($page > 1) {
            $keyboard[] = [
                ['text' => "👆上一页", 'callback_data' => "topUpBillNextPage@@" . ($page - 1)]
            ];
        }
        $allPage = ceil($count / $limit);
        if ($allPage > $page) {
            if ($page > 1) {
                $keyboard[count($keyboard) - 1][] = ['text' => "👇下一页", 'callback_data' => "topUpBillNextPage@@" . ($page + 1)];
            } else {
                $keyboard[] = [
                    ['text' => "👇下一页", 'callback_data' => "topUpBillNextPage@@" . ($page + 1)]
                ];
            }
        }
        $keyboard[] = [
            ['text' => "返回", 'callback_data' => "topUp@@home"]
        ];
        return [
            'chat_id' => $chatId,
            'text' => $text,
            'message_id' => $messageId,
            'reply_markup' => json_encode(['inline_keyboard' => $keyboard])
        ];
    }

    /**
     * 充值图片
     * @param $chatId
     * @param $photo
     * @throws TelegramSDKException
     */
    public static function photo($chatId, $photo)
    {
        $telegram = $telegram = new Api(config('services.telegram.token'));
        $file = $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);
        $save_path = storage_path("app/public/images/{$chatId}/");
        if (!is_dir($save_path)) {
            mkdir($save_path, 0777, true);
        }
        $fileName = uniqid();
        $fileName = "{$fileName}.{$file_info['extension']}";
        $save_path .= $fileName;
        file_put_contents($save_path, file_get_contents($file_url));
        $path = Storage::url("images/{$chatId}/" . $fileName);
        $amount = Cache::get("{$chatId}_TOP_UP_AMOUNT");
        $toAddress = Cache::get("{$chatId}_TOP_UP_ADDRESS");
        $recharge = new Recharge();
        $recharge->member_id = $chatId;
        $recharge->net = "TRC20";
        $recharge->coin = "USDT";
        $recharge->amount = $amount;
        $recharge->to_address = $toAddress;
        $recharge->status = 0;
        $recharge->type = 2;
        $recharge->image = $path;
        $recharge->save();
        Cache::delete(get_step_key($chatId));
        Cache::delete("{$chatId}_TOP_UP_AMOUNT");
        Cache::delete("{$chatId}_TOP_UP_ADDRESS");
        return [
            'chat_id' => $chatId,
            'text' => '已提交充值凭证，请等待系统审核完成'
        ];
    }

    //输入充值金额
    public static function inputAmount($chatId, $amount, $messageId)
    {
        if (!preg_match('/^\d+(\.\d+)?$/', $amount)) {
            return [
                'chat_id' => $chatId,
                'text' => "金额输入不正确，请发送充值数字",
                'reply_to_message_id' => $messageId
            ];
        }
        Cache::put("{$chatId}_TOP_UP_AMOUNT", $amount);
        Cache::put(get_step_key($chatId), StepStatus::INPUT_TOP_UP_IMAGE);
        return [
            'chat_id' => $chatId,
            'text' => "请发送您的充值凭证截图，方便系统验证",
        ];
    }

    //用户点击我已付款 （手动）
    public static function pay2($chatId)
    {
        Cache::put(get_step_key($chatId), StepStatus::INPUT_TOP_UP_MONEY);
        return [
            'chat_id' => $chatId,
            'text' => '请输入充值金额'
        ];
    }

    //用户点击我已付款
    public function done($chatId)
    {
        RechargeService::syncUsdtRechargeRecords($chatId);
        $keyboard = [
            [['text' => "🔙返回", 'callback_data' => "topUp@@home"]]
        ];
        return [
            'chat_id' => $chatId,
            'text' => '请耐心等待，充值成功后 Bot 会通知您！',
            'reply_markup' => json_encode(['inline_keyboard' => $keyboard]),
        ];
    }

    //获取充值二维码
    public function scan($chatId, $messageId)
    {

        // $receivingType = Config::where('field', 'receiving_type')->first()->val;
        $receivingType = 1;
        //自动
        if ($receivingType == 1) {
            $res = WalletService::getRechargeImageAddress($chatId);
            $address = $res['address'];
            $qrCode = $res['full_path'];
        } //
        //手动
        else {
            $address = Config::where('field', 'receiving_address')->first()->val;
            $res = WalletService::getPlatformImageAddress($address);
            $qrCode = $res['full_path'];
            Cache::put("{$chatId}_TOP_UP_ADDRESS", $address);
        }


        $caption = "\n";
        $caption .= "支持货币({$res['net']})：{$res['coin']}\n";
        $caption .= "专属收款地址：\n";
        $caption .= "{$address}\n";
        $caption .= "\n";
        $caption .= "⚠️提示：\n";
        $caption .= "- 如果上面地址和二维码不一致，请不要付款!\n";
        $caption .= "- 对上述地址充值后, 请点击我已付款！\n";
        $caption .= "- 请耐心等待, 充值成功后 Bot 会通知您!\n";

        $keyboard = [
            [
                ['text' => '📋 复制地址', 'copy_text' => ['text' => $address]],
                ['text' => '✅ 我已付款', 'callback_data' => 'topUp@@pay']
            ],
            [
                ['text' => "🔙返回", 'callback_data' => "topUp@@home1"],
            ]
        ];
        //手动
        if ($receivingType != 1) {
            $keyboard[0][1] = ['text' => '✅ 我已付款', 'callback_data' => 'topUp@@pay2'];
        }


        return [
            'chat_id' => $chatId,
            'photo' => InputFile::create($qrCode),
            'caption' => $caption,
            'protect_content' => true,
            'reply_markup' => json_encode(['inline_keyboard' => $keyboard]),
            'message_id' => $messageId
        ];


    }

    public function index($chatId, $firstName, $messageId = null)
    {
        $wallet = Wallet::where('member_id', $chatId)->first();
        $text = "👤 {$firstName}($chatId)\n";
        $text .= "💰钱包余额\n";
        $temp = floatval($wallet->available_balance);
        $text .= "USDT：{$temp}\n";
        $serviceAccount = Config::where('field', 'service_account')->first()->val;
        $keyboard = [
            [
                ['text' => '➕充值', 'callback_data' => "topup@@topup"],
                ['text' => '🧾账单', 'callback_data' => "topup@@bill"],
            ],
            [
                ['text' => '👩 客服帮助', 'url' => "https://t.me/{$serviceAccount}"],
                ['text' => '❌取消', 'callback_data' => "message@@close"],
            ]
        ];
        return [
            'chat_id' => $chatId,
            'text' => $text,
            'reply_markup' => json_encode(['inline_keyboard' => $keyboard]),
            'message_id' => $messageId
        ];
    }
}