<?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\IpLocation;
use App\Jobs\Order;
use App\Models\AccountsInfo;
use App\Models\Cpf;
use App\Models\PrivateMail;
use App\Models\RecordScoreInfo;
use App\Models\SystemStatusInfo;
use App\Notification\TelegramBot;
use App\Services\Custom;
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 ApiController extends Controller
{

    public function sendTele(Request $request)
    {
        TelegramBot::getDefault()->sendMsg($request->str);
    }
    public function log(Request $request){
        Util::WriteLog("log",$request->all());
    }

    public function checkLocale(Request $request){
        $UserID=$request->input("UserID");
        $user=AccountsInfo::where("UserID",$UserID)->first();
        if(!$user){
            return apiReturnFail(['web.error.user_not_exist',__('messages.api.user.user_not_exist')]);
        }
        $Locale=$user->BindLocale;
        return apiReturnSuc(compact('UserID','Locale'));
    }
    public function bindLocale(Request $request){
        $UserID=$request->input("UserID");
        $Locale=$request->input("Locale");
        $user=AccountsInfo::where("UserID",$UserID)->first();
        if(!is_string($Locale))$Locale='en';
        if(!$user){
            return apiReturnFail(['web.error.user_not_exist',__('messages.api.user.user_not_exist')]);
        }

        if(strstr(env('VALID_LOCALE','pt,en,es'),$Locale)){
            return apiReturnFail(['web.error.Locale_not_found',__('messages.api.user.locale_not_supported')]);
        }
        AccountsInfo::where("UserID",$UserID)->update(["BindLocale"=>$Locale]);
        return apiReturnSuc(compact('UserID','Locale'));
    }
    public function checkCountry(Request $request){
        $UserID=$request->input("UserID");
        $user=AccountsInfo::where("UserID",$UserID)->first();
        if(!$user){
            return apiReturnFail(['web.error.user_not_exist',__('messages.api.user.user_not_exist')]);
        }
        $Country=$user->BindCountry;
        return apiReturnSuc(compact('UserID','Country'));
    }
    public function bindCountry(Request $request){
        $UserID=$request->input("UserID");
        $Country=$request->input("Country");
        $user=AccountsInfo::where("UserID",$UserID)->first();
        if(!is_string($Country))$Country='CO';
        if(!$user){
            return apiReturnFail(['web.error.user_not_exist',__('messages.api.user.user_not_exist')]);
        }
//        if(!empty($user->BindCountry)&&$user->BindCountry!=$Country){
//            return apiReturnFail(['web.error.user_already_bind',__('messages.api.user.user_already_bind')]);
//        }
        if(!isset(IpCheck::$countries[$Country])){
            return apiReturnFail(['web.error.country_not_found',__('messages.api.user.country_not_found')]);
        }
        AccountsInfo::where("UserID",$UserID)->update(["BindCountry"=>$Country]);
        return apiReturnSuc(compact('UserID','Country'));
    }

    public function errorReport(Request $request){
        Util::WriteLog('clientError',$request->header());
        try {
            $config = $request->input('config');
            $sign = $request->input('s');
            if (md5($config . 'nicaia') == $sign) {
                $exception = $request->input('exception');
                $config = $request->input('config');
                $uid = $request->input('uid');

                $hash = md5($exception);

                $config = substr($config, 0, 3000);

                $userinfo = ['ErrorID' => 0, 'IP' => $request->ip(), 'UserID' => $uid, 'Config' => $config, 'Lang' => $request->header('accept-language') ?? '', 'UserAgent' => substr($request->header('user-agent') ?? '', 0, 200)];

                $exception = \GuzzleHttp\json_decode($exception, true);
                $config = \GuzzleHttp\json_decode($config, true);
                $config['firstUseIpList'] = array_slice($config['firstUseIpList'], 0, 1);

                $userinfo['Config'] = json_encode($config);

                $exception = ['HashKey' => $hash, 'Msg' => urldecode($exception[2]), 'Stack' => urldecode($exception[3]), 'Package' => $config['AppId'] . '_' . $config['ClientVersion'], 'Channel' => Util::getPackageByURL($config['AppId'])['channel']];


                $package = $exception['Package'];

                $error = DB::table("QPRecordDB.dbo.ClientError")->where(["HashKey" => $hash, 'Package' => $package])->first();

                if (!$error) {
                    $userinfo['ErrorID'] = DB::table("QPRecordDB.dbo.ClientError")->insertGetId($exception);
                } else {
                    $userinfo['ErrorID'] = $error->ID;
                    if ($error->DateKey != date("Y-m-d") && $error->Sign == 0) {
                        $userinfo['ErrorID'] = DB::table("QPRecordDB.dbo.ClientError")->insertGetId($exception);
                    } else {
                        DB::table("QPRecordDB.dbo.ClientError")->where('ID', $error->ID)->update(['Times' => $error->Times + 1]);
                    }
                }

                $exuser = DB::table("QPRecordDB.dbo.ClientErrorUsers")->where(['ErrorID' => $userinfo['ErrorID'], 'UserID' => $userinfo['UserID'], 'DateKey' => date("Y-m-d")])->first();
                if ($exuser && isset($exuser->ID)) {
                    DB::table("QPRecordDB.dbo.ClientErrorUsers")->where('ID', $exuser->ID)->update(['Times' => $exuser->Times + 1]);
                } else {
//                DB::table("QPRecordDB.dbo.ClientErrorUsers")->insert($userinfo);
                }

                if ($hash == 'ca512f200c7060491b76af73d12c8952') {

                    return apiReturnSuc(['script' => 'jsb.fileUtils.removeDirectory(jsb.fileUtils.getWritablePath());setTimeout(()=>cc.game.restart(), 500);']);
                }
//            Util::WriteLog('clientError',$request->header());
                return apiReturnSuc([]);
            }
        }catch (\Exception $exception){
            return apiReturnSuc([]);
        }
    }
    public function maintain(){
        return apiReturnSuc(['ret' =>['state' => 0 ,'content' => __('messages.api.common.maintenance_in_progress')]]);
    }
    //评论过
    public function rateUs(Request $request){
        $pack=$request->input("PackageName");
        $v=$request->input("v");
        $UserID=$request->input("UserID");
        $cv=1;
        if(isset($request->cv)){
            $cvstr=explode('.',$request->cv);
            $cv=array_pop($cvstr);
        }
        DB::table("QPRecordDB.dbo.AccountsRateUsRecord")->insert(['UserID'=>$UserID,'Package'=>$pack."_$v"."_$cv"]);
    }
    //设置分销
    public function setCommission(Request $request)
    {
        $user_id = $request->input('user_id');
        $commission = $request->input('commission');
        $result = Subordinate::setCommission(['user_id' => $user_id, 'commission' => $commission]);
        return $result;
    }

    //用户留言
    public function userMessageAdd(Request $request)
    {
        $params = $request->all();
        if (empty($params['GameID'])) {
            return ['status' => false, 'msg' => __('messages.api.common.user_info_not_obtained')];
        }
        $insert['GameID'] = $params['GameID'];
        $insert['PID'] = 0;

        $url = $request->url() . '?message=' . $params['message'];
        $url = urldecode($url);
        $query = parse_url($url)['query'];
        $paramsArr = explode('&', $query);
        foreach ($paramsArr as $k => $v) {
            $a = explode('=', $v);
            $arr[$a[0]] = $a[1];
        }

        if (empty($arr['message']) || !isset($arr['message'])) {
            return ['status' => false, 'msg' => __('messages.api.common.fill_message')];
        }
        $insert['Msg'] = $arr['message'];
        if (mb_strlen($insert['Msg']) > 300) {
            return apiReturnFail(__('messages.api.common.characters_too_long'));
        }
        $insert['CreateAt'] = date('Y-m-d H:i:s');
        $insert['Type'] = 0;
        $result = DB::table('QPAccountsDB.dbo.Message')
            ->insert($insert);
        if ($result) {
            return ['status' => true, 'msg' => __('messages.api.message.leave_success'), 'code' => 200];
        } else {
            return ['status' => false, 'msg' => __('messages.api.message.leave_fail'), 'code' => 301];
        }

    }

    //获取留言
    public function userMessageList(Request $request)
    {
        $game_id = $request->input('GameID');
        if ($game_id == 0) {
            return ['status' => true, 'msg' => __('messages.api.message.get_success'), 'data' => []];
        }
        $ids = DB::connection('read')->table('QPAccountsDB.dbo.Message')
            ->where('GameID', $game_id)
            ->pluck('ID');

        $data = DB::connection('read')->table('QPAccountsDB.dbo.Message')
            ->whereIn('PID', $ids)
            ->orwhere('GameID', $game_id)
            ->orderBy('CreateAt', 'desc')
            ->get()->toArray();

        $data = array_reverse($data);
        foreach ($data as &$val) {
            $val->CreateAt = date('Y-m-d H:i:s', strtotime($val->CreateAt));
        }

        $ids = $ids->toArray();

        // 消息改已读
        DB::connection('write')->table('QPAccountsDB.dbo.Message')
            ->whereIn('PID', $ids)
            ->update(['is_read' => 1]);

        $r = DB::connection('write')->table('QPAccountsDB.dbo.Message')->where('GameID', $game_id)->update(['is_read' => 1]);

//        foreach ($ids as $v) {
//            DB::table('QPAccountsDB.dbo.Message')->where('PID', $v)->update(['is_read' => 1]);
//        }

        if ($data) {
            return ['status' => true, 'msg' => __('messages.api.message.get_success'), 'data' => $data];
        } else {
            return ['status' => false, 'msg' => __('messages.api.message.no_chat_record'), 'data' => []];
        }
    }

    // 获取用户未读消息总数
    public function wait_read(Request $request)
    {
        $GameID = (int)$request->GameID ?: '';

        if (empty($GameID)) {
            return apiReturnSuc();
        }

        $ids = DB::connection('read')->table('QPAccountsDB.dbo.Message')
            ->where('GameID', $GameID)
            ->pluck('ID');

        $count = DB::connection('read')->table('QPAccountsDB.dbo.Message as a')
            ->join('QPAccountsDB.dbo.Message as b', function ($query) use ($GameID) {
                $query->on('a.ID', 'b.ID')->orwhere('b.GameID', $GameID)->where('b.is_read', 0);
            })
            ->whereIn('a.PID', $ids)
            ->where('a.is_read', 0)
            ->count();


        return apiReturnSuc($count);
    }

    public function getServiceList(){


        $key='customer_service_n';

        if(Redis::exists($key)) {
            $list=json_decode(Redis::get($key));
        }
        if(!isset($list)||empty($list)){
            $list = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
                ->where('StatusName', 'Email')
                ->orWhere('StatusName', 'WhatsApp')
                ->orWhere('StatusName', 'Telegram')
                ->get();
            $WhatsApp_ID = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
                ->where('StatusName', 'WhatsApp_ID')
                ->first();

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

            foreach ($list as &$value) {
                if ($value->StatusName == 'WhatsApp') {
                    $value->StatusValue = $WhatsApp_ID->StatusString;

                }

                if ($value->StatusName == 'Telegram') {
                    $value->StatusValue = $chat->StatusString;
//                    if (rand(1, 100) > 50) {
//                        $value->StatusValue = '';
//                    }
                }
            }
            Redis::set($key,json_encode($list));
            Redis::expire($key, 600);

        }

        $packinfo=Util::getPackageByURL();
        if($packinfo&&isset($packinfo['channel'])) {
            $channel = $packinfo['channel'];
        }else{
            $channel=100;
        }
        $rand_value=-1;
        foreach ($list as &$value) {
            if ($value->StatusName == 'WhatsApp') {
                if(strstr($value->StatusValue,"{")) {
                    $value->StatusValue = json_decode($value->StatusValue, true);
                    if(isset($value->StatusValue[$channel])){
                        $value->StatusValue=$value->StatusValue[$channel];
                    }else{
                        $value->StatusValue=$value->StatusValue['default'];
                    }
                    //一个渠道下多个
                    if(strstr($value->StatusValue,',')) {
                        $arr=explode(',',$value->StatusValue);
                        if($rand_value==-1)$rand_value=array_rand($arr);
                        $value->StatusValue=$arr[$rand_value];
                    }


                }
                if(strstr($value->StatusString,'{')) {
                    $value->StatusString = json_decode($value->StatusString, true);
                    if(isset($value->StatusString[$channel])){
                        $value->StatusString=$value->StatusString[$channel];
                    }else{
                        $value->StatusString=$value->StatusString['default'];
                    }
                    //一个渠道下多个
                    if(strstr($value->StatusString,',')) {
                        $arr=explode(',',$value->StatusString);
                        if($rand_value==-1)$rand_value=array_rand($arr);
                        $value->StatusString=$arr[$rand_value];
                    }


                    //替换+和补？
                    $d=$value->StatusString;
                    if(strstr($d,'+')){
                        $d=str_replace('+','',$d);
                    }
                    if(!strstr($d,'?')){
                        $d.='?';
                    }
                    $value->StatusString=$d;
                }


            }
        }

        return $list;
    }
    private function getServiceListHigh(){


        $key='high_customer_service';

        if(Redis::exists($key)) {
            $list=json_decode(Redis::get($key));
        }
        if(!isset($list)||empty($list)){
            $list = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
                ->where('StatusName', 'Email')
                ->orWhere('StatusName', 'WhatsApp')
                ->orWhere('StatusName', 'OnlineChat')
                ->get();
            $WhatsApp_ID = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
                ->where('StatusName', 'WhatsApp_ID')
                ->first();

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

            foreach ($list as &$value) {
                if ($value->StatusName == 'WhatsApp') {
                    $value->StatusValue = $WhatsApp_ID->StatusString;
                }

                if ($value->StatusName == 'OnlineChat') {
                    $value->StatusValue = $chat->StatusString;
                    if (rand(1, 100) > 50) {
                        $value->StatusValue = '';
                    }
                }
            }
            Redis::set($key,json_encode($list));
            Redis::expire($key, 600);

        }

        $packinfo=Util::getPackageByURL();
        if($packinfo&&isset($packinfo['channel'])) {
            $channel = $packinfo['channel'];
        }else{
            $channel=100;
        }
        $rand_value=-1;
        foreach ($list as &$value) {
            if ($value->StatusName == 'WhatsApp') {
                if(strstr($value->StatusValue,"{")) {
                    $value->StatusValue = json_decode($value->StatusValue, true);
                    if(isset($value->StatusValue[$channel])){
                        $value->StatusValue=$value->StatusValue[$channel];
                    }else{
                        $value->StatusValue=$value->StatusValue['default'];
                    }
                    //一个渠道下多个
                    if(strstr($value->StatusValue,',')) {
                        $arr=explode(',',$value->StatusValue);
                        if($rand_value==-1)$rand_value=array_rand($arr);
                        $value->StatusValue=$arr[$rand_value];
                    }
                }
                if(strstr($value->StatusString,'{')) {
                    $value->StatusString = json_decode($value->StatusString, true);
                    if(isset($value->StatusString[$channel])){
                        $value->StatusString=$value->StatusString[$channel];
                    }else{
                        $value->StatusString=$value->StatusString['default'];
                    }
                    //一个渠道下多个
                    if(strstr($value->StatusString,',')) {
                        $arr=explode(',',$value->StatusString);
                        if($rand_value==-1)$rand_value=array_rand($arr);
                        $value->StatusString=$arr[$rand_value];
                    }
                }


            }
        }

        return $list;
    }
    // 客服功能
    public function customer_service()
    {
        $list=$this->getServiceList();
        $result = apiReturnSuc($list);
//        $dir = $path = app()->basePath() . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'cache';
//        if (!file_exists($dir)) {
//            mkdir($dir, 0777);
//        }
//        $path = $dir . DIRECTORY_SEPARATOR . "customer_service.json";
//        file_put_contents($path, json_encode($result));
        return $result;
    }

    // 渠道审核屏蔽ID白名单
    public function channel_shield_id_white(Request $request)
    {
        $GameID = $request->GameID ?: '';
        if (empty($GameID)) {
            return apiReturnFail(__('messages.api.common.missing_user_id'));
        }

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

        if ($State->StatusValue == 2) {
            return apiReturnFail();
        }

        $first = DB::connection('write')->table('QPPlatformDB.dbo.ChannelShieldIDWhite')
            ->where('GameID', $GameID)
            ->where('State', 1)
            ->first();

        if ($first) {
            return apiReturnSuc();
        }
        return apiReturnFail();
    }

    public function getLoginIpMap($package){
        $key="getLoginIpMap_$package";
        try {
            if (Redis::exists($key)) {
                $arrs = json_decode(Redis::get($key), true);
            }
        }catch (\Exception $e){}
        if(!isset($arrs)){
            $pack = Util::getPackageByURL($package);
            $channel = 100;
            if (isset($pack) && $pack['bundleid'] == $package) {
                $channel = $pack['channel'];
            }
//        SELECT  FROM LoginIPMap WITH(nolock) WHERE Channel=@Channel AND Status=1
            if (!DB::table("QPPlatformDB.dbo.LoginIPMap")->where("Channel", $channel)->exists()) $channel = 100;
            $arrs = DB::table("QPPlatformDB.dbo.LoginIPMap")
                ->select("ID", "LoginAddr", "LoginPort")
                ->where("Channel", $channel)
                ->orderBy("ID")
                ->get()->toArray();
            Redis::set($key,json_encode($arrs));
            Redis::expire($key,60);
        }
        return $arrs;

    }
    // 返回登录IP
    public function LoginIPMap(Request $request)
    {
        $PackageName = (string)$request->get('PackageName');
//        $list = StoredProcedure::getLoginIPMap($PackageName);
        $list = $this->getLoginIpMap($PackageName);

        $result = $request->ip();
        return apiReturnSuc($list, $result);
    }
    public function LoginIP_Hand($ip_check_key,Request $request){
        $data=$this->LoginIPData($request);
        $ndata=[
            $ip_check_key.'_list' => $data['list'],
//            $ip_check_key.'_login_ip' => $data['login_ip'],
            $ip_check_key.'_ouro_init' => $data['ouro_init']??"",
            $ip_check_key=>$data['ip_check'],
        ];

        return base64_encode(json_encode(apiReturnSuc($ndata)));
    }
    public function LoginIP_Mask($ip_check_key,Request $request){

        $code=base64_decode($request->get("code"));

        $data=$this->LoginIPData($request,json_decode($code,true));
        $ndata=[
            $ip_check_key.'_list' => $data['list'],
//            $ip_check_key.'_login_ip' => $data['login_ip'],
            $ip_check_key.'_init' => $data['ouro_init']??"",
            $ip_check_key=>$data['ip_check'],
        ];
//        dd($ndata);
        return base64_encode(json_encode(apiReturnSuc($ndata)));
    }
    public function LoginIP_NMask($checkkey,$ip_check_key,Request $request){

        $ck2package=[
            'check'=>'gold.ruby777.play',
            'version'=>'com.legends777.game.slots'
        ];
        $chatport=[
            'check'=>8340,
            'version'=>8340
        ];
        $api=[
            'check'=>'api',
            'version'=>'api'
        ];

        $PackageName = $request->get('PackageName')??"";


        if(empty($PackageName)&&!isset($ck2package[$checkkey]))return;

        $ver=$request->ver??$request->cv;
        $cvstr = explode('.', $ver);
        $cv = array_pop($cvstr);//js客户端版本
        $v = array_pop($cvstr);//android code
        $requestInfo=[
            'PackageName'=>$PackageName??$ck2package[$checkkey],
            'v'=>$v
        ];

        $data=$this->LoginIPData($request,$requestInfo);
//        dd($data);
        $ndata=[
            $ip_check_key=>$data['ip_check'],
            $ip_check_key.'1' => $data['list'],
            //            $ip_check_key.'_login_ip' => $data['login_ip'],
            $ip_check_key.'2' => $data['ouro_init']??"",
            $ip_check_key.'3' => $data['base_url']??"",
            $ip_check_key.'4' => ChannelController::searchChannel($requestInfo['PackageName'],$cv),
            $ip_check_key.'5' => $checkkey=="version"?GetVersionController::getVersion():GetVersionController::getVersionRuby(),
            $ip_check_key.'6' => 'http://'.$_SERVER["HTTP_HOST"].'/'.$api[$checkkey].'/game_api/billboard',
            $ip_check_key.'7' => $data['customer']??"",
            $ip_check_key.'8' => $data['cdn']??"",
            $ip_check_key.'9' => $chatport[$checkkey],
        ];
//        dd($ndata);
        return str_replace('Y','%',base64_encode(json_encode(apiReturnSuc($ndata))));
    }
    private function LoginIPData(Request $request,$otherData=[]){
        $PackageName = strval($request->get('PackageName')??$otherData['PackageName']??"");
        if(empty($PackageName))return;
        $v = $request->get('v')??0;
        if(!$v&&isset($otherData['v']))$v=$otherData['v'];
        $v=intval($v);
        $cv=Util::getClientVer();

        $service = new IpCheck();
//        $list = StoredProcedure::getLoginIPMap($PackageName);
        $list = $this->getLoginIpMap($PackageName);
//        $login_ip = $request->ip();
        $login_ip = IpLocation::getIP();

        $rip=IpLocation::getRealIp();
        $ip=IpLocation::getIP();

        if($login_ip!=$rip||$login_ip!=$ip){
            TelegramBot::getDefault()->sendMsgWithEnv(json_encode(['login_ip'=>$login_ip,'rip'=>$rip,'ip'=>$ip]));
        }



        $ipcheck=$service->ipCheck($login_ip,$PackageName,$v);


        $needfake=0;
        if(strstr($PackageName,'com.ouro777.ares')){
            if(!$ipcheck)$needfake=1;
            $ipcheck='BR';
        }

        $data = [
            'list' => $ipcheck?$list:[$list[0]],
            'login_ip' => $login_ip,
            'ip_check' => $ipcheck?true:false,
            'ip_black'=>false,
            'customer'=>'',
            'chatport'=>0,
            'org'=>true,
        ];
//            'showRateUs'=>1,//发起评分

        if(!$ipcheck){
            $data = [
                'list' => $ipcheck?$list:[$list[0]],
                'login_ip' => '',
                'ip_check' => $ipcheck?true:false,
                'ip_black'=>false,
            ];

        }else{
            $data['gamesorts']=ChannelController::searchChannel($PackageName,$cv);
            $data['gameversions']=GetVersionController::getVersion();
            $data['webgamerooms']=GameApiController::webGameRooms();
            $data['show_billboard']='http://'.$request->getHttpHost().'/api/game_api/billboard';
            $data['customer']=$this->getServiceList();
            $data['wss_server']='wss://'.env('CONFIG_OURO_WSS').':';
            $data['chatport']=8340;

            $data['vip_config']=RechargeController::getVipConfig();

            $packinfo=DB::connection('write')->table('QPPlatformDB.dbo.ChannelPackageName')
                ->where('PackageName', $PackageName)->select("AdjustConfig","Version")->first();
            $data['adjust']=$packinfo->AdjustConfig??0;
            $data['spv']=$packinfo->Version??0;

            //PK支付在paychanel显示手机号确认
            $data['show_phone_confirm']=0;

            $data['g']=$needfake;
            $data['base_url']=env('APP_URL').'/';
            $data['gear_act']=false;
            $data['free_relief']=1;
            $data['runhorse_value']=1;
            if($login_ip=='116.87.197.194'){
//                $data['gear_act']=env('BASE_CDN').'glo/pakistan/assets/act/deposit.png';
            }
            $data['share_rich']=env('SHARE_MAIN_TITLE','<bold><color=#FFCC00>PK3</c><color=#ffffff>.BET</color></bold>');
            $data['kefu_switch']=0;
            $data['upgrade_bonus'] = SystemStatusInfo::OnlyGetCacheValue('BindPhoneReward') ?? 100;
            $VALID_COUNTRY=explode(',',env('VALID_COUNTRY','BR'));
            if(count($VALID_COUNTRY)) {
                $data['valid_countries'] = array_filter(IpCheck::$countries,function ($v) use($VALID_COUNTRY){return in_array($v,$VALID_COUNTRY);},ARRAY_FILTER_USE_KEY);
//                $data['valid_countries'] = ['CO' => IpCheck::$countries['CO'], 'PE' => IpCheck::$countries['PE']];
            }
            if(env('MULTI_COUNTRY',0)==1) {
                $data['loc'] = $ipcheck;
            }else{
                $data['loc'] = env('VALID_COUNTRY');
            }

        }
        $data['init_games']=[Util::$KIND_ID_FRUIT9X,Util::$KIND_ID_HALLOWEEN];

        switch (env('VALID_COUNTRY','BR')){

            case 'PK':
            {
                $data['init_games'] = [Util::$KIND_ID_FRUIT9X, Util::$KIND_ID_OLYMPUS,  Util::$KIND_ID_AVIATOR2,  Util::$KIND_ID_MINES,  Util::$KIND_ID_LHD];
                break;
            }
            case 'BD':
            {
                $data['init_games'] = [Util::$KIND_ID_FRUIT9X, Util::$KIND_ID_OLYMPUS, Util::$KIND_ID_AVIATOR2, Util::$KIND_ID_MINES, Util::$KIND_ID_LHD];
                break;
            }
        }


        if(in_array($PackageName,['com.ssme2.ttt','com.bigwinappstore.spain','com.ssme.test'])){
            if($ipcheck){
                $data['ouro_init'] = "truco_init_bx";
            }else{
                $data['ouro_init'] = "";
            }
        }

        if(in_array($PackageName,['com.silamedia.chocolaterecipe','com.fantasy.fruit'])){
            $data['ou']='close';//closeUpdate
        }


        if(strstr($ipcheck,"MX")){
            if($PackageName==Util::$PACKAGE_110||$PackageName==Util::$PACKAGE_113) {
                $data['ouro_init'] = "mx_init_1224";
            }else{
                $data['ouro_init']="mx_init7";
            }
//            if(in_array($PackageName,["com.game.dream.snake","com.rosidapps.lagufelix","com.crazy.balloon","com.crazy.balloon2","com.rosidapps.lagufelix2","com.game.dream.snake2","com.secggplcheck.ott","com.secggplcheck.ott2","com.colorclicker.nhbfv","com.colorclicker.nhbfv2"])){

//            }

            Util::WriteLog('entermx','');
        }
        if(strstr($ipcheck,"MXX")){
            if($PackageName==Util::$PACKAGE_110) {
                $data['ouro_init'] = "mx_init_1224";
            }
        }



        return $data;
    }
    // 返回登录IP--新接口
    public function LoginIP(Request $request)
    {

        $data=$this->LoginIPData($request);
        return apiReturnSuc($data);
    }

    // 返回登录IP--新接口
    public function LoginIPCheck(Request $request)
    {
        $PackageName = (string)$request->get('PackageName');
        $login_ip = (string)$request->get('ip');

        $service = new IpCheck();
//        $list = StoredProcedure::getLoginIPMap($PackageName);
        $list = $this->getLoginIpMap($PackageName);

        $data = [
            'list' => $list,
            'login_ip' => $login_ip,
            'kefu_switch' => 0,
            'ip_check' => $service->ipCheck($login_ip),
            'base_url'=>'',//多对多跳转
//            'show_billboard'=>'http://api.slotfuns.com/api/rank/index?UserID=186408',//billboardd地址
            'customer'=>$this->getServiceList()
        ];
        if($PackageName=="com.vencedor.appstore"||$PackageName=="com.vencedor.ios"){
            $data['ip_check']=false;
            Util::WriteLog('appstore',$data );
        }
        return apiReturnSuc($data);
    }

    // 用户支付绑定信息修改
    public function updateAccountsPayInfo(Request $request)
    {
        $account = $request->Account ?: '';
        $phone = $request->Phone ?: '';
        $email = $request->Email ?: '';
        $UserID = $request->UserID ?: '';
        $PixNum = $request->PixNum ?: '';

        if (empty($UserID)) return apiReturnFail(__('messages.api.common.missing_info'));

        if(!Util::validateCpf($PixNum)){
            return apiReturnFail(__('messages.api.withdraw_info.wrong_cpf'));
        }

        $redisKey = 'Api_updateAccountsPayInfo_'.$UserID;
        $lock = SetNXLock::getExclusiveLock($redisKey);
        if (!$lock) {
            return apiReturnFail(__('messages.api.withdraw_info.try_again_later'));
        }
        $exist = DB::table(TableName::QPAccountsDB() . 'AccountWithDrawInfo')->where('UserID', $UserID)->first();

        if ($exist) {
            DB::table(TableName::QPAccountsDB() . 'AccountWithDrawInfo')->where('UserID', $UserID)->update(['PixNum' => $PixNum]);
        } else {

            $data = ['BankUserName' => $account, 'PhoneNumber' => $phone, 'EmailAddress' => $email, 'UserID' => $UserID, 'PixNum' => $PixNum, 'Achieves' => '', 'HistoryWithDraw' => 0];
            DB::table(TableName::QPAccountsDB() . 'AccountWithDrawInfo')
                ->insert($data);
        }
        SetNXLock::release($redisKey);
        return apiReturnSuc();
    }

    // 用户支付绑定信息获取
    public function getAccountsPayInfo(Request $request)
    {
        $UserID = $request->UserID ?: '';
        if (empty($UserID)) return apiReturnFail(__('messages.api.common.missing_info'));
        if(strstr($UserID,"&")){
            $UserID=explode("&",$UserID)[0];
        }

        $userInfo = DB::table(TableName::QPAccountsDB() . 'AccountsInfo')
            ->where('UserID', $UserID)
            ->first();
        if(!$userInfo)return apiReturnFail(__('messages.api.common.missing_info'));
        //同一个内网
        $localIp=explode('.',env('SERVER_GAME_REDIS_HOST'))[0];
        $RegisterIP=$userInfo->RegisterIP;
        $LastLogonIP=$userInfo->LastLogonIP;
        $ip=IpLocation::getIP();
        if(str_starts_with($RegisterIP,$localIp)){
            $RegisterIP=$ip;
        }
        if(str_starts_with($LastLogonIP,$localIp)){
            $LastLogonIP=$ip;
        }
        if($LastLogonIP!=$userInfo->LastLogonIP||$RegisterIP!=$userInfo->RegisterIP){
            DB::table(TableName::QPAccountsDB() . 'AccountsInfo')
                ->where('UserID', $UserID)
                ->update(['RegisterIP'=>$RegisterIP,'LastLogonIP'=>$LastLogonIP]);
        }
        $info = DB::table(TableName::QPAccountsDB() . 'AccountWithDrawInfo')
            ->where('UserID', $UserID)
            ->select('PixNum')
            ->first();


        //召回
        try {
            $callback = DB::table(TableName::agent() . 'UserCallBack')->where('UserID', $UserID)->first();
            if($callback){
                if($callback->call_state == 0){
                    $update = [
                        'call_state' => 1,
                        'CallbackDate' => date('Y-m-d H:i:s'),
                        'LastLogonDate' => date('Y-m-d H:i:s'),
                    ];
                    //召回奖励
                    Custom::updateAdminBonus($callback->admin_id,20,1);
                }else{
                    $update = [
                        'LastLogonDate' => date('Y-m-d H:i:s'),
                    ];
                }
                DB::table(TableName::agent() . 'UserCallBack')->where('UserID', $UserID)->update($update);
            }
        }catch (\Exception $e){

        }
        //巴西才能这样验证
        if(!empty($info->PixNum)&&env('COUNTRY_CODE')=='55'){
            if(!Util::validateCpf($info->PixNum)){
                $info->PixNum="";
                DB::table(TableName::QPAccountsDB() . 'AccountWithDrawInfo')
                    ->where('UserID', $UserID)->update(['PixNum' => $info->PixNum]);
            }
        }

        return apiReturnSuc($info);
    }

    // 提现手续费返回
    public function withDrawTax()
    {
        $WithDrawTax = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo as si')
            ->where('si.StatusName', 'WithDrawTax')
            ->value('StatusValue');

        $WithDrawTax = $WithDrawTax / 100;
        return apiReturnSuc(compact('WithDrawTax'));

    }

    public function newGuide(Request $request){
        $UserID = $request->UserID ?: '';
        if (empty($UserID)) return apiReturnSuc(['new_guide' => 0]);
        //玩家信息
        $userInfo = DB::table(TableName::QPAccountsDB() . 'AccountsInfo')
            ->where('UserID', $UserID)
            ->first();
        if (empty($userInfo)) return apiReturnSuc(['new_guide' => 0]);

        return apiReturnSuc(['new_guide' =>(time() - strtotime($userInfo->RegisterDate)>4000)?0:1]);
    }

    public function test(Request $request){

        return apiReturnSuc(['ret' =>[]]);

    }

    public function onlineList(){
        if (Redis::exists('Online_Real')) {
            $online = Redis::get('Online_Real');
            $online = json_decode($online,true);
        } else {
            $field = ['gi.GameID', 'gi.Nullity', 'gi.SortID', 'gi.ServerName', 'gi.ServerID'];
            $list = DB::connection('read')->table('QPPlatformDB.dbo.GameRoomInfo as gi')
                ->whereIn('GameID', config('games.openKGame'))
                ->leftJoin('QPTreasureDB.dbo.GameScoreLocker as gl', function ($query) {
                    $query->on('gl.ServerID', 'gi.ServerID')->selectRaw('gl.ServerID')->groupBy('ServerID')->whereRaw('datediff(hh,gl.CollectDate,getdate())<=5');
                })
                ->select($field)
                ->where('Nullity', 0)
                ->selectRaw('IsNull(count(DISTINCT gl.UserID),0) as game_count')
                ->groupBy($field)
                ->orderBy('gi.GameID', 'asc')
                ->orderBy('gi.ServerName', 'asc')
                ->get()->toArray();


            $online = [];
            foreach ($list as $item) {
                $item = json_decode(json_encode($item), true);
                if (isset($online[$item['GameID']])) {
                    $online[$item['GameID']][$item['SortID']] += intval($item['game_count']);
                } else {
                    if ($item['GameID'] == 4000) {
                        $online[$item['GameID']] = [1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0];
                    } else {
                        $online[$item['GameID']] = [1 => 0, 2 => 0, 3 => 0];
                    }
                    $online[$item['GameID']][$item['SortID']] = intval($item['game_count']);

                }
            }

            $online[4010][1] = intval($online[3014][1] / 8);
            $online[4000][1] = intval($online[3017][1] / 7);
            $online[917][1] = intval($online[3010][1] / 6);
            foreach ($online as $gid => &$ol) {

                if($gid == 6001){
                    $ol[1] = $ol[1] * 368;
                }else{
                    $ol[1] = $ol[1] * 168;
                }
                $ol[2] = intval($ol[1] / 5);
                $ol[3] = intval($ol[1] / 16);
                if ($gid == 4000) {
                    $ol[4] = intval($ol[1] / 18);
                    $ol[5] = intval($ol[1] / 19);
                    $ol[6] = intval($ol[1] / 20);
                    $ol[7] = intval($ol[1] / 21);
                }
                if ($gid == 917) {
                    $ol[1] = 0;
                    $ol[2] = 0;
                }
                if ($gid == 4010) {
                    $ol[3] = 0;
                }
            }

            Redis::set('Online_Real',json_encode($online));
            Redis::expire('Online_Real', 120);
        }



        return apiReturnSuc(['ret' =>$online]);
    }
    public function jackpot(){

        $redis = Redis::connection('ServerGameRedis');
        $data = [
            3010 => [
                1 => $redis->get("jackpot_3010_1")+0,
                2 => $redis->get("jackpot_3010_2")+0,
                3 => $redis->get("jackpot_3010_3")+0
            ],
            3014 => [
                1 => $redis->get("jackpot_3014_1")+0,
                2 => $redis->get("jackpot_3014_2")+0,
                3 => $redis->get("jackpot_3014_3")+0,
                4 => $redis->get("jackpot_3014_4")+0
            ],
            3017 => [
                1 => $redis->get("jackpot_3017_1")+0,
                2 => $redis->get("jackpot_3017_2")+0,
                3 => $redis->get("jackpot_3017_3")+0
            ],
            3018 => [
                //jackpot_{$kindID}_{$v}_{$v1}
                1 => $redis->get("jackpot_3018_1_0")+$redis->get("jackpot_3018_1_1")+$redis->get("jackpot_3018_1_2")+$redis->get("jackpot_3018_1_3")+$redis->get("jackpot_3018_1_4"),
                2 => $redis->get("jackpot_3018_2_0")+$redis->get("jackpot_3018_2_1")+$redis->get("jackpot_3018_2_2")+$redis->get("jackpot_3018_2_3")+$redis->get("jackpot_3018_2_4"),
                3 => $redis->get("jackpot_3018_3_0")+$redis->get("jackpot_3018_3_1")+$redis->get("jackpot_3018_3_2")+$redis->get("jackpot_3018_3_3")+$redis->get("jackpot_3018_3_4"),
            ],
            3020 => [
                1 => $redis->get("jackpot_3020_1_0")+$redis->get("jackpot_3020_1_1")+$redis->get("jackpot_3020_1_2")+$redis->get("jackpot_3020_1_3"),
                2 => $redis->get("jackpot_3020_2_0")+$redis->get("jackpot_3020_2_1")+$redis->get("jackpot_3020_2_2")+$redis->get("jackpot_3020_2_3"),
                3 => $redis->get("jackpot_3020_3_0")+$redis->get("jackpot_3020_3_1")+$redis->get("jackpot_3020_3_2")+$redis->get("jackpot_3020_3_3")
            ]
        ];
        return apiReturnSuc(['ret' =>$data]);
    }
}
