<?php

namespace App\Http\Controllers\Game;


use App\Facade\TableName;
use App\Game\Block;
use App\Game\Config\GameBasicConfig;
use Carbon\Carbon;
use App\Game\GameCard;
use App\Game\GlobalUserInfo;
use App\Game\Route;
use App\Game\RouteModel;
use App\Game\Services\BetbyService;
use App\Game\Services\BetbyTestService;
use App\Game\Services\OuroGameService;
use App\Game\Services\RouteService;
use App\Game\Services\TelegramAppService;
use App\Game\Style;
use App\Game\WebChannelConfig;
use App\Game\WebRegionConfig;
use App\Http\Controllers\Api\ApiController;
use App\Http\Controllers\Api\WeightConfigController;
use App\Http\Controllers\Controller;
use App\Http\helper\NumConfig;
use App\IpLocation;
use App\Models\AccountsInfo;
use App\Models\SystemStatusInfo;
use App\Jobs\IpRiskDetection;
use App\Services\ApkService;
use App\Services\VipService;
use App\Util;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;


// use Yansongda\Pay\Log;

class WebRouteController extends Controller
{

    protected $routeService;

    public function __construct(RouteService $routeService)
    {
        $this->routeService = $routeService;
    }

    public function Routes(Request $request)
    {

        GlobalUserInfo::UpdateLoginDate($request, true);
        $FPID = $request->input("bfp", "");
        $inApp = $request->input('ia', 0);

        // 仅加载顶层路由，并预加载所有嵌套子路由
        $routes = RouteModel::whereNull('parent_id')
            ->whereRaw(RouteService::getStateToWhereRaw($request))
            ->with('subs.subs.subs')  // 根据实际层级深度调整
            ->orderBy('index')
            ->get();

        $styles = Style::all();
        $blocks = Block::all();

        $config = RouteService::getChannelConfig($request);

        $guestOpen = $config->isGuestOpen();
        $disablePromote = $config->isDisablePromote();
        //在fb内，节省时间，不快速注册
        //if($inApp)$guestOpen=false;

        $upgradeBonus = intval($config->BONUS_VERIFY_PHONE());
        if ($guestOpen && !$upgradeBonus) {
            //游客模式打开，随时可以登录
            $upgradeBonus = SystemStatusInfo::OnlyGetCacheValue('BindPhoneReward') ?? 500;
        }
        $user = GlobalUserInfo::$me;//LoginController::checkLogin($request);
        if ($user) {
            $ua = $request->userAgent();
            if (stripos($ua, 'iPhone') !== false) {
                $mobileBand = 'iPhone';
            } else if (stripos($ua, 'iPad') !== false) {
                $mobileBand = 'iPad';
            } else if (stripos($ua, 'Android') !== false) {
                $mobileBand = 'Android';
            } else if (stripos($ua, 'Windows') !== false) {
                $mobileBand = 'PC';
            } else if (stripos($ua, 'Mac') !== false) {
                $mobileBand = 'Mac';
            }
            if (isset($mobileBand)) {
                AccountsInfo::saveMobileBand($user->UserID, $mobileBand);
            }
        }


        $hashadd = $request->input("hashadd", "");
        $isreg = 0;
        if (!empty($hashadd)) {
            try {
                $hashadd = json_decode($hashadd, true);
                if ($hashadd['type'] == 'tele') {
                    $teleUser = TelegramAppService::decodeHash($hashadd['data']);
                    if (intval($teleUser->UserID)) {
                        if (!$user || $user->UserID != $teleUser->UserID) {
                            $user = GlobalUserInfo::getGameUserInfo('UserID', $teleUser->UserID);
                        }
                    } else {
                        //不存在用户
                        if (!$user) {

                            $guestUser = (new LoginController())->registerUser($request, true);
                            if (!is_array($guestUser)) {
                                $guestUser->NickName = $teleUser->first_name;
                                $guestUser->save();
                                $isreg = 1;
                                $user = $guestUser;
                            }

                        }
                        if ($user) {
                            //绑定现有用户
                            $teleUser->UserID = $user->UserID;
                            $teleUser->GlobalUID = $user->GlobalUID;
                            $teleUser->save();
                        }
                    }

                }
            } catch (\Exception $e) {

            }
        }

        if (!$user) {
            $loginController = new LoginController();
            //游客模式打开，随时可以登录
            $user = $loginController->getUserByFPID($FPID);
//            if (!$user) {
//                $user = $loginController->registerUser($request, true);
//            }

        }

        $FF=$request->input('ff', '');
        $isPWA=$request->input('pwa', 0);
        $urlvars=json_decode($request->input('urlvars',''));

        if(!$user&&!empty($FF)&&$isPWA){
            $user=GlobalUserInfo::GetRecentLogin($request);
        }
        //转换成web数据
        //转换成web数据
        if ($user){
            // 异步派发 IP 风险检测
            $userId = $user->UserID ?? 0;
            $ip = IpLocation::getRealIp();
            if ($ip && $userId) {
                IpRiskDetection::dispatch($userId, $ip);
            }

            $user = GlobalUserInfo::toWebData($user);
            $config=WebChannelConfig::getByChannel($user['Channel']);
        } else{
            Util::WriteLog('routes_params',[$request]);
        }




        $data=['code'=>0,'data'=>$routes,'blocks'=>$blocks,'styles'=>$styles,'user'=>$user];


        $origin = $request->server('HTTP_ORIGIN') ?? $request->server('HTTP_REFERER')?? '*';
        $data['origin']=$origin;
        $isDesktop=($request->input('_d','m')=='d');
        $firstBonus=1;
        if(env('CONFIG_24680_NFTD_99',0)==0)if($config->Channel==99)$firstBonus=0;

        $registerBonus = SystemStatusInfo::OnlyGetCacheValue('GrantScoreCountNew') ?? 1000;

        $chat = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
            ->where('StatusName', 'Telegram')
            ->first();

        $servicelist = (new ApiController())->getServiceList();


//        $chat = "https://m.me/930365713484502";
        // 默认推荐游戏
        $defaultGameId = 931;
        $recommendGame = '/game/' . $defaultGameId;
        $popPwaBonus=$user?(Redis::get('pwa_bonus:'.$user['UserID'])??0):0;
        $ChannelPackageName = DB::table('QPPlatformDB.dbo.ChannelPackageName')->where('Channel',$config->Channel??100)
            ->first();


        // slotsPartner: 与 WebChannelConfig 通过 RegionID 关联且 RegionID 不为空的区域，且当前 $config 的 Channel 不在该区域的 BindChannels 中（即其他“伙伴”区域）
//        $currentChannel = $config->Channel;
//        $slotsPartner = WebRegionConfig::query()
//            ->where('RegionID', '!=', '')
//            ->whereIn('RegionID', function ($q) use ($currentChannel) {
//                $q->select('RegionID')
//                    ->from((new WebChannelConfig())->getTable())
//                    ->where('RegionID', '!=', '')
//                    ->where('Channel', '!=', $currentChannel);
//            })
//            ->get()
////            ->filter(function ($region) use ($currentChannel) {
////                $bindChannels = $region->BindChannels;
////                return !is_array($bindChannels) || !in_array((int)$currentChannel, $bindChannels);
////            })
//            ->map(function ($region) {
//                return [
//                    'DomainUrl' => $region->DomainUrl ?? '',
//                    'LogoUrl'   => $region->LogoUrl ?? '',
//                    'GameDesc'  => $region->GameDesc ?? '',
//                ];
//            })
//            ->values()
//            ->all();


        $GroupID=0;
        $RegionID = $request ? $request->input('regionid', '') : ($_REQUEST['regionid'] ?? '');
        if (empty($RegionID) && !empty($origin)) {
            $RegionID = explode('.', $origin)[str_starts_with($origin, 'www') ? 1 : 0];
        }
        if(!empty($RegionID)){
            $GroupID=WebRegionConfig::query()->where('RegionID',$RegionID)->value('GroupID')??0;
        }
        // slotsPartner: 与 WebChannelConfig 通过 RegionID 关联且 RegionID 不为空的区域，且当前 $config 的 Channel 不在该区域的 BindChannels 中（即其他“伙伴”区域）
        // $currentChannel = $config->Channel;
        $slotsPartner = WebRegionConfig::query()
            ->where('GroupID', $GroupID)
            ->whereIn('RegionID', function ($q) {
                $q->select('RegionID')
                    ->from((new WebChannelConfig())->getTable())
                    ->where('RegionID', '!=', '');
            })
            ->get()
            ->map(function ($region) {
                return [
                    'DomainUrl' => $region->DomainUrl ?? '',
                    'LogoUrl'   => $region->LogoUrl ?? '',
                    'GameDesc'  => $region->GameDesc ?? '',
                    'SC'        => $region->SuggestChannel ?? '',
                ];
            })
            ->values()
            ->all();


        // sharePop：用户注册日起满 3 个自然日后开始弹（例：1 日注册则 4 日及以后满足）
        $sharePop = 0;
        if ($user && isset($user['UserID'])) {
            $userModel = GlobalUserInfo::getGameUserInfo('UserID', $user['UserID']);
            if ($userModel && $userModel->RegisterDate) {
                $registerDate = Carbon::parse($userModel->RegisterDate)->startOfDay();
                $today        = Carbon::today();
                $user = GlobalUserInfo::toWebData($userModel);
                if ($today->gte($registerDate->copy()->addDays(3)) && $user['vip'] > 0) {
                    $sharePop = 1;
                } else if ($user['vip'] == 0 && time() > strtotime($userModel->RegisterDate) + 1800) {
                    $sharePop = 1;

                }
            }
        }

        $spe_key=$request->input('s_k', 0);
        $data['conf']=[
            'hall'=>env("CONFIG_24680_HALL")??GameBasicConfig::$HallServer,
            'DOLLAR'=>env("CONFIG_24680_DOLLAR")??GameBasicConfig::$DOLLAR,
            'currency'=>env("CONFIG_24680_CURRENCY","USD"),
            'promoteInstall'=>$disablePromote?0:($inApp?1:((RouteService::isTestOrLocalSite()||$isDesktop)?0:25)),
            'showInstall'=>$disablePromote?0:($inApp?1:((RouteService::isTestOrLocalSite()||$isDesktop)?0:25)),
            'guest'=>$guestOpen?1:0,
            'AdjustToken' => $ChannelPackageName?$ChannelPackageName->AdjustToken:null,
            'AdjustConfig' => $ChannelPackageName?$ChannelPackageName->AdjustConfig:null,
            'upgradeBonus'=>$upgradeBonus,

            'registerBonus' =>$registerBonus,

            'recommendGame' => $recommendGame,

            'LandscapeGames' => [962,963,964,965,966,967,972,973,974,975, 976, 977, 978, 979, 980, 982, 983,
                962, 941, 942, 943, 945, 946, 947, 948, 949, 950, 951, 952, 953,
                936, 938, 939,940,934],

            'getStateToWhereRaw' =>RouteService::getStateToWhereRaw($request),

//            'serviceLink' => $chat,
            'serviceLink' => $chat?$chat->StatusString:'https://m.me/930365713484502',
            'cs'          => $servicelist,

            'vipConfig' => VipService::getVipLevelConfig(),

            'popWheel'=>0,
            'firstBonus'=>$firstBonus,
            'popFirst'=>$firstBonus,
            'openRelief'=>$firstBonus,
            'popBindPhone'=>1,
            'popPwaBonus'  => $popPwaBonus,
            'jumplater'    => $config->isFbJumpLater(),
            'download'=>['light'=>$config->LightApk,'full'=>$config->FullApk,'bonus'=>$config->BONUS_PWA()],
            'registerOpen'=>$config->RegOpen??env('CONFIG_REG_OPEN','sms,mail'),//id,phone,sms,mail,guest
            'loginOpen'=>$config->LoginOpen??'id,phone,sms,mail,guest',
            'slotsPartner' => $slotsPartner,
            'outLimit' => ['cashapp' => 2000,'paypal' => 2000],
            'withdrawChannel' => ['cashapp','paypal'],
            'freeChannel' => ['paypal'],
            'sharePop' => $sharePop,
            's_k' => $this->quickLoad($spe_key, $user['UserID']??0, $FPID, $FF, $request->input('cookie', ''))??'',

            'weight1234' => WeightConfigController::getConfig(),

        ];


        $data['conf']['pf']=['type'=>$config->PlatformName,'id'=>$config->PlatformID];

//        if (!$user){
        Util::WriteLog('routes_rs',[$data['conf']]);
//        }

//        $data['request']=$request->all();
        return response()->json($data);
    }


    public function getRegisterGold(Request $request)
    {
        try {
            $user = $request->user();
            $UserID = $user->UserID;

            if ($user->Registed == 1) {
                return apiReturnFail('Fail');
            }

            // 添加金币（10金币）
            $addResult = OuroGameService::AddScore($UserID, 10 * NumConfig::NUM_VALUE, null, false);

            // 更新 webgame.GlobalUserInfo 的 Registed 字段
            DB::connection('mysql')->table('webgame.GlobalUserInfo')
                ->where('UserID', $UserID)
                ->update(['Registed' => 1]);

            // 更新 QPAccountsDB.dbo.AccountsInfo 的 Registed 字段
            DB::connection('write')->table('QPAccountsDB.dbo.AccountsInfo')
                ->where('UserID', $UserID)
                ->update(['Registed' => 1]);


            return apiReturnSuc([
                'user' => [
                    'InsureScore' => 10,
                    'Registed'    => 1,
                    'message'     => 'Success'
                ]

            ]);

        } catch (\Exception $e) {
            \Log::error('注册送金币失败：' . $e->getMessage(), [
                'UserID' => $UserID ?? 0,
                'trace'  => $e->getTraceAsString()
            ]);
            return apiReturnFail('领取失败：' . $e->getMessage());
        }
    }

    public function log(Request $request)
    {
        Util::writeLog("gamelog", [
            'user'    => $request->user(),
            'request' => $request->all()
        ]);
        return apiReturnSuc();
    }

    public function checkApkInstall(Request $request)
    {
        $user = $request->user();

        $FPID = $request->input("bfp", "");
        $ff = $request->input('ff', '');
        $url_sign = $request->input('us', RouteService::getChannel($request));

        $UserID = $user ? $user->UserID : "";
        $ip = $request->ip();
        $agent = $request->userAgent();
        $alen = strlen($agent);
        $key = "apktmp_{$url_sign}_$ip";


        Util::writeLog("apkload", [
            'FPID'     => $FPID,
            'FF'       => $ff,
            'url_sign' => $url_sign,
            'user'     => $user,
            'ip'       => IpLocation::getRealIp(),
            'agent'    => $agent,
            'req'      => $request->all()
        ]);

        $agent = explode('AppleWebKit', $agent)[0];
        //截取到最后一个分号Mozilla/5.0 (Linux; Android 16; SM-S936U Build/BP2A.250605.031.A3; wv) 去掉了wv和后面
        $lastSemicolon = strrpos($agent, ';');
        if ($lastSemicolon !== false) {
            $agent = substr($agent, 0, $lastSemicolon);
        }

        $cookieExist = ApkService::loadCookie($UserID, $FPID, $ff, $request->input('cookie', ''));
        if ($cookieExist && is_array($cookieExist)) {
            $data = [];
            $data['cookie'] = $cookieExist['Cookie'] ?? "";
            $data['params'] = $cookieExist['Params'] ?? "";
            $data['ls'] = $cookieExist['LocalStorage'] ?? "";
            $data['us'] = $cookieExist['UrlSign'] ?? "";
            $data['type'] = $cookieExist['Platform'] ?? "";
            $data['agent'] = $cookieExist['ClickUA'] ?? "";
            $data['origin'] = $_SERVER['HTTP_ORIGIN'] ?? $_SERVER['HTTP_REFERER'] ?? '*';
            Util::writeLog("apkload", "existUser:::" . json_encode($data));
            return apiReturnSuc($data);
        }
        $datas = [];
        if (Redis::exists($key)) {
            $datas = json_decode(Redis::get($key), true);

            //规则1，只有一个数据，直接归1
            if (count($datas) == 1) {
                Redis::del($key);
                ApkService::saveCookie($UserID, $datas[0], $FPID, $ff);
                Util::writeLog("apkload", "onlyone:::" . json_encode($datas[0]));
                return apiReturnSuc($datas[0]);
            }
            Util::WriteLog("apkload", $datas);

            foreach ($datas as $k => $v) {
                if (strstr($v['agent'], $agent) || $ff == $v['ff']) {
                    array_splice($datas, $k, 1);
                    Redis::set($key, json_encode($datas));
                    Redis::expire($key, 7200);
                    ApkService::saveCookie($UserID, $v, $FPID, $ff);
                    Util::writeLog("apkload", "sameagent:::" . json_encode($v));
                    return apiReturnSuc($v);
                }
            }

        }
        $recents = ApkService::getRecentsNew($url_sign);
        foreach ($recents as $v) {
            if (strstr($v['agent'], $agent) || $ff == $v['ff']) {
                ApkService::saveCookie($UserID, $v, $FPID, $ff);
                Util::writeLog("apkload", "recent:::" . json_encode($v));
                return apiReturnSuc($v);
            }
        }
        return apiReturnFail("");

    }
    public function quickLoad($spe_key=null, $UserID=0, $FPID='', $FF='', $cookie='')
    {
        $data=null;
        $fbclid = ApkService::extractFbclid($cookie);

        if($spe_key){
            $key = "quick_{$spe_key}";
            if(Redis::exists($key)) {
                $data = json_decode(Redis::get($key), true);
            }
        }
        if(!$data){
            $table = TableName::QPAccountsDB() . "AccountCookie";
            $obj=null;
            if($spe_key) {
                $candidates = DB::table($table)->where('SPE_KEY', $spe_key)->orderBy('CreateTime', 'desc')->get();
                $obj = ApkService::pickBestCandidate($candidates, $fbclid);
            }
            if(!$obj && $UserID){
                $candidates = DB::table($table)->where('UserID', $UserID)->orderBy('CreateTime', 'desc')->get();
                $obj = ApkService::pickBestCandidate($candidates, $fbclid);
            }
            if(!$obj && (!empty($FPID) || !empty($FF))){
                $query = DB::table($table);
                if (!empty($FPID) && !empty($FF)) {
                    $query->where(function ($q) use ($FPID, $FF) {
                        $q->where('FPID', $FPID)->orWhere('FF', $FF);
                    });
                } elseif (!empty($FPID)) {
                    $query->where('FPID', $FPID);
                } else {
                    $query->where('FF', $FF);
                }

                $candidates = $query->orderBy('CreateTime', 'desc')->get();
                $obj = ApkService::pickBestCandidate($candidates, $fbclid);
            }
            try {
                if(!$obj && !empty($fbclid)){
                    $obj = DB::table($table)
                        ->where('Cookie', 'like', '%' . $fbclid . '%')
                        ->orderBy('CreateTime', 'desc')
                        ->first();
                }
            }catch (\Exception $e) {
                Util::WriteLog('invalid_cookie',$fbclid);
                $obj = null;
            }


            if($obj){
                $data=['type'=>$obj->Platform,'cookie'=>$obj->Cookie,'s_k'=>$obj->SPE_KEY, 'url_sign'=>$obj->UrlSign, 'params'=>$obj->Params, 'ff'=>$obj->FF, 'localStorage'=>$obj->LocalStorage];
            }
        }

        return $data;
    }
    public function quickSave(Request $request)
    {
        $FPID = $request->input("bfp", "");
        $ff = $request->input('ff', '');
        $url_sign = RouteService::getChannel($request);

        $UserID =$request->user()?$request->user()->UserID:0;
        $ip = IpLocation::getRealIp();
        $agent = $request->userAgent();



        ///gg or fb
        $type = $request->get('type') ?? "fb";
        $cookie = $request->get('cookie') ?? '';
        $localStorage = $request->get('ls') ?? '';
        $params = $request->get('params') ?? '';

        $origin = $_SERVER['HTTP_ORIGIN'] ?? $_SERVER['HTTP_REFERER'] ?? '*';
        $time = time();

        $spe_key = $request->input('s_k',0);
        if(!$spe_key)$spe_key=$this->md5Base62($cookie . $localStorage . $params);

        $locale = $request->get('locale') ?? '';

        $data = compact('ip', 'agent', 'cookie', 'type', 'url_sign', 'time', 'params', 'locale', 'origin', 'ff', 'localStorage');

        $key = "quick_{$spe_key}";
        if (Redis::exists($key)) {
            $cached = json_decode(Redis::get($key), true);
            if (is_array($cached)) {
                $data = $this->mergeQuickData($cached, $data);
            }
        }

        ApkService::saveCookie($UserID, $data, $FPID, $ff,$spe_key);

        Redis::set($key, json_encode($data));
        Redis::expire($key, 7200);

        Util::WriteLog("saveQuick", $data);

        return apiReturnSuc(['s_k'=>$spe_key]);
    }

    public function saveEnv(Request $request)
    {
        $user = $request->user();
        $FPID = $request->input("bfp", "");
        $ff = $request->input('ff', '');
        $url_sign = $request->input('us', RouteService::getChannel($request));

        $UserID = $user ? $user->UserID : "";
        $ip = IpLocation::getRealIp();
        $agent = $request->userAgent();
        $alen = strlen($agent);
        $key = "apktmp_{$url_sign}_$ip";


        ///gg or fb
        $type = $request->get('type') ?? "fb";
        $cookie = $request->get('cookie') ?? '';
        $localStorage = $request->get('ls') ?? '';
        $params = $request->get('params') ?? '';

        $origin = $_SERVER['HTTP_ORIGIN'] ?? $_SERVER['HTTP_REFERER'] ?? '*';
        $time = time();


        $locale = $request->get('locale') ?? '';

        $data = compact('ip', 'agent', 'cookie', 'type', 'url_sign', 'time', 'params', 'locale', 'origin', 'ff', 'localStorage');

        $cookieExist = ApkService::loadCookie($UserID, $FPID, $ff, $cookie);
        if (!$cookieExist) {
            ApkService::saveCookie($UserID, $data, $FPID, $ff);

            $key = "apktmp_{$url_sign}_$ip";
            $datas = [];
            if (Redis::exists($key)) {
                $datas = json_decode(Redis::get($key), true);
                //防止重复压入
                foreach ($datas as $v) {
                    if ($data['agent'] == $v['agent'] && $data['type'] == $v['type']) {
                        return apiReturnSuc(1);
                    }
                }
            }
            array_unshift($datas, $data);

            Redis::set($key, json_encode($datas));
            Redis::expire($key, 7200);

            //压入最近记录
            ApkService::addRecentsNew($data, $url_sign);
            //写入快手
            if ($type == 'kw') {
                ApkService::sendToKwai(json_decode($cookie, true), ApkService::KWAI_EVENT['EVENT_DOWNLOAD']);
            }

            Util::WriteLog("saveEnv", $data);


        }


        return apiReturnSuc(1);
    }

    private function mergeQuickData(array $cached, array $current)
    {
        $merged = $cached;
        foreach ($current as $k => $v) {
            if ($k === 'cookie' || $k === 'params') {
                continue;
            }
            if ($v !== '' && $v !== null) {
                $merged[$k] = $v;
            }
        }

        $merged['cookie'] = $this->mergeCookieString($cached['cookie'] ?? '', $current['cookie'] ?? '');
        $merged['params'] = $this->mergeParamsString($cached['params'] ?? '', $current['params'] ?? '');

        return $merged;
    }

    private function mergeParamsString($cached, $current)
    {
        if ($cached === '') return $current;
        if ($current === '') return $cached;

        $cachedJson = json_decode($cached, true);
        $currentJson = json_decode($current, true);
        if (is_array($cachedJson) && is_array($currentJson)) {
            return json_encode(array_replace_recursive($cachedJson, $currentJson), JSON_UNESCAPED_UNICODE);
        }

        $cachedArr = [];
        $currentArr = [];
        parse_str($cached, $cachedArr);
        parse_str($current, $currentArr);
        if (!empty($cachedArr) || !empty($currentArr)) {
            return http_build_query(array_replace($cachedArr, $currentArr));
        }

        if ($cached === $current) return $current;
        return $cached . '&' . $current;
    }

    private function mergeCookieString($cached, $current)
    {
        if ($cached === '') return $current;
        if ($current === '') return $cached;

        $cachedJson = json_decode($cached, true);
        $currentJson = json_decode($current, true);
        if (is_array($cachedJson) && is_array($currentJson)) {
            return json_encode(array_replace_recursive($cachedJson, $currentJson), JSON_UNESCAPED_UNICODE);
        }

        $cookies = $this->parseCookiePairs($cached);
        $newCookies = $this->parseCookiePairs($current);
        if (!empty($cookies) || !empty($newCookies)) {
            $cookies = array_replace($cookies, $newCookies);
            $cookieParts = [];
            foreach ($cookies as $k => $v) {
                $cookieParts[] = $k . '=' . $v;
            }
            return implode('; ', $cookieParts);
        }

        if ($cached === $current) return $current;
        return $cached . '; ' . $current;
    }

    private function parseCookiePairs($cookieStr)
    {
        $pairs = [];
        foreach (explode(';', $cookieStr) as $segment) {
            $segment = trim($segment);
            if ($segment === '') {
                continue;
            }
            $pos = strpos($segment, '=');
            if ($pos === false) {
                continue;
            }
            $name = trim(substr($segment, 0, $pos));
            $value = trim(substr($segment, $pos + 1));
            if ($name !== '') {
                $pairs[$name] = $value;
            }
        }
        return $pairs;
    }

    /**
     * 环境短 key：MD5 二进制取前 6 字节（48bit）再 base62，长度 <=9（10 字符以内）。
     * PHP 对齐示例：$b = substr(md5($value, true), 0, 6); 再对 $b 做相同 base62 循环。
     */
    private function md5Base62($value)
    {
        $b = substr(md5($value, true), 0, 6);
        $bytes = array_values(unpack('C*', $b));
        $alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        $result = '';

        while (!empty($bytes)) {
            $quotient = [];
            $remainder = 0;

            foreach ($bytes as $byte) {
                $acc = ($remainder << 8) + $byte;
                $q = intdiv($acc, 62);
                $remainder = $acc % 62;
                if (!empty($quotient) || $q !== 0) {
                    $quotient[] = $q;
                }
            }

            $result = $alphabet[$remainder] . $result;
            $bytes = $quotient;
        }

        return $result === '' ? '0' : $result;
    }

    public function SaveRoutes(Request $request)
    {

        // Assuming $jsonData is your JSON data
        $jsonData = json_decode(file_get_contents('path_to_your_json_file.json'), true);

        foreach ($jsonData['data'] as $routeData) {
            $this->insertRoute($routeData);
        }
    }

    function insertRoute($routeData, $parentId = null)
    {
        $route = new RouteModel([
            'parent_id' => $parentId,
            'path'      => $routeData['path'],
            'type'      => $routeData['type'],
            'side'      => $routeData['side'],
            'block'     => $routeData['block'],
            'title'     => $routeData['title'],
            'icon'      => $routeData['icon'],
            'fill'      => $routeData['fill'],
            'component' => $routeData['component'],
            'query'     => $routeData['query'],
            'login'     => $routeData['login'],
            'lpath'     => $routeData['lpath']
        ]);
        $route->save();

        foreach ($routeData['subs'] as $sub) {
            $this->insertRoute($sub, $route->id);
        }
    }


    public function testScoreChange(Request $request)
    {
        $user = $request->user();
        $nowGolds = $request->input("nowGolds", 4000);
        $AddNum = $request->input("AddNum", 1000);
//        notifyWebHall($UserID,"",'pay_finish',["Golds"=>$NowScore,"PayNum"=>$GiftScore]);
        OuroGameService::notifyWebHall($user->UserID, "", 'call_client', ["Golds" => $nowGolds, "AddNum" => $AddNum, "type" => "start_change"]);
//        ($user_id,$GlobalUID,'call_client',["type"=>"refresh_mail"]);
        return apiReturnSuc("");
    }

}
