<?php

if (substr(PHP_SAPI_NAME(), 0, 3) !== 'cli') {
    die("The program runs only in CLI mode!");
}
const API_TOKEN = 'Tha-k75HDFTdG9WE_s58';
const APP_TOKEN = '9z4r8gsp7k00';
const DB_CONN = 'report';
const API_URL = 'https://dash.adjust.com/control-center/reports-service/report?';
!defined('TIMESTAMP') && define('TIMESTAMP', time());
$sid = $lid = 1;
include_once dirname(__FILE__) . "/crontab.inc.php";
include_once dirname(__FILE__) . "/../com.php";
set_time_limit(0);
$hi = date('Hi', TIMESTAMP);
//$hi = '0000';
//$hi = '0815';
//$hi = '0830';
echo time() . PHP_EOL;
switch ($hi){
    case '0000':// 8点00分 拉取周报
    case '0800':// 8点00分 拉取周报
        Adjust::adjustReport('week') ;
        break;
    case '0030':// 8点30分 拉取月报
    case '0830':// 8点30分 拉取月报
        Adjust::adjustReport('month') ;
        break;
}
Class Adjust{
    static $headers = [
        'Authorization:Bearer '.API_TOKEN
    ];
    private static function getDateList($type){
        $dayTime = strtotime(date('Y-m-d', TIMESTAMP));
        switch ($type){
            case 'day':
                $maxNum = 120;
                $beginTime = $dayTime - 86400;
                break;
            case 'week':
                $maxNum = 52;
                $weekIdx = date('w', $dayTime);
                $weekIdx = empty($weekIdx) ? 7 : $weekIdx;
                $beginTime = $dayTime - ($weekIdx-1)*86400;
                break;
            case 'month':
                $maxNum = 13;
                $monthIdx = date('d', $dayTime);
                $beginTime = $dayTime - ($monthIdx-1)*86400;
                break;
            default:
                return[];
        }
        $dateList = [];
        for($i = 0; $i<= $maxNum; $i++){
            $stime = strtotime("-{$i} {$type}", $beginTime);
            $etime = strtotime("+1 {$type}", $stime) - 86400;
            $dateList[] = [date('Y-m-d', $stime), date('Y-m-d', $etime)];
        }
        return $dateList;

    }

    private static function getOldData($table, $date){
        $sql = "select * from {$table} where date = '{$date}'";
        $oldDatas = oo::commonOprDb(DB_CONN)->getAll($sql,MYSQLI_ASSOC);
        return $oldDatas;
    }

    # 周报，月报
    static function adjustReport($type = 'month'){
        $typePrefix = substr($type, 0, 1);
        $dateList = self::getDateList($type);
        $periodItemsPrefix = ['retained_users','paying_users','revenue_total','paying_user_size'];
        $periodDays = self::getPeriodIdxs($type);
        $periodItems = self::getPeriodItems($type);
        $adjustReportTable = otable::adjustReport($type);
        $dayCnt = 0;
        oo::commonOprDb(DB_CONN)->query("set names utf8mb4");
        foreach ($dateList as $dateArray){
            $insertAdjustData = [];
            $updateAdjustData = [];
            $dayCnt++;
            list($start, $end) = $dateArray;
            oo::logs()->debug3(   "index:$dayCnt:{$start} ~ {$end}:" , 'adjustDataCrontab');
            $dateKey = date('Ymd', strtotime($start)) . '~'.date('Ymd', strtotime($end)) ;

            $params['date_period'] = "{$start}:{$end}";
            $params['dimensions'] = "country_code,network,tracker_token,os_name";
            $params['metrics'] = implode(',',$periodItems);
            $params['attribution_type'] = "click";
            $params['reattributed'] = "false";
            $params['app_token__in'] = APP_TOKEN;
            $url = urldecode(API_URL . http_build_query($params));
            oo::logs()->debug3(  $url , 'adjustDataCrontab');
            $response = funs::curlPost($url, self::$headers, [], 'GET');
            $response = @json_decode($response, true)['rows'] ?? [];
            oo::logs()->debug3(  '记录数：' . count($response) , 'adjustDataCrontab');
            # 查询老数据
            $oldDatas = self::getOldData($adjustReportTable, $dateKey);
            $oldAdjustDataIdMaps = [];
            foreach ($oldDatas as $data){
                $key = "{$data['date']}{$data['countries']}{$data['os_names']}{$data['trackers_channel_token']}";
                $oldAdjustDataIdMaps[$key] = $data['id'];
            }
            $newkips = [0,0,0];
            foreach ($response as $data){
                $key = "{$dateKey}{$data['country_code']}{$data['os_name']}{$data['tracker_token']}";
                $adjustData = [
                    'date' => $dateKey,
                    'countries' => $data['country_code'],
                    'os_names' => $data['os_name'],
                    'trackers_channel_token' => $data['tracker_token'],
                    'trackers_channel_name' => $data['network'],
                    'trackers_group_type' => $data['network'],
                    'kpi_values' => json_encode([$data['daus'], $data['installs'], $data['revenue']],32),
                ];
                $periodData = [];
                foreach ($periodDays as $day){
                    $kips = [];
                    foreach ($periodItemsPrefix as $prefix){
                        $kips[] = $data["{$prefix}_{$typePrefix}{$day}"];
                    }
                    $periodData[$day] = $kips;
                }
                $adjustData['period_values'] = json_encode($periodData);
                if(empty($oldAdjustDataIdMaps[$key])) # 新纪录
                    $insertAdjustData[] = $adjustData;
                else
                    $updateAdjustData[$oldAdjustDataIdMaps[$key]] = $adjustData;
            }
            oo::logs()->debug3(  'insertAdjustData:'.count($insertAdjustData), 'adjustDataCrontab');
            oo::logs()->debug3(  'updateAdjustData:'.count($updateAdjustData), 'adjustDataCrontab');
            if(count($insertAdjustData))
                oo::commonOprDb(DB_CONN)->query(funs::db_intsertArrSQL($adjustReportTable, array_keys($insertAdjustData[0]), $insertAdjustData));

            foreach ($updateAdjustData as $id => $updateItem){
                oo::commonOprDb(DB_CONN)->query(funs::db_updateSQL($adjustReportTable, $updateItem,  ' id='.$id));
            }
            oo::logs()->debug3(  '--------------------------------------------------------------' , 'adjustDataCrontab');
        }
        oo::logs()->debug3(  $dayCnt , 'adjustDataCrontab');
    }
    private static function getPeriodIdxs($type){
        $periodDays = [];
        $max = 0;
        switch ($type){
            case 'week':
                $max = 52;
                break;
            case 'month':
                $max = 13;
                break;
            default:
                return [];
        }
        for ($i=0;$i<=$max;$i++){
            if($type == 'week'){
                if($i > 1 && $i%4)continue;
            }
            $periodDays[] = $i;
        }
        return $periodDays;
    }
    private static function getPeriodItems($type){
        $periodItemsPrefix = ['retained_users','paying_users','revenue_total','paying_user_size'];
        $typePrefix = substr($type, 0, 1);
        $periodDays = self::getPeriodIdxs($type);
        $periodItems = ['daus','installs','revenue'];
        foreach ($periodItemsPrefix as $item){
            foreach ($periodDays as $day){
                $periodItems[] = "{$item}_{$typePrefix}{$day}";
            }
        }
        return $periodItems;
    }

}
oo::logs()->debug3( $hi , 'adjustDataCrontab');
echo time() . PHP_EOL;











