<?php


namespace App\Services;

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;

/**
 * 用户虚拟币钱包
*/
class WalletService extends BaseService 
{
    /**
     * @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 self::model()::where(self::getWhere($search))->first();
    }

    /**
     * @description: 查询所有数据
     * @param array $search
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public static function findAll(array $search = [])
    {
        return self::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 = self::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]);


        $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();
        
        // 批量创建钱包以提高性能
        self::model()::insert($walletsData);

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

    /**
     * @description: 获取用户的钱包
     * @param {int} $memberId 
     * @return {*}
     */    
    public static function getUserWallet(int $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]);
        $path = self::rechargeQrCodeExists($info->address);
        if(empty($path)){
            $path = self::createRechargeQrCode($info->address);
        }

        // $host = config('app.url'); // 通常在 .env 中配置 APP_URL
        return [
            'coin' => $info->coin,
            'net' => $info->net,
            'address' => $info->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]);

        $text = '';
        $text .= "用户ID：{$memberId} \n";
        $text .= "用户名：{$userInfo->first_name} \n";
        $text .= "当前余额：{$selfInfo->available_balance} \n";

        $keyboard = [
            [
                ['text' => '➕充值', 'callback_data' => "topup@@topup"],
                ['text' => '🧾账单', 'callback_data' => "topup@@bill"],
            ]
        ];

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