<?php


namespace App\dao\af;


use App\Facade\TableName;
use App\Http\helper\HttpCurl;
use App\Services\ApkService;
use App\Services\UploadOfflineConversion;
use App\Util;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class AfEvent
{
    protected $config;
    protected $afToken;
    protected $userinfo=null;
    protected $adjustConfig=null;

    // 设备码类型 -- 可用的设备 ID
    protected $eventType = [1 => 'adid', 2 => 'gps_adid', 3 => 'fire_adid', 4 => 'oaid', 5 => 'idfa', 6 => 'idfv', 7 => 'android_id'];

    public function __construct()
    {
        $this->config = config('api.af');
        $this->afToken = config('aftoken');
    }

    // af充值事件
    public function pay($AdId, $UserID, $eventType)
    {
        try {

            if (!array_key_exists($eventType, $this->eventType)) return true;

            $userinfo=$this->getUserInfo($UserID);

            $Channel = $userinfo->Channel;
            $CustomID = $userinfo->CustomID;
            $PackageName = $userinfo->LastLogonPackage;

            if (empty($AdId)) {
                Log::channel('adjustEvent')->info('adid为空 '.$UserID);
                $AdId = DB::connection('write')->table(TableName::QPAccountsDB() . 'AccountsInfo')
                    ->where('UserID', $UserID)
                    ->value('LastLogonMachine');
            }

            $gateway = $this->config['gateway'];

            $afTokenConfig =  $this->adjustConfig;
            if(!isset($afTokenConfig)||empty($afTokenConfig)){
                Util::WriteLog("aftoken",$userinfo);
                return true;
            }
            if($afTokenConfig['token']=='wgh5')return;
            //过度adjust账号
//            if(intval($Channel)==105&&intval($CustomID)>0){
//                $CustomID=intval($CustomID);
//                $v=intval($CustomID/1000);
//                if(isset($this->afToken[$Channel."_".$v])){
//                    $afTokenConfig = $this->afToken[$Channel."_".$v];
//                }
//            }

            $data = [$this->eventType[$eventType] => $AdId, 'event_token' => $afTokenConfig['payOk'], 'app_token' => $afTokenConfig['token'], 's2s' => 1, 'created_at_unix' => time()];

            Log::channel('adjustEvent')->info('记录渠道包:'.$Channel);
            Log::channel('adjustEvent')->info('请求数据'.\GuzzleHttp\json_encode($data));
            $curl = new HttpCurl();
            $res = $curl->curlPost($gateway, $data, '');
            if (is_array($res)) {
                $res = json_encode($res);
            }
            Log::channel('adjustEvent')->info('af充值事件' . $UserID . ' - ' . $res);
        } catch (\Exception $exception) {
            Log::channel('adjustEvent')->info('af充值事件失败' . $UserID . $exception->getMessage());
        }
    }

    // af充值金额统计事件
    public function paySum($AdId, $UserID, $Recharge, $eventType)
    {
        try {

            if (!array_key_exists($eventType, $this->eventType)) return true;


            if ($Recharge < 0) return true;


//            $userinfo=DB::table(TableName::QPAccountsDB() . 'AccountsInfo')
//                ->where('UserID', $UserID)->select("Channel","CustomID")->first();

            $userinfo=$this->getUserInfo($UserID);
            $Channel = $userinfo->Channel;
            $CustomID = $userinfo->CustomID;


            $gateway = $this->config['gateway'];

            $afTokenConfig =  $this->adjustConfig;
            if(!isset($afTokenConfig)||empty($afTokenConfig)){
                Util::WriteLog("aftoken",$userinfo);
                return true;
            }
            if($afTokenConfig['token']=='wgh5')return;
            //过度adjust账号
//            if(intval($Channel)==105&&intval($CustomID)>0){
//                $CustomID=intval($CustomID);
//                $v=intval($CustomID/1000);
//                if(isset($this->afToken[$Channel."_".$v])){
//                    $afTokenConfig = $this->afToken[$Channel."_".$v];
//                }
//            }

            $data = [$this->eventType[$eventType] => $AdId, 'event_token' => $afTokenConfig['PaySum'], 'app_token' => $afTokenConfig['token'], 's2s' => 1, 'created_at_unix' => time(), 'revenue' => $Recharge, 'currency' => env('CONFIG_24680_CURRENCY','BRL')];
            Log::channel('adjustEvent')->info('记录渠道包:'.$Channel);
            Log::channel('adjustEvent')->info('请求数据'.\GuzzleHttp\json_encode($data));

            if(!in_array($Channel,[103,"103"])){
                //为了投vo取消了
//                $data['revenue']=$Recharge/10;
//                Log::channel('adjustEvent')->info('非联运渠道，收入数据/10:'.$data['revenue']);
            }
            $curl = new HttpCurl();
            $res = $curl->curlPost($gateway, $data, '');
            if (is_array($res)) {
                $res = json_encode($res);
            }
            Log::channel('adjustEvent')->info('af充值金额统计事件' . $UserID . ' - ' . $res);
        } catch (\Exception $exception) {
            Log::channel('adjustEvent')->info('af充值金额统计事件' . $UserID . $exception->getMessage());
        }
    }
    protected $UserID;
    protected function getUserInfo($UserID){
        if(!$this->userinfo||$this->UserID!=$UserID){
            $this->UserID=$UserID;
            $this->userinfo=DB::table(TableName::QPAccountsDB() . 'AccountsInfo')
                ->where('UserID', $UserID)->first();
        }
        if(!$this->adjustConfig){
            $this->adjustConfig=DB::table('QPPlatformDB.dbo.ChannelPackageName')->where('Channel',$this->userinfo->Channel)->value('AdjustPayConfig');
            if(!empty( $this->adjustConfig)) $this->adjustConfig=json_decode( $this->adjustConfig,true);
        }
        return $this->userinfo;
    }
    // af充值人数统计事件
    public function payCount($AdId, $UserID, $eventType)
    {
        try {
            if (!array_key_exists($eventType, $this->eventType)) return true;

            $userInfo=$this->getUserInfo($UserID);

            $Channel = $userInfo->Channel;
            $RegisterDate=$userInfo->RegisterDate;
            $CustomID = $userInfo->CustomID;

            $isD0=(date("Y-m-d")==date("Y-m-d", strtotime($RegisterDate)));
//            $isD0=(time()-strtotime($RegisterDate)<86400);

            $gateway = $this->config['gateway'];
            $afTokenConfig =  $this->adjustConfig;
            if(!isset($afTokenConfig)||empty($afTokenConfig)){
                Util::WriteLog("aftoken",$userInfo);
                return true;
            }

            if($afTokenConfig['token']=='wgh5')return;
            //过度adjust账号
//            if(intval($Channel)==105&&intval($CustomID)>0){
//                $CustomID=intval($CustomID);
//                $v=intval($CustomID/1000);
//                if(isset($this->afToken[$Channel."_".$v])){
//                    $afTokenConfig = $this->afToken[$Channel."_".$v];
//                }
//            }

            $PayCountD0Event = $afTokenConfig['PayCountD0'] ?? 0;
            $PayCountEvent = $afTokenConfig['PayCount'] ?? 0;

            if($PayCountEvent === 0)  return true;

            Log::channel('adjustEvent')->info('记录渠道包:'.$Channel.",isD0:".($isD0?1:0).",date:".$RegisterDate);

            if($PayCountD0Event!==0&&$isD0){
                $data = [$this->eventType[$eventType] => $AdId, 'event_token' => $PayCountD0Event, 'app_token' => $afTokenConfig['token'], 's2s' => 1, 'created_at_unix' => time()];
                Log::channel('adjustEvent')->info('请求数据'.\GuzzleHttp\json_encode($data));
                $curl = new HttpCurl();
                $res = $curl->curlPost($gateway, $data, '');
                if (is_array($res)) {
                    $res = json_encode($res);
                }
                Log::channel('adjustEvent')->info('af充值人数D0统计事件' . $UserID . ' - ' . $res);

            }
            $data = [$this->eventType[$eventType] => $AdId, 'event_token' => $PayCountEvent, 'app_token' => $afTokenConfig['token'], 's2s' => 1, 'created_at_unix' => time()];

            Log::channel('adjustEvent')->info('请求数据'.\GuzzleHttp\json_encode($data));
            $curl = new HttpCurl();
            $res = $curl->curlPost($gateway, $data, '');
            if (is_array($res)) {
                $res = json_encode($res);
            }
            Log::channel('adjustEvent')->info('af充值人数统计事件' . $UserID . ' - ' . $res);



        } catch (\Exception $exception) {
            Log::channel('adjustEvent')->info('af充值人数统计事件' . $UserID . $exception->getMessage());
        }
    }
    public function recordKwaiRecharge($userid,$payAmt){

        $arr=ApkService::loadCookie($userid);
        if(isset($arr)&&$arr['Platform']=='kw') {
            $cookie = $arr['Cookie'];
            ApkService::sendToKwai(json_decode($cookie, true), ApkService::KWAI_EVENT['EVENT_PURCHASE'],['currency'=>'USD','value'=>floor($payAmt/5)]);
            //唯一性记录
            if($arr['UniqueAction']<4){
                $userinfo=$this->getUserInfo($userid);
                $RegisterDate=$userinfo->RegisterDate;

                $isD0=(date("Y-m-d")==date("Y-m-d", strtotime($RegisterDate)));
//                $isD0=(time()-strtotime($RegisterDate)<86400);

                if($isD0) {
                    $arr['UniqueAction'] = 4;
                    ApkService::sendToKwai(json_decode($cookie, true), ApkService::KWAI_EVENT['EVENT_ADD_TO_CART']);
                }else{
                    $arr['UniqueAction'] = 6;
                }
                ApkService::updateCookie($userid, $arr);
                ApkService::sendToKwai(json_decode($cookie, true), ApkService::KWAI_EVENT['EVENT_FIRST_DEPOSIT']);
            }
        }
    }
    public function recordGoogleRecharge($userid,$payAmt){

        $arr=ApkService::loadCookie($userid);
        if(isset($arr)&&$arr['Platform']=='gg') {
            $cookie = json_decode($arr['Cookie'], true);
            $userinfo=$this->getUserInfo($userid);

            UploadOfflineConversion::pay($userinfo->Channel,$cookie,$payAmt,$userinfo->LastLogonPackage);
            //唯一性记录
            if($arr['UniqueAction']<4){
                $userinfo=$this->getUserInfo($userid);
                $RegisterDate=$userinfo->RegisterDate;

                $isD0=(date("Y-m-d")==date("Y-m-d", strtotime($RegisterDate)));
//                $isD0=(time()-strtotime($RegisterDate)<86400);

                if($isD0) {
                    $arr['UniqueAction'] = 4;
                    UploadOfflineConversion::d0($userinfo->Channel,$cookie,$userinfo->LastLogonPackage);
                }else{
                    $arr['UniqueAction'] = 6;
                }
                ApkService::updateCookie($userid, $arr);
                UploadOfflineConversion::d1($userinfo->Channel,$cookie,$userinfo->LastLogonPackage);
            }
        }
    }

}
