<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Sven extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->library('curl');
        $this->load->model('common');
        $this->load->model('oo');

    }
    public function index()
    {
        $payInfo = oo::commonOprRedis('Statistics')->hMGet('svenx',['a','b','e']);
        echo json_encode($payInfo);
    }
    public function getLogs()
    {
        $time = time();
        $uidStr = '<951813><494305><1401879><435278><1007017><2665223><2665192><2208752><1200954><1543816><2634229><1774431><2095582><186243><1285671><2667515><1873305><1159505><502829><1896134><1359899><732663><130523><189650><1079916><2195057><2337151><2153158><2666290><1956383><275359><420528><2170720><2027441><424679><1860742><1706229><1548223><2665333><2307319><1067618><2510512><2101837><1599260><2668489><499945><2541888><1888542><2599527><1888542><2663256><585620><557341><2339980><510269><2201595><1502959><1233865><420782><498884><1011259><1019211><2051591>';
        $uidStr = strtr($uidStr, ['><'=>',', '<' => '', '>' =>'']);
        $logRootPath = 'deBUG/clientErrorLogFiles/';
        $uids = explode(',', $uidStr);
        $beginDate = '20211209';
        $endDate = date('Ymd', $time);
        $beginTime = strtotime($beginDate);
        $endTime = max(strtotime($endDate), $beginTime);
        for($tmpTime = $beginTime; $tmpTime <= $endTime; $tmpTime += 86400){
            $tmpDate = date('Ymd', $tmpTime);
            foreach ($uids as $uid){
                $logPath = $logRootPath . "{$tmpDate}/{$uid}";
                if(!is_dir($logPath)){
                    echo "--------dir not found for uid:{$uid}, date:{$tmpDate}" . PHP_EOL;
                    continue;
                }

                $dirHandle = opendir($logPath);
                while($file = readdir($dirHandle)){
                    if(strpos($file, $uid) === false)continue;
                    echo $logPath . '/'.$file . PHP_EOL;
                }
            }
        }
    }

    public function chmods()
    {
        $resourceRootPath = '/home/wwwroot/crazy_god_CMS/public/game/';
        $refreshList = [
            'image/activity_2/',
            'crazycoin/activity/Android/',
            'crazycoin/activity/iOS/',
        ];
        foreach ($refreshList as $path){
            $resourcePath = $resourceRootPath . $path;
            if(is_dir($resourcePath)){
                echo $resourcePath . ' is dir' . PHP_EOL;
            }
            else{
                echo $resourcePath . ' is not dir' . PHP_EOL;
            }
            $dirHandle = opendir($resourcePath);
            while($file = readdir($dirHandle)){
                if(in_array($file, ['.', '..']))continue;
                $filePath = $resourcePath . $file ;
                $permit = substr(base_convert(fileperms($filePath), 10, 8), 2);
                if($permit == 777){
                    continue;
                }
                $cmd = 'sudo  chmod 777 -R ' . $filePath;
                echo 'cmd: '.$cmd . PHP_EOL;
//                exec($cmd, $result, $returns);
//                echo ' result:' . var_export($result) . ' returns:'.var_export($returns). PHP_EOL;

                $res = chmod($filePath, 0777);
                echo ' result:' . var_export($res) . PHP_EOL;
            }
        }

    }

    public function updateUserShushuGroups(){
        date_default_timezone_set('Asia/Shanghai');
        while(true){
            $sleepTime = 1 * 60;   #每1分判断一次
            $time = time();
            $h = date('H', $time);
            $i = date('i', $time);
            if(($h == 19 && $i >= 10) || ($h > 19)){
                if($this->checkRefreshStatus()){
                    $this->updateGroups();
                }else{
                    oo::logs()->debug3('数数方分组更新未完成', 'updateShushuGroups.log');
                    $sleepTime = 10;   # 未更新，每10秒判断一次
                }
            }else{
                oo::logs()->debug3('未到时间，不做处理', 'updateShushuGroups.log');
            }
            sleep($sleepTime);
        }
    }
    private function updateGroups(){
        $time = time();
        $isUpdatedKey = okeys::shushuGroupUpdateCompleteKey(date('Ymd', $time));
        $isUpdated = oo::commonOprRedis('statistics')->get($isUpdatedKey);
        if($isUpdated){ #已更新，不做处理
           oo::logs()->debug3('今日分组更新已完成', 'updateShushuGroups.log');
            return true;
        }

        oo::logs()->debug3('拉取数数方最新分组用户开始;', 'updateShushuGroups.log');
        $config = oo::commonOprModel('config')->getUserGroupConfigByCid(5);
        $updateGroups = oo::commonOprRedis('statistics')->hgetall(okeys::configSSGroupUpdate());
        $updateGroupsIds = array_keys($updateGroups);
        $uidGroupsNewerList = [];
        $validGroups = [];
        foreach ($config as $v){
            if($v['groupId'] == 0 || $v['name'] == '数数-默认分组'){
                continue;
            }
            if(!in_array($v['id'], $updateGroupsIds))continue;
            $validGroups[$v['id']] = $v['name'];
            $uidList = oo::commonOprModel('SSdata')->getUidListByGroupName($v['name']);
            if(!empty($uidList)){
                foreach ($uidList as $uid){
                    $uidGroupsNewerList[$uid] = $uidGroupsNewerList[$uid] ?? [];
                    $uidGroupsNewerList[$uid][] = $v['id'];
                }
            }
        }

        oo::logs()->debug3('拉取数数方最新分组用户完毕；开始计算用户最新分组', 'updateShushuGroups.log');
        oo::logs()->debug3('拉取的数数分组列表：'.json_encode($validGroups), 'updateShushuGroups.log');
        oo::logs()->debug3('拉取的总用户数：'.count($uidGroupsNewerList), 'updateShushuGroups.log');
        $debugData = [];
        foreach ($uidGroupsNewerList as $uid => $groupsNew){
            $debugData[$uid] = [
                'new' => implode(',', $groupsNew)
            ];
            $removeGroups = [];
            $userData = oo::commonOprModel('member')->getUserDynamicsData($uid);
            $groupsOld = empty($userData['groupId3']) ? [] : explode(',', $userData['groupId3']);
            sort($groupsOld);
            $debugData[$uid]['old'] = implode(',', $groupsOld);
            foreach ($updateGroupsIds as $groupId){    #遍历用户新的分组
                if(!in_array($groupId, $groupsNew)){  # 如果用户最新分组数据不在分组里，从老的分组删除该分组
                    $removeGroups[] = $groupId;
                    $idx = array_search($groupId,$groupsOld);
                    if($idx !== false)unset($groupsOld[$idx]);
                }
            }
            $groupsNew = array_merge($groupsOld, $groupsNew);
            $groupsNew = array_filter(array_unique($groupsNew));
            sort($removeGroups);
            sort($groupsNew);
            $debugData[$uid]['removed'] = implode(',', $removeGroups);
            $debugData[$uid]['newest'] = implode(',', $groupsNew);

            $userData['groupId3'] = implode(',', $groupsNew);
            oo::commonOprModel('member')->setUserDynamicsData($uid, $userData);
        }
        # 更新完毕，设置已更新标识,存在一天
        oo::commonOprRedis('statistics')->setex($isUpdatedKey, 1);

        oo::logs()->debug3('用户数数分组数据更新结束', 'updateShushuGroups.log');
    }

    private function checkRefreshStatus(){
        # 获取所有数数分组
        $config = oo::commonOprModel('config')->getUserGroupConfigByCid(5);

        #获取需要更新的数数分组id
        $updateGroups = oo::commonOprRedis('statistics')->hgetall(okeys::configSSGroupUpdate());
        $updateGroupsIds = array_keys($updateGroups);
        $progressList = [];
        foreach ($config as $v){
            if($v['groupId'] == 0 || $v['name'] == '数数-默认分组'){
                continue;
            }
            if(!in_array($v['id'], $updateGroupsIds))continue;

            #校验数数方分组刷新进度
            $response = oo::commonOprModel('SSdata')->checkRefreshStatusByGroupName($v['name']);
            if(is_string($response))$response = json_decode($response, true);
            $progressList[$v['name']] = $response['data']['progress'] ?? 0;
            if($progressList[$v['name']] < 100){
                oo::logs()->debug3('用户数数分组数据更新未完成:'.$v['name'], 'updateShushuGroupsRefresh.log');
                return false;    #进度未到100 这当前数数方分组刷新未完成
            }
        }
        return true;
    }


    public function tiktokCallback(){
        $params = $this->input->get();
        oo::commonOprRedis('Statistics')->set(okeys::tiktokParamsKey(), json_encode($params));
    }

    public function getTikTokAuthParams(){
        $params = oo::commonOprRedis('Statistics')->get(okeys::tiktokParamsKey());
        exit($params);
    }

    public function getTikTokAuthToken(){
        $path = "/open_api/v1.2/oauth2/access_token/";
        $url = "https://business-api.tiktok.com" . $path;


        $secret = '196ca870c4aa8a58fb750a51c2b2918d88b60551';
        $app_id = '7068569320179105794';
        $params = oo::commonOprRedis('Statistics')->get(okeys::tiktokParamsKey());
        $auth_code = json_decode($params, true)['auth_code'] ?? '';

        /* Args in JSON format */
        $json_str = sprintf("{\"secret\": \"%s\", \"app_id\": \"%s\", \"auth_code\": \"%s\"}", $secret, $app_id, $auth_code);

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $json_str,
            CURLOPT_HTTPHEADER => array(
                "Content-Type: application/json",
            ),
        ));

        $response = curl_exec($curl);
        curl_close($curl);
        oo::commonOprRedis('Statistics')->set(okeys::tiktokTokenParamsKey(), $response);
        exit($response);

    }


    public function getUserReturns(){
        $datetime = strtotime('2021-11-01');
        $curTime = time();
        $endtime = $curTime - 30 * 86400;
        $userTbl = otable::userinfo();
        $dayAfterArr = [30, 90];
        $data = [];
        while($datetime < $endtime){
            $curDate =  date('Ymd', $datetime);
            echo $curDate . PHP_EOL;
            $fbUids = $guestUids = [];
            $dayStartTime = $datetime;
            $dayEndTime   = $datetime + 86400;
            $sql = "select uid,isFb from {$userTbl} where createtime >={$dayStartTime} and createtime <{$dayEndTime} ";
            $registerUser = oo::commonOprDb('gameslave')->getAll($sql);
            foreach ($registerUser as $user){
                if($user['isFb'])$fbUids[] = $user['uid'];
                else $guestUids[] = $user['uid'];
            }
            $data[$curDate] = [
                'fbCount' => count($fbUids),
                'guestCount' => count($guestUids),
            ];
            $datetime += 86400;
            foreach ($dayAfterArr as $days){
                $afterTime = $dayStartTime + $days * 86400;
                $loginUids = [];
                if($afterTime < ($curTime - 86400)){
                    $afterDate = date('Ymd', $afterTime);
                    $loginTbl = otable::newloginLog($afterDate);
                    $sql = "select uid from {$loginTbl} group by uid";
                    $loginUsers = oo::commonOprDb('report')->getAll($sql);
                    $loginUids = array_column($loginUsers, 'uid');
                }
                $data[$curDate][$days.'FbReturnUids'] = count(array_intersect($fbUids, $loginUids));
                $data[$curDate][$days.'GuestReturnUids'] = count(array_intersect($guestUids, $loginUids));
            }
        }

        $header = [
            '日期', 'FB注册人数', '游客注册人数', '30FB留存', '30游客留存', '90FB留存', '90游客留存'
        ];
        $f = fopen(__DIR__."/留存数据{$curTime}.csv", 'w');
        fputcsv($f, $header);
        foreach ($data as $date => $item){
            $line = [
                $date, $item['fbCount'], $item['guestCount'], $item['30FbReturnUids'], $item['30GuestReturnUids'], $item['90FbReturnUids'], $item['90GuestReturnUids']
            ];
            fputcsv($f, $line);
        }
        fclose($f);
        echo 'ok';
    }
    public function getThUserReturns(){
        $datetime = strtotime('2022-02-01');
        $curTime = time();
        $endtime = $curTime - 2 * 86400;
        $userTbl = otable::registerLog();
        $dayAfterArr = [1, 3, 7];
        $data = [];
        while($datetime < $endtime){
            $curDate =  date('Ymd', $datetime);
            echo $curDate . PHP_EOL;
            $sql = "select uid from {$userTbl} where date ='{$curDate}' and country='TH' ";
            $registerUser = oo::commonOprDb('report')->getAll($sql);
            $uids = array_column($registerUser, 'uid');
            $data[$curDate] = [
                'count' => count($uids),
            ];
            foreach ($dayAfterArr as $days){
                $afterTime = $datetime + $days * 86400;
                $loginUids = [];
                if($afterTime < ($curTime - 86400)){
                    $afterDate = date('Ymd', $afterTime);
                    $loginTbl = otable::newloginLog($afterDate);
                    $sql = "select uid from {$loginTbl} group by uid";
                    $loginUsers = oo::commonOprDb('report')->getAll($sql);
                    $loginUids = array_column($loginUsers, 'uid');
                }
                $ReturnUids = count(array_intersect($uids, $loginUids));
                $data[$curDate][$days.'ReturnUids'] = $ReturnUids;
                $data[$curDate][$days.'ReturnRate'] = empty($ReturnUids) ? 0 : $ReturnUids/count($uids);
            }
//            echo json_encode($data);die;
            $datetime += 86400;
        }

        $header = [
            '日期', '注册人数',  '1留存', '3留存', '7留存',  '1留存率', '3留存率', '7留存率'
        ];
        $f = fopen(__DIR__."/留存数据{$curTime}.csv", 'w');
        fputcsv($f, $header);
        foreach ($data as $date => $item){
            $line = [
                $date, $item['count'],  $item['1ReturnUids'],$item['3ReturnUids'],$item['7ReturnUids'],  $item['1ReturnRate'],$item['3ReturnRate'],$item['7ReturnRate']
            ];
            fputcsv($f, $line);
        }
        fclose($f);
        echo 'ok';
    }

    public function formatOnlineData(){
        date_default_timezone_set('UTC');
        $tbl = otable::staData();
        $timestamp = time();
        $yesterday = date('Ymd', $timestamp - 86400);
        $sql = "select * from {$tbl} where date='{$yesterday}' and type='foxOnlinePlaying' limit 1";
        $yesterdayOnlinePlaying = oo::commonOprDb('statistics')->getOne($sql, 1);
        $onlineData = json_decode($yesterdayOnlinePlaying['data'], true)[1];
        ksort($onlineData);

        $hiData = [];
        $lastNum = 0;
        foreach ($onlineData as $timestampKey => $onlineNum){
            if(empty($onlineNum))$onlineNum = $lastNum;
            $hi = date('Ymd H:i', $timestampKey);
            $lastNum = $onlineNum;
            $hiData[$hi] = $onlineNum;
        }

        $yesterdayBegin = strtotime($yesterday);
        $yesterdayEnd = $yesterdayBegin+86400;
        $time = $yesterdayBegin;
        while($time < $yesterdayEnd){
            $hi = date('Ymd H:i', $time);
            if(empty($hiData[$hi])){
                $lhi = date('Ymd H:i', $time-60);
                echo $hi . PHP_EOL;
                echo strtotime($hi) . PHP_EOL;
                $onlineData[strtotime($hi)] = $hiData[$lhi];
            }
            $time += 60;
        }
        ksort($onlineData);
        $data = [
            1 => $onlineData
        ];
        $data = json_encode($data);
        $sql = "update {$tbl} set data='{$data}' where date='{$yesterday}' and type='foxOnlinePlaying' limit 1";
        echo $sql . PHP_EOL;
        $yesterdayOnlinePlaying = oo::commonOprDb('statistics')->query($sql, 1);
        var_dump($yesterdayOnlinePlaying);
        echo json_encode($onlineData);
    }


    public function onlineData(){
        date_default_timezone_set('UTC');
        $tbl = otable::staData();
        $timestamp = time();
        $yesterday = date('Ymd', $timestamp - 86400);
        $sql = "select * from {$tbl} where date='{$yesterday}' and type='foxOnlinePlaying' limit 1";
        $yesterdayOnlinePlaying = oo::commonOprDb('statistics')->getOne($sql, 1);
        $onlineData = json_decode($yesterdayOnlinePlaying['data'], true)[1];
        ksort($onlineData);
        $lastNum = 0;
        $foxOnlineData = [];
        foreach ($onlineData as $timestampKey => $onlineNum){
            if(empty($onlineNum))$onlineNum = $lastNum;
            $lastNum = $onlineNum;
            $i = date('i', $timestampKey)	;
            if($i%5)continue;
            $foxOnlineData[date('H:i', $timestampKey + 8 * 3600)] = $onlineNum;
        }
        echo json_encode($foxOnlineData);

    }


    public function delExpiredLogs(){
        $paths = [
            PATH_DAT."logs/",
            PATH_DAT."clientErrorLogFiles/",
            PATH_DAT."mysql/",
            PATH_DAT."userShushuGroups/",
        ];
        $expireTime = time() - 8 * 86400;
        foreach ($paths as $path){
            echo $path .'::::::::'. PHP_EOL;
            $d = opendir($path);
            while($f = readdir($d)){
                if(in_array($f, ['.', '..']))continue;
                $array = explode('.', $f);
                $date = $array[0];
                $time = strtotime($date);
                if(empty($time))continue;
                $filePath = $path  . $f;
                if($time < $expireTime){
                    echo $filePath . '过期' . PHP_EOL;
                    if(is_dir($filePath)){

                        $cmd = "rm -rf {$filePath}";
                        exec($cmd);
                    }else{
                        unlink($filePath);
                    }
                }else{
                    echo $filePath . '未过期' . PHP_EOL;
                }
            }
            closedir($d);
        }
    }

    public function removeDir($path = ''){
        if(empty($path) || !is_dir($path))return true;
        echo '开始删除目录：'.$path  . PHP_EOL;
        $d = opendir($path);
        while($f = readdir($d)){
            echo $f .PHP_EOL;
            if(in_array($f, ['.', '..']))continue;
            $filePath = $path . DIRECTORY_SEPARATOR . $f;
            echo $filePath .PHP_EOL;
            if(is_dir($filePath)){
                echo $filePath  . ' 是目录：'.PHP_EOL;
                $this->removeDir($filePath);
            }else{
                unlink($filePath);
            }
        }
        closedir($d);
        rmdir($path);
        echo '删除目录：'.$path  . PHP_EOL;

    }

    public function delUnusedConfigFile(){
        $configUrl = 'http://cc-testhttp.superant.cc/api/config_crazy.php';
        $oos_debug = $this->config->item('oos_debug');
        if(!$oos_debug){
            $configUrl = 'https://coin.crazycoin.link/api/config_crazy.php';
        }
        $config = file_get_contents($configUrl);
        $config = @json_decode($config, true) ?? [];
        if(empty($config))return;
        $path =  './public/game/config/';
        echo '有用文件数：'.count($config) . PHP_EOL;
        if(is_dir($path)) {
            $dirHandler = opendir($path);
            $fileCnt = 0;
            $cntMap = [];
            while($tf = readdir($dirHandler)){
                if(in_array($tf, ['.','..']))continue;
                $filePath = $path . $tf;
                if(is_dir($filePath))continue;
                $fileCnt++;
                if(in_array($tf, $config)){
                    $cntMap['存在']++;
                    unset($config[array_search($tf,$config)]);
                }else{
                    $cntMap['不存在']++;
//                    unlink($filePath);
                }
            }
            echo '总文件数：'.$fileCnt . PHP_EOL;
            echo json_encode($cntMap, JSON_UNESCAPED_UNICODE) . PHP_EOL;
            echo json_encode($config, JSON_UNESCAPED_UNICODE) . PHP_EOL;
        }

    }

    public function subNsq(){
        $nsq_lookupd = new NsqLookupd("10.0.24.134:4161"); //the nsqlookupd http addr
        $nsq = new Nsq();
        $config = array(
            "topic" => "stopservie_config",
            "channel" => "struggle",
            "rdy" => 2,                //optional , default 1
            "connect_num" => 1,        //optional , default 1
            "retry_delay_time" => 5000,  //optional, default 0 , if run callback failed, after 5000 msec, message will be retried
            "auto_finish" => true, //default true
        );

        $nsq->subscribe($nsq_lookupd, $config, function($msg,$bev){

            echo $msg->payload.PHP_EOL;
            echo $msg->attempts.PHP_EOL;
            echo $msg->messageId.PHP_EOL;
            echo $msg->timestamp.PHP_EOL.PHP_EOL.PHP_EOL.PHP_EOL;

        });
    }
    public function pubNsq(){
        $res = $this->SendNsqMsg('test', ['a' => 'A']);
        var_dump($res);
    }


    public function SendNsqMsg($topic,$body,$hearder = []){
        $nsqdAddrs = $this->config->item('nsqAddress');
        $bodyArr = $body;
        $data =array_values( unpack("C*", json_encode($body)));
        $nsq = new Nsq();
        $isTrue = false;
        foreach ($nsqdAddrs as $nsqdAddr){
            $isTrue = $nsq->connectNsqd([$nsqdAddr]);
            if($isTrue)break;
        }

        if($isTrue){
            $res = $nsq->publish($topic,json_encode($data));
            if(!$res)
                oo::logs()->debug3(['nsqdAddrs' => $nsqdAddrs, "msg"=>"publish failed","topic"=>$topic,"info"=>$bodyArr],"publishNsq.log");
            else
                oo::logs()->debug3(['nsqdAddrs' => $nsqdAddrs, "msg"=>"publish successed","topic"=>$topic,"info"=>$bodyArr],"publishNsq.log");
            $nsq->closeNsqdConnection();
        }else{
            oo::logs()->debug3(['nsqdAddrs' => $nsqdAddrs, "msg"=>"lose connect...","topic"=>$topic,"info"=>$bodyArr],"publishNsq.log");
        }
        return $res;
    }

    public function refreshShushuGroups(){
        # 当前系统所有数数分组
        $tb = otable::UserGroupConfig(2);
        $localGroups = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} where cid=5 and sort >= 0",MYSQLI_ASSOC);


        # 数数方最新数数分组
        $data = oo::commonOprModel('SSdata')->getGroupList();
        $datas = [];
        $existGroups = [];
        foreach ($data as $k=>$v){
            $existGroups[] = $v['id'];
            $datas[$k] =[
                'cid'=>5,
                'groupId'=>$v['id'],
                'name'=>$v['clusterName'],
                'remark'=>$v['displayName'],
                'update'=>1,
                'count'=>$v['usersNum']
            ];
        }

        # 后台存在，数数不存在的分组
        $delGroups = [];
        foreach ($localGroups as $group){
            if(!empty($group['groupId']) && !in_array($group['groupId'], $existGroups)){
                $delGroups[] = $group['id'];
            }
        }

        oo::logs()->debug3(['后台数数分组数据'=>$localGroups,'数数最新分组数据'=>$datas,'需要删除的分组数据'=>$delGroups],"refreshShushuGroups.log");
        if(!empty($delGroups)){
            $delIdsStr = implode(',', $delGroups);

            # 将数数那边删除的分数在这边废弃
            oo::commonOprDb('games')->query("update  {$tb} set sort=-1 where cid=5 and id in ({$delIdsStr})",MYSQLI_ASSOC);
            $updateKey = okeys::configSSGroupUpdate();
            $hideKey = okeys::configSSGroupShow();
            foreach ($delGroups as $id){
                oo::commonOprRedis('statistics')->hSet($hideKey,$id,$id);   # 显示状态为隐藏
                oo::commonOprRedis('statistics')->hDel($updateKey, $id);    # 更新状态为不更新
            }
        }

    }


    public function formatAAAData(){
        $date = $startDate = '2022-04-12';
        $endDate = '2022-04-25';
        $updateCnt = [];
        while(true){
            echo $date. PHP_EOL;
            $date = date('Y-m-d', strtotime('+1day', strtotime($date)));
            if($date > $endDate)break;


            $updateCnt[$date] = [];
            $table = otable::TAdjustPeriodView();//'t_adjust_period_view';
            $sql = "select * from {$table} where date = '{$date}' and creatives_id = '' and campaigns_name like '%AAA%'";
            $rows = oo::commonOprDb('report')->getAll($sql);
            $patter = '/\((\d+)\_\d+\)$/';
            echo count($rows) . PHP_EOL;
            foreach ($rows as $row){
                preg_match($patter, $row['creatives_name'], $matchs);
                if(!empty($matchs[1])){
                    $data = [
                        'creatives_id' => $matchs[1]
                    ];
                    $updateSql = funs::db_updateSQL($table, $data, ' id='.$row['id']);
                    $res = oo::commonOprDb('report')->query($updateSql);
                    $updateCnt[$date][intval($res)]++;
                }
            }
        }
        echo json_encode($updateCnt) . PHP_EOL;
    }

    public function decryptFBData($referer, $times = 0){
        $key = '99eaa1e052e3fe42ebe3379fcdbfa45953842974c6cb868e3beb5c3e4b236063';
        $queryInfo = \GuzzleHttp\Psr7\parse_query($referer);
        $utm_content = json_decode($queryInfo['utm_content'], true);
        $nonce = $utm_content['source']['nonce'];
        $cipher = $utm_content['source']['data'];
        try {
            $result = sodium_crypto_aead_aes256gcm_decrypt ( sodium_hex2bin ( $cipher ), '' , sodium_hex2bin ( $nonce ), sodium_hex2bin ( $key ));
            return $result;
        }catch (\throwable $e){
            if($times > 0)throw  $e;
            $times++;
            return $this->decryptFBData(urldecode($referer),$times );
        }
//        echo $result; //这有16字节的标签修剪
    }

    function getCsvData($file)
    {
        if (!is_file($file)) {
            exit('没有文件');
        }

        $handle = fopen($file, 'r');
        if (!$handle) {
            exit('读取文件失败');
        }
        $list = [];
        while (($data = fgetcsv($handle)) !== false) {
            $list[] = $data;
        }

        fclose($handle);
        return $list;
    }

    function updateAdjustData(){
        $data = $this->getCsvData(__ROOT__ . '/Excel/astak-fb.csv');
        $table = otable::AdJustData();
        $failedQueryList = [];
        echo count($data);
        $successCnt = 0;
        foreach ($data as $k => $item){
            if(!$k)continue;
            $adid = $item[1];
            $referer = $item[5];
            try{
                $decryptData = $this->decryptFBData($referer);
                $decryptData = json_decode($decryptData, true);
                $newData = [];
                $newData['network_name'] = 'Facebook';
                $newData['campaign_name'] = sprintf('%s(%d)', $decryptData['campaign_group_name'],$decryptData['campaign_group_id']);
                $newData['adgroup_name'] = sprintf('%s(%d)', $decryptData['campaign_name'],$decryptData['campaign_id']);
                $newData['creative_name'] = sprintf('%s(%d)', $decryptData['adgroup_name'],$decryptData['adgroup_id']);
                $newData['tracker_name'] = implode('::', [$newData['network_name'], $newData['campaign_name'], $newData['adgroup_name'], $newData['creative_name']]);
                $updateSql = funs::db_updateSQL($table, $newData, " `adid`='{$adid}'");
                $res = oo::commonOprDb('games')->query($updateSql);
                if(!$res){
                    $failedQueryList[$adid] = $updateSql;
                }else{
                   echo ++$successCnt . PHP_EOL;
                }
            }catch (\throwable $e){
                $failedQueryList[$adid] = $item;
            }
        }
        echo  json_encode($failedQueryList);
    }

    private function changeCountry($country){
        $country = trim($country);
        switch (ucfirst(strtolower($country))){
            case 'Poland':  return'PL';
            case 'Romania': return'RO';
            case 'United kingdom': return'GB';
        }
        var_dump($country);
        die('未识别的国家：'.$country);
    }
    function updateGoogleSpendsData(){
        $data = $this->getCsvData(__ROOT__ . '/Excel/cost5.csv');
        $i = 2;
        while($i>0){
            $i--;
            array_shift($data);
        }
        echo count($data);
        $tb = otable::googleCampaign();
        $keys = [
            'date_start',
            'campaign_name',
            'country',
            'campaign_id',
            'currency',
            'spend',
            'clicks',
            'impressions',
            'conversions',
        ];
        $res = [];
        foreach ($data as $k => $v){
            if(!$k)continue;
//            var_dump($v);die;
            $v = array_combine($keys, $v);
            $v["country"] = $this->changeCountry($v["country"]);
            $v['date_start'] = date('Y-m-d', strtotime($v['date_start'] ));
            unset($v["currency"]);
//            var_dump($v);die;
            $where = " date_start = '{$v["date_start"]}' AND campaign_id = '{$v["campaign_id"]}' AND campaign_name = '{$v["campaign_name"]}' AND country = '{$v["country"]}'";
            $sql2 = "SELECT COUNT(*) AS count FROM {$tb} WHERE {$where}";
            $retTemp = oo::commonOprDb('report')->getOne($sql2,1);
//            var_dump($retTemp);
            if($retTemp["count"]){
                $sql2 = funs::db_updateSQL($tb,$v,$where);
            }else{
                $sql2 = funs::db_insertSQL($tb,$v);
            }
            var_dump($sql2);
            $res[] = oo::commonOprDb('report')->query($sql2);
        }
        var_dump($res);

    }
}


