<?php

namespace App\Http\Controllers\Api;

use App\Facade\TableName;
use App\Game\Services\RouteService;
use App\Game\WebChannelConfig;
use App\Http\Controllers\Controller;
use App\IpLocation;
use App\Models\AgentClickLog;
use App\Models\WithdrawalChannelPositionConfig;
use App\Util;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;


class AutoApkController extends Controller
{
    protected $defaultChannel=100;
    public function index()
    {
        $this->defaultChannel=env('REGION_24680_DEFAULT_CHANNEL',100);
    }
    public function h5jump(Request $request){
        $url="https://cdn.24680.com/client/orgbr/index.html";
        Util::WriteLog("h5","");
        $redirect_url=$url.'?'.http_build_query($request->all());
        header("Location: $redirect_url", true, 302);
        exit();
//        return redirect($url.'?'.http_build_query($request->all()));
    }
    public function channelConfig(Request $request)
    {
        $config = WebChannelConfig::getByChannel($request->input('c','100'));
        return response()->json(['apkurl'=>$config->LightApk]);
    }
    public function jumpApkByConfig(Request $request)
    {
        $config = WebChannelConfig::getByChannel($request->input('c','100'));
        return redirect($config->LightApk);
    }

    public function health(Request $request){
        // 从Redis读取系统健康状态配置
        $healthConfig = Redis::get('system:health');

        if (!$healthConfig) {
            // 如果Redis中没有配置，则返回默认值
            return ['status' => 1, 'pay' => 1, 'cashout' => 1, 'notice' => '','other'=>json_decode($healthConfig, true)];
        }

        // 返回Redis中的配置
        return json_decode($healthConfig, true);
    }
    public function inside(Request $request){



        // 读取文件内容
        $file_path = public_path('inside.htm');
        $content = file_get_contents($file_path);

        // 替换 URL
        $old_url = 'https://saapi.24680.org';
        $new_url = env('APP_URL');
        $updated_content = str_replace($old_url, $new_url, $content);

        $updated_content = str_replace('BRL', env('CONFIG_24680_CURRENCY','BRL'), $updated_content);
        // 替换 URL
        $old_url = 'domain=brapi.24680.org';
        $new_url = 'domain='.$_SERVER['HTTP_HOST'];
        $updated_content = str_replace($old_url, $new_url, $updated_content);
        $old_url = 'domain=.24680.org';
        $new_url = 'domain='.$_SERVER['HTTP_HOST'];
        $updated_content = str_replace($old_url, $new_url, $updated_content);


        $UserID=$request->uid??0;
        if($UserID) {
            AgentClickController::checkClick($UserID);
        }

        return $updated_content; // 返回结果

    }
    public function findUrlSign(Request $request){
        $packageName = $request->input('packageName')??$request->input('PackageName');
        $packageConfig=DB::table('QPPlatformDB.dbo.ChannelPackageName')->where('PackageName',$packageName)->first()->toArray();
        if(!$packageConfig){
            return apiReturnFail();
        }
        return apiReturnSuc($packageConfig);
    }

    /////模板包资源 //包体 pack/input/apks //签名 pack/input/keystore //替换目录 pack/input/res/ //输出目录 临时制作目录 pack/output //工具 解包 签名 pack/tools
    //
    ////最终包输出目录 app/public/apks/
    //
    //接口 get post api/getApk //包名 packageName //app名字 appName //icon url 名字随意 iconUrl //圆icon url 名字随意 iconRoundUrl //指定制作配置 默认ouro777 不更改可不传 pkey
    //
    public function createApk(Request $request)
    {
        $packageName = $request->input('packageName');
        //投放标识
        $channelName = $request->input('channelName');
        $appName = $request->input('appName');
        $iconUrl = $request->input('iconUrl');
        $iconRoundUrl = $request->input('iconRoundUrl');
        $adminSign=$request->input('adminSign',"dk");

        $pkey=env('DEFAULT_APK_PKEY','ouro777');
        $configToPkey=['bxorg'=>'ouro777','mxorg'=>'ouro777_mx','bx_skin2_nftd'=>'BR_SKIN1_NewFirstPay','bx_org_nftd'=>'BR_ORG_NewFirstPay','colperu_org'=>'oro777_sa','bx24680'=>'red24680','pakistan_org'=>'pakistan'];
        if($request->has('config')){
            $config = preg_replace('/[^a-zA-Z_]+$/', '', trim($request->input('config')));
            $pkey=$configToPkey[$config]??$pkey;
        }

        $params=compact('packageName','appName','iconUrl','iconRoundUrl','pkey');
        $api='getApk';
        if($request->input('rebuild',0)==1){
            $api='rebuildApk';
        }
//        dd('http://15.228.201.93/api/'.$api.'?' . http_build_query($params));
        try {
            $url='http://15.228.201.93/api/'.$api.'?' . http_build_query($params);
            $client = new Client(['timeout'=>60]);

            $response = $client->get($url, [
                'timeout'      => 60
            ]);
            $result = $response->getBody();

        }catch (\Exception $e){
            Util::WriteLog('autoapk',$e->getMessage().$e->getTraceAsString());
            return apiReturnFail(__('messages.api.auto_apk.please_wait'));
        }
        $result=json_decode($result,true);
        if($result['code']!=200){
            $result['makeurl']='http://15.228.201.93/api/'.$api.'?' . http_build_query($params);
            return $result;
        }
        Util::WriteLog('autoapk',$result);
        //制作成功，建立数据
        $packageUrl=$result['data']['packageUrl'];
        $packageUrl=str_replace('http://18.228.154.186/','https://d388b4gb9i0dwg.cloudfront.net/',$packageUrl);

        $packageConfig=$this->autoCreateChannel($packageName,$channelName,$adminSign);

        $signConfigs=[
            'xidu'=>['david_view','david','xidu','liang','newapk','desheng','William'],
        ];

        //修改后台权限
        $Channel=$packageConfig['Channel'];
        DB::connection('mysql')->table('dcat-admin.admin_users')->whereIn('username',$signConfigs[$adminSign])->orderBy('username')->each(function($item) use ($Channel) {
            $item=(array)$item;
            $channels=json_decode($item['channel'],true);
            if(!in_array($Channel,$channels))$channels[]=$Channel;
            DB::connection('mysql')->table('dcat-admin.admin_users')->where('username',$item['username'])->update(['channel'=>json_encode($channels)]);
        });
        $urlSign=$packageConfig['AppKey'];
        $data=['packageUrl'=>$packageUrl,'packageName'=>$packageName,'channel'=>$packageConfig['Channel'],'urlSign'=>$urlSign];
        return apiReturnSuc($data);
    }

    public function modifyRights($packageConfig,$adminSign='dk')
    {
        $xidu=['xidu','kele','liang','laoma888','William'];
        $signConfigs=[
            'dk'=>array_merge(['david_view','david'],$xidu),
            'xidu'=>$xidu,
            'aresbigs'=>array_merge(['aresbigs'],$xidu),
            //            'xidu'=>['xidu','kele','liang','newapk_ours','desheng'],
        ];

        //修改后台权限
        $Channel=$packageConfig['Channel'];
        DB::connection('mysql')->table('dcat-admin.admin_users')->whereIn('username',$signConfigs[$adminSign])->orderBy('username')->each(function($item) use ($Channel) {
            $item=(array)$item;
            $channels=json_decode($item['channel'],true);
            if(!in_array($Channel,$channels))$channels[]=$Channel;
            DB::connection('mysql')->table('dcat-admin.admin_users')->where('username',$item['username'])->update(['channel'=>json_encode($channels)]);
        });
    }

    public function autoCreateChannel($packageName, $channelName,$adminSign='dk')
    {

        $packageConfig=DB::table('QPPlatformDB.dbo.ChannelPackageName')->where('PackageName',$packageName)->first();
        $UnionSign=0;
        if($adminSign=='dk'){
            //联运通道
            $UnionSign=1;
            $channelName='USA_'.$channelName;
        }else{
            $channelName='NEW_'.$channelName;
        }
        if(!$packageConfig){
            $sample=DB::connection('write')->table('QPPlatformDB.dbo.ChannelPackageName')->where('Channel',$this->defaultChannel)->orderBy('ID')->first();
            $post=(array)$sample;
            unset($post['ID']);

            $post['Remarks'] = $post['AliasName']=$channelName;
            $post['UnionSign']=$UnionSign;
            $post['PackageName'] = $packageName;
            $post['AppKey']= Util::generateRandomString();
            $post['Sort'] = $this->defaultChannel;


            while(DB::connection('write')->table('QPPlatformDB.dbo.ChannelPackageName')->where('AppKey', $post['AppKey'])->exists()) {
                $post['AppKey'] = Util::generateRandomString();
            }
            $maxChannel=DB::connection('write')->table('QPPlatformDB.dbo.ChannelPackageName')->max('Channel');

            $post['Channel']=$Channel = $maxChannel+1;
            DB::connection('write')->table('QPPlatformDB.dbo.ChannelPackageName')
                ->insert($post);
            if($Channel){
                $createConfig = function () use($Channel) {
                    $config = new WithdrawalChannelPositionConfig();
                    $config->channel = $Channel;
                    return $config;
                };

                $config = WithdrawalChannelPositionConfig::query()->where('channel', $Channel)->first() ?: $createConfig();
                $config->save();
            }

        }else{
            $packageConfig=(array)$packageConfig;

            if($packageConfig['Remarks']!=$channelName||$packageConfig['AliasName']!=$channelName){
                DB::table('QPPlatformDB.dbo.ChannelPackageName')->where('PackageName',$packageName)->update(['Remarks'=>$channelName,'AliasName'=>$channelName]);
                WebChannelConfig::where('Channel', $packageConfig['Channel'])->update(['Remarks' => $channelName,'PackageName'=>$packageName]);
            }
            $Channel=$packageConfig['Channel'];
            $post=$packageConfig;
        }




        if(WebChannelConfig::where('Channel', $Channel)->exists()) {
            WebChannelConfig::where('Channel', $Channel)->update(['Remarks' => $channelName,'PackageName'=>$packageName]);
        }else {
            $templateConfig = WebChannelConfig::getByChannel($this->defaultChannel);
            if($templateConfig) {
                $config = $templateConfig->toArray();
                $config['Remarks'] = $channelName;
                $config['Channel'] = $Channel;
                $config['PackageName'] = $packageName;
                unset($config['ID']);
                WebChannelConfig::insert($config);
            }
        }

        $dcatChannel=DB::connection('mysql')->table('dcat-admin.channel')->where('channel',$Channel);
        if($dcatChannel->exists()){
            $dcatChannel->update(['channel_name'=>$channelName]);
        }else{
            DB::connection('mysql')->table('dcat-admin.channel')->insert(['channel'=>$Channel,'channel_name'=>$channelName,'package_name'=>'','remark'=>'']);
        }

        $dcatChannel=DB::connection('mysql')->table('dcat-admin.channel_ownership')->where('channel',$Channel);
        if($dcatChannel->exists()){
            $dcatChannel->update(['name'=>$channelName]);
        }else{
            DB::connection('mysql')->table('dcat-admin.channel_ownership')->insert(['channel'=>$Channel,'name'=>$channelName]);
        }


        return $post;
    }
}
