<?php


namespace App\Services;

use App\Models\Config;
use App\Services\BaseService;
use App\Models\Wallet;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use App\Services\CoinService;
use App\Services\UserService;
use App\Helpers\TronHelper;
use Illuminate\Support\Facades\Log;
use App\Services\BalanceLogService;
use Telegram\Bot\Api;
use Telegram\Bot\Exceptions\TelegramSDKException;

/**
 * 用户虚拟币钱包
 */
class WalletService extends BaseService
{
    public static string $MODEL = Wallet::class;

    public static function init(Api $telegram, $data, $chatId, $firstName, $messageId, $callbackId): void
    {


        switch ($data) {
            case "withdraw@@home"://提现管理
                $telegram->deleteMessage(['chat_id' => $chatId, 'message_id' => $messageId]);
                $returnMsg = WalletService::getBalance($chatId);
                if ($returnMsg) {
                    $telegram->sendMessage($returnMsg);
                }
                break;
            case "balanceAlert"://查看余额弹窗
                $alertText = WalletService::getBalance($chatId)['text'];
                WalletService::alertNotice($callbackId, $alertText);
                break;
            case "topUp@@home"://充值首页
            case "topUp@@home1"://充值首页
                $returnMsg = WalletService::getBalance($chatId);
                if ($returnMsg) {
                    if ($data === "topUp@@home1") {
                        $telegram->deleteMessage(['chat_id' => $chatId, 'message_id' => $messageId]);
                        $telegram->sendMessage($returnMsg);
                    } else {
                        $returnMsg['message_id'] = $messageId;
                        $telegram->editMessageText($returnMsg);
                    }
                }
                break;


        }


    }


    /**
     * @description: 模型
     * @return {string}
     */
    public static function model(): string
    {
        return Wallet::class;
    }

    /**
     * @description: 枚举
     * @return {*}
     */
    public static function enum(): string
    {
        return '';
    }

    /**
     * @description: 获取查询条件
     * @param {array} $search 查询内容
     * @return {array}
     */
    public static function getWhere(array $search = []): array
    {
        $where = [];
        if (isset($search['coin']) && !empty($search['coin'])) {
            $where[] = ['coin', '=', $search['coin']];
        }
        if (isset($search['net']) && !empty($search['net'])) {
            $where[] = ['net', '=', $search['net']];
        }
        if (isset($search['address']) && !empty($search['address'])) {
            $where[] = ['address', '=', $search['address']];
        }
        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']];
        }
        return $where;
    }

    /**
     * @description: 查询单条数据
     * @param array $search
     * @return \App\Models\Coin|null
     */
    public static function findOne(array $search): ?Wallet
    {
        return static::$MODEL::where(self::getWhere($search))->first();
    }

    /**
     * @description: 查询所有数据
     * @param array $search
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public static function findAll(array $search = [])
    {
        return static::$MODEL::where(self::getWhere($search))->get();
    }

    /**
     * @description: 分页查询
     * @param array $search
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public static function paginate(array $search = [])
    {
        $limit = isset($search['limit']) ? $search['limit'] : 15;
        $paginator = static::$MODEL::where(self::getWhere($search))->paginate($limit);
        return ['total' => $paginator->total(), 'data' => $paginator->items()];
    }

    /**
     * @description: 为用户创建虚拟钱包
     * @param {int} $memberId 用户ID
     * @return {*}
     */
    public static function createVirtualWallets(int $memberId)
    {
        $coins = CoinService::findAll(['coin' => 'USDT']);
        $users = UserService::findOne(['member_id' => $memberId]);
       Log::error("WallerService");
       Log::error(json_encode($users));
        $walletsData = $coins->map(function ($coin) use ($memberId, $users) {
            switch ($coin->coin) {
                case 'USDT':
                    $trons = TronHelper::createAddress($memberId);
                    break;
                default:
                    $trons = [];
            }
            return [
                'user_id' => $users['id'],
                'member_id' => $memberId,
                'coin' => $coin->coin,
                'net' => $coin->net,
                'address' => $trons['address'] ?? '',
                'private_key' => $trons['private_key'] ?? '',
                'available_balance' => 0,
                'frozen_balance' => 0
            ];
        })->toArray();
        // 批量创建钱包以提高性能
        static::$MODEL::insert($walletsData);

        // 活动
        // self::newUserRegisterActivity($memberId);

        return self::findAll(['member_id' => $memberId]);

    }

    /**
     * 重置所有用户钱包
     * @return void
     */
    public static function resetUserWallets()
    {
        $list = self::findAll();

        foreach ($list as $wallet) {
            $memberId = $wallet->member_id;
            $coin = $wallet->coin;

            switch ($coin) {
                case 'USDT':
                    $trons = TronHelper::createAddress($memberId);
                    break;
                default:
                    $trons = [];
            }

            $wallet->address = $trons['address'] ?? $wallet->address;
            $wallet->private_key = $trons['private_key'] ?? $wallet->private_key;
            $wallet->save();
        }
    }


    /**
     * 新用户注册活动
     * @param $memberId
     * @return void
     * @throws TelegramSDKException
     */
    public static function newUserRegisterActivity($memberId)
    {
        $start_date = '2025-12-23'; // 活动开始
        $end_date = '2026-01-31';   // 活动结束

        $date = date('Y-m-d');
        if ($date >= $start_date && $date <= $end_date) {
            $user = UserService::findOne(['member_id' => $memberId]);
            $amount = 28;//活动金额
            // 有用户名的账号
            if ($user && $user->getUsername()) {
                $wallets = self::findOne(['member_id' => $memberId]);
                $before_balance = $wallets->available_balance;
                $after_balance = $before_balance + $amount;
                $wallets->available_balance = $after_balance;
                $wallets->save();
                BalanceLogService::addLog($memberId, $amount, $before_balance, $after_balance, '人工充值', 0, '双旦活动注册赠送28');
                $returnMsg = WalletService::getBalance($user->getMemberId());
                $telegram = new Api(config('services.telegram.token'));
                $telegram->sendMessage($returnMsg);

            }
        }

    }

    /**
     * @description: 获取用户的钱包
     * @param {int} $memberId
     * @return {*}
     */
    public static function getUserWallet($memberId)
    {
        $wallets = self::findAll(['member_id' => $memberId]);

        if ($wallets->isEmpty()) {
            $wallets = self::createVirtualWallets($memberId);
        }

        $wallets->map(function ($wallet) {
            $wallet->available_balance = removeZero($wallet->available_balance);
            $wallet->frozen_balance = removeZero($wallet->frozen_balance);
            // $wallet->total_balance = $wallet->available_balance + $wallet->frozen_balance;
            return $wallet;
        });
        return $wallets;
    }

    /**
     * @description: 获取用户充值钱包地址
     * @param {*} $memberId
     * @return {*}
     */
    public static function getRechargeImageAddress($memberId)
    {
        self::getUserWallet($memberId);
        $info = self::findOne(['member_id' => $memberId]);
        
        if (empty($info->address)) {
            $trons = TronHelper::createAddress($memberId);
            $info->address = $trons['address'] ?? '';
            $info->private_key = $trons['private_key'] ?? '';
            $info->save();
        }
        $address = $info->address;
        $path = self::rechargeQrCodeExists($address);
        if (empty($path)) {
            $path = self::createRechargeQrCode($address);
        }

        RechargeService::markUsdtRechargePending($memberId);

        // $host = config('app.url'); // 通常在 .env 中配置 APP_URL
        return [
            'coin' => $info->coin,
            'net' => $info->net,
            'address' => $address,
            'path' => $path,
            'full_path' => asset($path)
        ];
    }

    /**
     * @description: 获取平台充值钱包地址
     * @param {*} $address
     * @return {*}
     */
    public static function getPlatformImageAddress($address)
    {
        $path = self::rechargeQrCodeExists($address);
        if (empty($path)) {
            $path = self::createRechargeQrCode($address);
        }

        // $host = config('app.url'); // 通常在 .env 中配置 APP_URL
        return [
            'coin' => 'USDT',
            'net' => "TRC20",
            'address' => $address,
            'path' => $path,
            'full_path' => asset($path)
        ];
    }

    /**
     * @description: 更新余额
     * @param {*} $memberId
     * @param {*} $amount
     * @return {*}
     */
    public static function updateBalance($memberId, $amount)
    {
        $data = [];
        $self = self::findOne(['member_id' => $memberId]);
        $data['before_balance'] = $self->available_balance; // 操作前余额
        $self->available_balance += $amount;
        $data['after_balance'] = $self->available_balance;
        $self->save();
        return $data;
    }

    /**
     * @description: 获取用户余额
     * @param {int} $memberId 用户ID
     * @return {*}
     */
    public static function getBalance($memberId)
    {
        $selfInfo = self::findOne(['member_id' => $memberId]);
        $userInfo = UserService::findOne(['member_id' => $memberId]);


        $balance = number_format($selfInfo->available_balance, 2, '.', '');

        $text = lang("用户ID") . "：{$memberId} \n";
        $text .= lang('用户名') . "：{$userInfo->getUsername()} \n";
        $text .= lang('昵称') . "：{$userInfo->getFirstName()} \n";
        $text .= lang('当前余额') . "：{$balance} RMB\n";

        $keyboard = [
            [
                // ['text' => lang('➕充值'), 'callback_data' => "topup@@topup"],
                ['text' => lang('➕充值'), 'callback_data' => "topup@@sj_apply"],
                ['text' => lang('🧾账单'), 'callback_data' => "topup@@bill"],
            ],
            [
                ['text' => lang('➕ 提现'), 'callback_data' => "withdraw@@qb_show_channel"],
                ['text' => lang('🧾 提现账单'), 'callback_data' => "withdraw@@bill"]
            ],
            [
                ['text' => lang('🔑秘钥管理'), 'callback_data' => 'secret@@index'],
            ],


        ];
        $three_payment_switch = Config::where('field', 'three_payment_switch')->first()->val;
        if ($three_payment_switch == 1) {
//             $keyboard[] = [
// //                ['text' => '➕ 钱宝提现', 'callback_data' => "withdraw@@qb_apply"],
// //                ['text' => '🧾 钱宝账单', 'callback_data' => "withdraw@@bank_bill_1"],
//                 ['text' => '🧾 钱宝提现账单', 'callback_data' => "withdraw@@bank_bill_1"],
//             ];
            $keyboard[] = [
                // ['text' => '➕ 三斤充值', 'callback_data' => "topup@@sj_apply"],

                ['text' => lang('🧾 第三方充值提现订单'), 'callback_data' => "topup@@sj_bill_1"]
            ];
        }
        $keyboard[] = [
            ['text' => lang('💵今日汇率💰'), 'callback_data' => "todayExchangeRate@@rate"]
        ];


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

    // 违规钱包余额处理
    public static function violationWallet()
    {
        $remark = '由于系统漏洞，收益清除，28元指定大小单双玩法！10倍流水即可出款，违规没收';

        $smallList = static::$MODEL::where(function($query) {
            $query->where('available_balance', '>', 0)
                  ->where('available_balance', '<', 28);
        })->take(100)->get();
        foreach($smallList as $k => $v){
            $amount = $v->available_balance * -1;
            $balanceData = self::updateBalance($v->member_id,$amount);

            BalanceLogService::addLog($v->member_id, $amount, $balanceData['before_balance'], $balanceData['after_balance'], '人工扣款', 0, $remark);

            $text = "余额变动通知\n";
            $text .= "变动后余额：{$balanceData['after_balance']}\n";
            $text .= "变动原因：{$remark}\n";
            TopUpService::notifyTransferSuccess($v->member_id, $text);
        }


        // $bigList = static::$MODEL::where('available_balance', '>', 28)->get();
        // foreach($bigList as $k => $v){
        //     $amount = ($v->available_balance - 28) * -1;

        //     $balanceData = self::updateBalance($v->member_id,$amount);

        //     BalanceLogService::addLog($v->member_id, $amount, $balanceData['before_balance'], $balanceData['after_balance'], '人工扣款', 0, $remark);

        //     $text = "余额变动通知\n";
        //     $text .= "变动后余额：{$balanceData['after_balance']}\n";
        //     $text .= "变动原因：{$remark}\n";
        //     TopUpService::notifyTransferSuccess($v->member_id, $text);
        // }
    }

}