<?php

namespace App\Http\Controllers\Game;


use App\Game\Config\GameBasicConfig;
use App\Game\GameCard;
use App\Game\GlobalUserInfo;
use App\Game\LogGamecardClick;
use App\Game\PageModule;
use App\Game\Services\OuroGameService;
use App\Http\Controllers\Api\ApiController;
use App\Http\Controllers\Controller;
use App\Models\AccountsInfo;
use App\Models\Treasure\GameScoreLocker;
use App\Services\IpCheck;
use App\Util;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;


// use Yansongda\Pay\Log;

class GameController extends Controller
{


    public function __construct()
    {

    }
    public function GetGameInfo(Request $request)
    {
        $id=$request->input('id');
        $card=GameCard::GetGameByID($id);
        return apiReturnSuc($card);
    }
    public function Ouro777GamePage(Request $request)
    {
        $this->CheckOuroGamePort();




        $gid=$request->input('gid');
        $level=$request->input('level',1);
        $user = $request->globalUser;
        $userid=$user->UserID;
        $lang=GlobalUserInfo::getLocale();
        $clientLang='en';
        if($lang=='pt')$clientLang='pu';
        else if($lang=='es')$clientLang='sp';
        else $lang='en';
        GameScoreLocker::where('UserID',$userid)->delete();

        $Dollar=GameBasicConfig::$DOLLAR;//['pt'=>'R$','en'=>'$','es'=>'M$'];
        GameCard::$enableStateCheck=false;
        $gamecard=GameCard::where('gid',$gid)->where('brand','OURO777')->first();


        $in_gameid=OuroGameService::getUserInGame($userid,$user->GlobalUID);
        if($in_gameid!=intval($gamecard->id)){
            Util::WriteLog('24680game',compact('in_gameid','gamecard','user'));
//            die;
        }

        $gamecard->increment('play_num',1);
        $this->logGameClick($gamecard->id,$userid);

        $servers=DB::table('QPPlatformDB.dbo.GameRoomInfo')
            ->where("Nullity",0)
            ->where("Alive",1)
            ->where("SortID",$level)
            ->where('GameID',$gid)->get()->toArray();
        $rand=$servers[array_rand($servers)];
        $rand=(object)$rand;
        $server=[
            "KindID"=> $rand->GameID,
            "NodeID"=> $rand->NodeID,
            "SortID"=> $rand->SortID,
            "ServerID"=> $rand->ServerID,
            "ServerType"=> $rand->ServerType,
            "ServerPort"=> $rand->ServerPort,
            "CellScore"=> $rand->CellScore,
            "EnterScore"=> $rand->MaxEnterScore,
            "ServerRule"=> $rand->MaxEnterScore,
            "OnLineCount"=> 1,
            "AndroidCount"=> 0,
            "FullCount"=> 100,
            "ServerAddr"=> "1.1.1.1",
            "ServerName"=> $rand->ServerName,
            "GameKindItem"=> [
                "TypeID"=> 2,
                "JoinID"=> 0,
                "SortID"=> $rand->SortID,
                "KindID"=> $rand->GameID,
                "GameID"=> $rand->GameID,
                "OnLineCount"=> 0,
                "FullCount"=> 0,
            ]
        ];


        $loginData=$this->LoginIPData($request);
        $account=new AccountsInfo();
        $userData=$account->newQuery()->where('UserID',$userid)->get()->first()->toArray();
        $userData['UserScore']=$account->Score($userid);
        $userData['Accounts']=$userData['RegisterMachine'];
        $userData['GroupName']=$userData['DynamicPass'];

        unset($userData['RegAccounts'],$userData['Compellation'],$userData['InsurePass'],$userData['LogonPass'],$userData['RegisterMachine'],$userData['DynamicPass'],$userData['RegisterDate'],$userData['RegisterIP'],$userData['LastLogonMachine'],$userData['LastLogonDate']);

        $loading_rand=random_int(1,3);

        $loading_color=["","#153343","#211411","#21171c"][$loading_rand];
        $open_acts=[1];
        $act_rand=$open_acts[random_int(0,count($open_acts)-1)];


        if(!in_array($lang,['pt','es','en'])){
            $lang='en';
        }
        $isDesktop=($request->input('_d','m')=='d');

        return view($isDesktop?"game.ouro.br24680land":"game.ouro.br24680",compact('userData','server','loginData','lang','Dollar','clientLang','loading_rand','act_rand','loading_color'));
    }
    public function logGameClick($gameid,$UserID)
    {
        LogGamecardClick::recordClick($gameid,$UserID);
    }

    public function CheckOuroGamePort()
    {
        $existKey="OuroGamePortChecked";
        if(Redis::exists($existKey)){
           return;
        }
        Redis::set($existKey,1);
        Redis::expire($existKey,600);
        $ouroGameInfos=[];
//        echo "http://ouro777:happiplay123@".env('CONFIG_OURO_WSS').":1088/haproxy;up;csv;norefresh";die;

        $stats=file_get_contents("http://ouro777:happiplay123@".env('CONFIG_OURO_WSS').":1088/haproxy;up;csv;norefresh");
        $stats=explode("\n",$stats);
        $stats=array_filter($stats,function($stat){
            return strstr($stat,"ws_backend_")&&strstr($stat,",UP")&&!strstr($stat,",BACKEND");
        });

        $portSort=[];
        $stats=array_map(function($stat) use (&$portSort){
            $stat=str_replace('ws_backend_','',$stat);
            $stat=explode(',',$stat);
            $portSort[$stat[0]]=$stat[73];
            return [$stat[0],$stat[73]];
        },$stats);

//        print_r($stats);
//        print_r($portSort);die;

        $servers=DB::table('QPPlatformDB.dbo.GameRoomInfo')->where("Nullity","0")->get();
        foreach ($servers as $server){
            $Alive=$server->Alive;
            $LocalAddress=$server->LocalAddress;
            if(isset($portSort[strval($server->ServerPort)])){
                $Alive=1;
                $LocalAddress=$portSort[strval($server->ServerPort)];
            }else{
                $Alive=0;
            }
            if($Alive==1){
                //更新记录
                if(!isset($ouroGameInfos[$server->GameID])){
                    $ouroGameInfos[$server->GameID]=[];
                };
                $ouroGameInfos[$server->GameID][$server->SortID]=$server->MinEnterScore;
            }
//            print_r($server);
            if($Alive!=$server->Alive||$LocalAddress!=$server->LocalAddress){
                DB::table('QPPlatformDB.dbo.GameRoomInfo')->where('ServerID',$server->ServerID)->update(compact('Alive','LocalAddress'));
            }
        }
        GameCard::setOuroGameInfo($ouroGameInfos);
        return $ouroGameInfos;
    }
    public function ModuleStat()
    {
        try {
            $stat = LogGamecardClick::getWeeklyStatsByBrand();

            $gameIdsAll = $stat['ALL'];

            $orderClause = 'FIELD(id, ' . implode(',', $gameIdsAll) . ')';
            $gameIdsAll = GameCard::select('id')->whereIn('id', $gameIdsAll)->orderByRaw($orderClause)->limit(16)->pluck('id')->toArray();
            $stat['ALL'] = implode(', ', array_slice($gameIdsAll, 0, 16));

            foreach ($stat as $brand => $gameids) {
                if (PageModule::where('data_key', $brand . '_top')->exists()) PageModule::where('data_key', $brand . '_top')->update(['game_ids' => $gameids]);
            }
            if (PageModule::where('data_key', 'hot_game')->exists()) PageModule::where('data_key', 'hot_game')->update(['game_ids' => implode(', ', array_slice($gameIdsAll, 0, 50))]);
            $this->CheckOuroGamePort();


            dd($stat);
        }catch (\Exception $e){

        }
    }

    private function LoginIPData(Request $request){

        $PackageName='com.24680.br';
        $v = $request->get('v')??0;
        $service = new IpCheck();

        $list = (new ApiController())->getLoginIpMap($PackageName);
        $login_ip = $request->ip();
//        $ipcheck=$service->ipCheck($login_ip,$PackageName,$v);


        $data = [
            'list' => $list,
            'login_ip' => $login_ip,
            'kefu_switch' => 0,
            'ip_check' => true,
            'ip_black'=>false,
            'base_url'=>'',//多对多跳转
            'chatport'=>8340,
            'loc'=>'br',
            'wss_server'=>'wss://'.env('CONFIG_OURO_WSS').':',
            'org'=>true,
        ];
        return $data;
    }
    // 客服功能
    public function customer_service()
    {
        $list=(new ApiController())->getServiceList();
        foreach($list as $k=>$v){
            if($v->StatusString=="cs@ouro777.com"){
                $v->StatusString="cs@24680.com";
            }
        }
        return apiReturnSuc($list);
    }
}
