<?php

namespace App\Http\Controllers\Game;


use App\Game\Block;
use App\Game\Config\GameBasicConfig;
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\Http\Controllers\Controller;
use App\Http\helper\NumConfig;
use App\IpLocation;
use App\Models\AccountsInfo;
use App\Models\SystemStatusInfo;
use App\Services\ApkService;
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);

        $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){
            //游客模式打开，随时可以登录
            $user=GlobalUserInfo::getGameUserInfo('FPID',$FPID);
        }

        $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数据
        if ($user){
            $user = GlobalUserInfo::toWebData($user);
        } 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();

        // 默认推荐游戏
        $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();
        $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?$chat->StatusString:'',

            'popWheel'=>0,
            'firstBonus'=>$firstBonus,
            'popFirst'=>$firstBonus,
            'openRelief'=>$firstBonus,
            'popBindPhone'=>1,
            'popPwaBonus'  => $popPwaBonus,
            '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'
        ];


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

//        $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 checkApkInstall(Request $request)
    {
        $user = $request->user();

        $FPID = $request->input("bfp", "");
        $ff=$request->input('ff', '');
        $url_sign = $request->get('us') ?? "tf";

        $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);
        }

        if (isset($UserID) && !empty($UserID)) {
            $cookieExist = ApkService::loadCookie($UserID,$FPID,$ff);
            if ($cookieExist && is_array($cookieExist)) {
                $data = [];
                $data['cookie'] = $cookieExist['Cookie'] ?? "";
                $data['params'] = $cookieExist['Params'] ?? "";
                $data['url_sign'] = $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 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("");
    }


}
