<?php

namespace App\Services;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Log;

class VipService
{
    /**
     * 计算用户VIP等级
     * 
     * @param int $userId 用户ID
     * @return int VIP等级
     */
    public static function calculateVipLevel($userId,$userRecharge=0)
    {
        if (!$userId) {
            return 0;
        }

        try {
            // 获取用户累计充值金额（从 YN_VIPAccount 表）

            // 如果没有充值记录，返回VIP 0
            if ($userRecharge <= 0) {
                return 0;
            }

            // 获取VIP等级配置（从 ProtectLevel 表）
            $vipLevels = self::getVipLevelConfig();

            // 根据充值金额查找对应的VIP等级
            // 规则：找到 MinRecharge <= userRecharge < Recharge 的等级
            $vipLevel = 0;
            foreach ($vipLevels as $level) {
                if ($userRecharge >= $level->MinRecharge && $userRecharge < $level->Recharge) {
                    $vipLevel = $level->VIP;
                    break; // 因为已按MinRecharge升序排列，可以提前退出
                }
            }

            return intval($vipLevel);

        } catch (\Exception $e) {
            Log::error('VIP等级计算失败', [
                'user_id' => $userId,
                'error' => $e->getMessage()
            ]);
            return 0;
        }
    }

    /**
     * 获取VIP等级配置（带缓存）
     * 
     * @return \Illuminate\Support\Collection
     */
    public static function getVipLevelConfig()
    {
        $cacheKey = 'vip_level_config';
        
        // 尝试从Redis获取
        if (Redis::exists($cacheKey)) {
            $data = Redis::get($cacheKey);
            return collect(json_decode($data));
        }

        // 从数据库查询（按MinRecharge升序排列）
        $levels = DB::table('QPAccountsDB.dbo.ProtectLevel')
            ->orderBy('MinRecharge', 'asc')
            ->select('ID', 'VIP', 'MinRecharge', 'Recharge', 'WithdrawLimit', 'DailyWithdraws', 'GrantNum', 'LevelUpBonus',
             'WithdrawFeeRate', 'SignAlpha', 'Alpha', 'CustomServiceType', 'RechargeExtraSendRate', 'SuperballNum', 'BirthdayValue')
            ->get();

        // 缓存10分钟
        Redis::setex($cacheKey, 600, json_encode($levels));

        return $levels;
    }

    /**
     * 通过某个字段获取vip信息
     * @param $field
     * @param $value
     * @return mixed|null
     */
    public static function getVipByField($field, $value)
    {
        $vipLevels = self::getVipLevelConfig();
        foreach ($vipLevels as $level) {
            if ($level->{$field} == $value) {
                return $level;
            }
        }
        return null;
    }

    public static function getKeepLevelMinRecharge()
    {
        return DB::table('QPAccountsDB.dbo.SystemStatusInfo')
            ->where('StatusName', 'ProtectLevelKeepMinRecharge')
            ->value('StatusValue');
    }
}
