<?php

namespace App\Services;

use App\Facade\TableName;
use App\Http\helper\HttpCurl;
use App\Http\helper\NumConfig;
use App\IpLocation;
use App\Models\AccountsSource;
use App\Util;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class ApkService
{

    //'ip','agent','cookie','type','url_sign','time'
    public static function updateCookie($UserID, $arr){
        DB::table(TableName::QPAccountsDB() . 'AccountCookie')->updateOrInsert(['UserID'=>$UserID],$arr);
        $key = "AccountCookie_$UserID";
        Redis::set($key, json_encode($arr));
        Redis::expire($key,36000);
    }
    //'ip','agent','cookie','type','url_sign','time'
    public static function saveCookie($UserID, $data,$FPID='')
    {
        $agent = $_SERVER['HTTP_USER_AGENT'];
        $key = "AccountCookie_$UserID";
        if(empty($UserID)&&!empty($FPID))$key="AccountCookie_$FPID";
        if (Redis::exists($key)) {
            return;
        }

        if (!DB::table(TableName::QPAccountsDB() . "AccountCookie")->where('UserID', $UserID)->exists()) {

//            if(DB::table(TableName::QPAccountsDB() . "AccountCookie")->where('Params', $data['params'])->exists()){
//                $data['params']='';
                //重复注册，下蛊吧
//                self::ControlOldUser($UserID,$data);
//            }

            $arr = [
                'UserID'    => $UserID,
                'FPID'      => $FPID,
                'Cookie'    => $data['cookie'],
                'Params'    => $data['params'],
                'UrlSign'   => $data['url_sign'],
                'Platform'  => $data['type'],
                'GameUA'    => $agent,
                'ClickUA'   => $data['agent'],
                'Origin'   => $data['origin']??"",
                'Locale'   => $data['locale']??$_SERVER['HTTP_ACCEPT_LANGUAGE'],
                'ClickTime' => date('Y-m-d H:i:s', $data['time']),
                'UniqueAction'   => 2,
                'IP'=>IpLocation::getIP(),
            ];
            DB::table(TableName::QPAccountsDB() . 'AccountCookie')->insert($arr);
            Redis::set($key, json_encode($arr));
            Redis::expire($key,36000);

            if(strstr($arr['Params'],'gclid')||strstr($arr['Params'],'fbclid')) {
                (new AccountsSource())->notExistsInsert($UserID, "APK_AD(" . $arr['Platform'] . ")");
            }
            //kwai手打点


            if($arr['Platform']=='kw') {
                $cookie = $arr['Cookie'];
                ApkService::sendToKwai(json_decode($cookie, true), ApkService::KWAI_EVENT['EVENT_COMPLETE_REGISTRATION']);
            }
            if($arr['Platform']=='gg') {
                $cookie = $arr['Params'];
//                UploadOfflineConversion::reg($UserID,json_decode($cookie, true));
            }
        }
    }

    public static function loadCookie($UserID)
    {
        $key = "AccountCookie_$UserID";
        if (Redis::exists($key)) {
            return json_decode(Redis::get($key), true);
        }
        if (DB::table(TableName::QPAccountsDB() . "AccountCookie")->where('UserID', $UserID)->exists()) {
            $ac = DB::table(TableName::QPAccountsDB() . "AccountCookie")->where('UserID', $UserID)->first();

            $ac = (array)$ac;
            Redis::set($key, json_encode($ac));
            Redis::expire($key, 36000);
            return $ac;
        }
        return null;

    }

    public static function addRecentsNew($data, $url_sign)
    {
        $recents = self::getRecentsNew($url_sign);
        array_push($recents, $data);
        if (count($recents) > 50) {
            array_shift($recents);
        }
        Redis::set("recent_apks_$url_sign", json_encode($recents));
    }

    public static function getRecentsNew($url_sign)
    {
        $recents = [];
        if (Redis::exists("recent_apks_$url_sign")) {
            $recents = json_decode(Redis::get("recent_apks_$url_sign"), true);
        }
        if (!isset($recents) || empty($recents)) $recents = [];
        return $recents;
    }
    public const KWAI_EVENT=[
        'EVENT_DOWNLOAD'=>'EVENT_DOWNLOAD',//download
        'EVENT_COMPLETE_REGISTRATION'=>'EVENT_COMPLETE_REGISTRATION',//reg
        'EVENT_PURCHASE'=>'EVENT_PURCHASE',//purchase
        'EVENT_FIRST_DEPOSIT'=>'EVENT_FIRST_DEPOSIT',//d0
        'EVENT_ADD_TO_CART'=>'EVENT_ADD_TO_CART',//
        'EVENT_CONTENT_VIEW'=>'EVENT_CONTENT_VIEW',//
    ];
    public static function kwaiEvent($userid,$event,$event_values=[])
    {

//        $cookies=['Cookie'    => $data['cookie'],
//                  'UrlSign'   => $data['url_sign'],
//                  'Platform'  => $data['type']]
        $user=self::loadCookie($userid);
        /*
         * {
              CampaignID: '987654321',
              adSETID: '123456789',
              CreativeID: '123456789',
              click_id: 'CCpgibAfpRkSWv9zxgDuFHX71q5u_vMxqmvRClE6enEynSNeQAaSvb3CCcXoqXaPwbYpThJBW5n6-62kmmECfY5He3KFgOJB9YErIJ9cIUk=',
              pixel_id: '12345678987654321'
            }
         */
        if(isset($user)&&$user['Platform']=='kw') {
            $params = json_decode($user['Cookie'], true);
            self::sendToKwai($params, $event, $event_values);
        }

    }
    public static function sendToKwai($params,$event,$event_values=[]){

        if((isset($params['pixel_id'])&&$params['pixel_id']=='545692252418097195')||(isset($params['kwai_api_id'])&&$params['kwai_api_id']=='545692252418097195')){
            $access_token='1Wvai0OBGGQlO9eVZIm+wnv1tq5hL9IudwMRdntfms4=';
        }
        if((isset($params['pixel_id'])&&$params['pixel_id']=='545692410115539004')||(isset($params['kwai_api_id'])&&$params['kwai_api_id']=='545692410115539004')){
            $access_token='cwYDbfB+9lWmVaSBWNxhFUVtL764Or8AzxGVclhG44g=';
        }
        try {
            $url = 'http://www.adsnebula.com/log/common/api';
            $data = [
                "access_token"    => $access_token,
                "clickid"         => $params['click_id'],
                "event_name"      => $event,
                "is_attributed"   => 1,
                "mmpcode"         => "PL",
                "pixelId"         => $params['pixel_id']??$params['kwai_api_id'],
                "pixelSdkVersion" => "9.9.9",
                "properties"      => json_encode($event_values),
                "testFlag"        => false,
                "trackFlag"       => false
            ];
            $httpCurl = new HttpCurl();
            $result = $httpCurl->curlPost($url, $data, 'json',true);
            Util::WriteLog("kwai", $result);
        }catch (\Exception $e){
            Util::WriteLog("kwai_error", compact("params","event","event_values"));
            Util::WriteLog("kwai_error", $e->getMessage().$e->getTraceAsString());

        }
    }
    public static function sendToKwaiTest($params,$event,$event_values=[]){
        if((isset($params['pixel_id'])&&$params['pixel_id']=='545692252418097195')||(isset($params['kwai_api_id'])&&$params['kwai_api_id']=='545692252418097195')){
            $access_token='1Wvai0OBGGQlO9eVZIm+wnv1tq5hL9IudwMRdntfms4=';
        }
        if((isset($params['pixel_id'])&&$params['pixel_id']=='545692410115539004')||(isset($params['kwai_api_id'])&&$params['kwai_api_id']=='545692410115539004')){
            $access_token='cwYDbfB+9lWmVaSBWNxhFUVtL764Or8AzxGVclhG44g=';
        }
        try {
            $url = 'http://www.adsnebula.com/log/common/api';
            $data = [
                "access_token"    => $access_token,
                "clickid"         => $params['click_id'],
                "event_name"      => $event,
                "is_attributed"   => 1,
                "mmpcode"         => "PL",
                "pixelId"         => $params['pixel_id']??$params['kwai_api_id'],
                "pixelSdkVersion" => "9.9.9",
                "properties"      => json_encode($event_values),
                "testFlag"        => false,
                "trackFlag"       => true
            ];
            $httpCurl = new HttpCurl();
            $result = $httpCurl->curlPost($url, $data, 'json',true);
            Util::WriteLog("kwai", $data);
            Util::WriteLog("kwai", $result);
        }catch (\Exception $e){
            Util::WriteLog("kwai_error", compact("params","event","event_values"));
            Util::WriteLog("kwai_error", $e->getMessage().$e->getTraceAsString());

        }
    }
    public static function ControlOldUser($UserID,$Params='')
    {
        $openGames = config('games.openKGame');
        $query = DB::table('QPTreasureDB.dbo.UserScoreControl')->where('UserID', $UserID)->first();
        if (!$query) {
            $build_sql = DB::connection('write')->table('QPTreasureDB.dbo.UserScoreControl');
            Util::WriteLog('control_old_user', compact("UserID","Params"));
            $data = [
                'ControlScore'   => (int)(-40 * NumConfig::NUM_VALUE),
                'EffectiveScore' => 0,
                'ControlKindID'  => -1,
                'Remarks'        => '',
                'InsertDate'     => date('Y-m-d H:i:s'),
                'ControlRadian'  => 0
            ];
            $build_sql->updateOrInsert(['UserID' => $UserID], $data);

            foreach ($openGames as $GameID) {
                $KindData = [
                    'UserID'        => $UserID,
                    'KindID'        => $GameID,
                    'ControlRadian' => 50,
                    'ControlDate'   => date('Y-m-d H:i:s')
                ];
                DB::connection('write')->table('QPTreasureDB.dbo.UserControlKind')->updateOrInsert(['UserID' => $UserID, 'KindID' => $GameID], $KindData);
            }
        }

    }
}
