<?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\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::toWebData($user);
//            $user['reg']=$isreg;
        }else if($guestOpen){
            //游客模式打开，随时可以登录
            $guestUser=GlobalUserInfo::getGameUserInfo('FPID',$FPID);
            if(!$guestUser){
//                $guestUser = GlobalUserInfo::getGameUserInfo('FPID', $FPID);
//                if (!$guestUser) {
                    $guestUser=(new LoginController())->registerUser($request,true);
                    if(is_array($guestUser)){
                        //出现错误
                    }else{
                        $user=GlobalUserInfo::toWebData($guestUser);
//                        $user['Registed'] = 0;
                    }
//                }
            }else{
                $user=GlobalUserInfo::toWebData($guestUser);
            }

        }
        $user['vip'] = 0;

        //LoginController::CheckTimeBonus($user);

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


        $origin = $request->server('HTTP_ORIGIN') ?? $request->server('HTTP_REFERER')?? '*';
        $data['origin']=$origin;
        $BBService=new BetbyService();
        if(RouteService::isTestSite()) {
            $data['fpid'] = $FPID;
            $data['request']=$request->all();
            $data['gopen'] = $guestOpen;

            Util::WriteLog('pro','');
            $BBService=new BetbyTestService();
        }
        $isDesktop=($request->input('_d','m')=='d');

        $bb=[
            'id'=>$BBService->brandId,
            'theme'=>['demo-green-dark-card','bc-game-light-tile'],
//            'theme'=>['default-table','default-table'],
            'token'=>$user?$BBService->getDefaultJWT($user):null
        ];
        $firstBonus=1;
        if(env('CONFIG_24680_NFTD_99',0)==0)if($config->Channel==99)$firstBonus=0;

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

        $recommendGame = '/game/pgsoft/lunch?gid=68';

        $data['conf']=[
            'bb'=>$bb,
            '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,
            'upgradeBonus'=>$upgradeBonus,

            'registerBonus' =>$registerBonus,

            'recommendGame' => $recommendGame,

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

            'popWheel'=>0,
            'firstBonus'=>$firstBonus,
            'popFirst'=>$firstBonus,
            'openRelief'=>$firstBonus,
            'popBindPhone'=>1,
            '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","");
        $url_sign=$request->get('us')??"tf";
        $UserID=$user?$user->UserID:"";
        $ip=$request->ip();
        $agent=$request->userAgent();
        $alen=strlen($agent);
        $key="apktmp_{$url_sign}_$ip";

        if(isset($UserID)&&!empty($UserID)) {
            $cookieExist = ApkService::loadCookie($UserID);
            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']?? '*';

                return apiReturnSuc($data);
            }
        }
        $datas=[];
        if(Redis::exists($key)){
            $datas=json_decode(Redis::get($key),true);

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

            foreach ($datas as $k=>$v){
                if($v['agent']==$agent||substr($v['agent'],0,$alen)==$agent){
                    array_splice($datas,$k,1);
                    Redis::set($key,json_encode($datas));
                    Redis::expire($key,7200);
                    ApkService::saveCookie($UserID,$v,$FPID);
                    return apiReturnSuc($v);
                }
            }

        }
        $recents=ApkService::getRecentsNew($url_sign);
        foreach ($recents as $v){
            if($v['agent']==$agent||substr($v['agent'],0,$alen)==$agent||$ip==$v['ip']){
                ApkService::saveCookie($UserID,$v,$FPID);
                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("");
    }

}
