<?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;

use App\Services\BalanceLogService;

class TopUpService
{

    /**
     * @param Api $telegram
     * @param $data
     * @param $chatId
     * @param $firstName
     * @param $messageId
     * @return void
     * @throws TelegramSDKException
     */
    public static function init(Api $telegram, $data, $chatId, $firstName, $messageId): void
    {


        switch ($data) {
            case "topUp@@pay2"://手动充值(后台审核后到账)
                $telegram->deleteMessage(['chat_id' => $chatId, 'message_id' => $messageId]);
                $res = TopUpService::pay2($chatId);
                $telegram->sendMessage($res);
                break;
            case "topUp@@pay"://自动充值
                $telegram->deleteMessage(['chat_id' => $chatId, 'message_id' => $messageId]);
                $res = TopUpService::done($chatId);
                $telegram->sendMessage($res);
                break;
            case "topup@@bill"://点击充值的账单按钮
                $res = TopUpService::bill($chatId, $firstName, $messageId);
                $telegram->editMessageText($res);
                break;
            case "topup@@topup"://点击充值按钮
                $res = TopUpService::chooseAddress($chatId, $messageId);
                $telegram->editMessageText($res);
                break;
            case "topUp@@TRC20"://选择充值地址
            case "topUp@@ERC20"://选择充值地址
                $type = preg_replace('/^topUp@@/', '', $data);
                $res = TopUpService::scan($chatId, $messageId, $type);
                $telegram->deleteMessage(['chat_id' => $chatId, 'message_id' => $messageId]);
                $telegram->sendPhoto($res);
                break;
            default:
                //充值账单，下一页
                $pattern = "/^topUpBillNextPage@@\d+$/";
                if (preg_match($pattern, $data)) {
                    $page = preg_replace('/^topUpBillNextPage@@/', '', $data);
                    $page = intval($page);
                    $res = TopUpService::bill($chatId, $firstName, $messageId, $page);
                    $telegram->editMessageText($res);
                }


                break;
        }
    }

    public static function onMessage($chatId, $text, $messageId, $stepStatus): ?array
    {
        switch ($stepStatus) {
            case StepStatus::INPUT_TOP_UP_MONEY:
                $res = TopUpService::inputAmount($chatId, $text, $messageId);
                break;
            default:
                $res = null;
                break;
        }
        return $res;
    }


    /**
     * 到账通知
     * @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 static function bill($chatId, $firstName, $messageId = null, $page = 1, $limit = 5)
    {
        RechargeService::markUsdtRechargePending($chatId);
        RechargeService::syncUsdtRechargeRecords($chatId);
        $list = BalanceLog::where('member_id', $chatId)
//            ->where('change_type', '充值')
            ->whereIn('change_type', BalanceLogService::$RW)
            ->orderByDesc('id')
            ->forPage($page, $limit)
            ->get();

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

        $text = "👤 {$firstName}({$chatId})    " . lang('钱包流水记录') . "\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} \n" . lang('余额') . "：{$balance} \n";
            $text .= lang('类别') . "：" . lang($item->change_type) . "\n";
            if ($item->remark) {
                $text .= lang("说明") . "：{$item->remark}\n";
            }
            $text .= lang("日期") . "：{$item->created_at}\n";
        }

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

    /**
     * 充值图片
     * @param $chatId
     * @param $photo
     * @return array
     * @throws TelegramSDKException
     */
    public static function photo($chatId, $photo): array
    {
        try {
            $telegram = new Api(config('services.telegram.token'));
        } catch (TelegramSDKException $e) {
            return [];
        }
        $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");
        $net = Cache::get("{$chatId}_TOP_UP_TYPE");
        $recharge = new Recharge();
        $recharge->member_id = $chatId;
        $recharge->net = $net;
        $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");
        Cache::delete("{$chatId}_TOP_UP_TYPE");
        return [
            'chat_id' => $chatId,
            'text' => lang('已提交充值凭证，请等待系统审核完成')
        ];
    }

    //输入充值金额
    public static function inputAmount($chatId, $amount, $messageId)
    {
        if (!preg_match('/^\d+(\.\d+)?$/', $amount)) {
            return [
                'chat_id' => $chatId,
                'text' => lang("金额输入不正确，请发送充值数字"),
                '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' => lang("请发送您的充值凭证截图，方便系统验证"),
        ];
    }

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

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

    public static function chooseAddress($chatId, $messageId)
    {
        $keyboard = [
            [['text' => 'TRC20', 'callback_data' => "topUp@@TRC20"], ['text' => 'ERC20', 'callback_data' => 'topUp@@ERC20']],
            [['text' => lang("↩️返回"), 'callback_data' => "topUp@@home"]]
        ];

        $receivingType = ConfigService::getVal("receiving_type");
        if ($receivingType == 1) unset($keyboard[0][1]);

        $text = lang("请选择网络类型");
        return [
            'chat_id' => $chatId,
            'text' => $text,
            'reply_markup' => json_encode(['inline_keyboard' => $keyboard]),
            'message_id' => $messageId,
        ];


    }

    //获取充值二维码
    public static function scan($chatId, $messageId, $type)
    {
        $receivingType = ConfigService::getVal("receiving_type");
        //自动
        if ($receivingType == 1) {
            $res = WalletService::getRechargeImageAddress($chatId);
            $address = $res['address'];
            $qrCode = $res['full_path'];
        } //
        //手动
        else {
            if ($type === "TRC20") {
                $address = Config::where('field', 'receiving_address')->first()->val;
            } else {//if ($type === "ERC20")
                $address = Config::where('field', 'receiving_address_erc20')->first()->val;
            }
            $res = WalletService::getPlatformImageAddress($address);
            $res['net'] = $type;
            $qrCode = $res['full_path'];
            Cache::put("{$chatId}_TOP_UP_ADDRESS", $address);
            Cache::put("{$chatId}_TOP_UP_TYPE", $type);
        }

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


        $keyboard = [
            [
                ['text' => lang('📋 复制地址'), 'copy_text' => ['text' => $address]],
                ['text' => lang('✅ 我已付款'), 'callback_data' => 'topUp@@pay']
            ],
            [
                ['text' => lang("↩️返回"), 'callback_data' => "topUp@@home1"],
            ]
        ];
        //手动
        if ($receivingType != 1) {
            $keyboard[0][1] = ['text' => lang('✅ 我已付款'), '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): array
    {
        $wallet = Wallet::where('member_id', $chatId)->first();
        $text = "👤 {$firstName}($chatId)\n";
        $text .= lang("💰钱包余额") . "\n";
        $temp = floatval($wallet->available_balance);
        $text .= "USDT：{$temp}\n";
        $serviceAccount = Config::where('field', 'service_account')->first()->val;
        $keyboard = [
            [
                ['text' => lang('➕充值'), 'callback_data' => "topup@@topup"],
                ['text' => lang('🧾账单'), 'callback_data' => "topup@@bill"],
            ],
            [
                ['text' => lang('👩 客服帮助'), 'url' => "https://t.me/{$serviceAccount}"],
                ['text' => lang('❌取消'), 'callback_data' => "message@@close"],
            ]
        ];
        return [
            'chat_id' => $chatId,
            'text' => $text,
            'reply_markup' => json_encode(['inline_keyboard' => $keyboard]),
            'message_id' => $messageId
        ];
    }
}