<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Adjuststa extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
        $config = array(
            'savePath' => 'Excel/uploads',             //存储文件夹
            'maxSize' => 1024 * 5,                   //允许的文件最大尺寸，单位KB
            'allowFiles' => array('.xls', '.xlsx')  //允许的文件格式
        );
        $this->load->library('uploader', $config);
        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/PHPExcel/IOFactory');
        $this->load->library('curl');
        foreach ($this->trackTokens as $track => $tokens){
            if (empty($tokens)){
                unset($this->trackTokens[$track]);
            }
        }
    }

    private $fcce = 0.65; // 0.7  => 0.65 分成比例系数
    private $spendCeList = [ // 实际广告话费
        'fb' => 0.92,
        'gg' => 1,
        'tt' => 0.95,
    ];

    public $trackerGroup = [
        "Organic" => ["7cva4i0"],
        "自传播" => ["h1jgpyy", "691f6ju", "5phzybo", "hr6yzec", "m6ir13p", "7m11adf", "rvrse90"],
        "Facebook" => ["te21fd0", "12v8vi0", "wi63kex", "bkgoyy4"],
        "Unity" => ["102g39c6"],
    ];

    public $trackTokens = [
        "Organic" => ["7cva4i0"],
        "自传播" => ["h1jgpyy", "691f6ju", "5phzybo", "hr6yzec", "m6ir13p", "7m11adf", "rvrse90"],
        "Facebook" => ["te21fd0", "12v8vi0", "wi63kex", "bkgoyy4"],

        '游戏内召回' => [
        ],
        '社媒KOL' => [
        ],
        '各平台主页渠道' => [
        ],
        '邮件营销' => [
        ],
        'Google_ads' => ['mds7ggs'],
        "Unity" => ["102g39c6"],
        '苹果商店页搜索广告' => [
        ],
        'Applovin' => [
        ],
        'IronSource' => [
        ],
        'Chartboost' => [
        ],
        'Mintegral' => [
        ],
        'Vungle' => [
        ],

        //网盟--begin
        '网盟-Inplayable' => [
        ],
        '网盟-Linkme' => [
        ],
        '网盟-Tecdo' => [
        ],
        '网盟-Virgrilmedia' => [
        ],
        '网盟-Youmi' => [
        ],
        '网盟-Adinall' => [
        ],
        '网盟-Chestnut' => [
        ],
        '网盟-Nativex' => [
        ],
        '网盟-Autumnant' => [
        ],
        '网盟-Coinads' => [
        ],
        '网盟-Gemmob' => [
        ],
        //网盟--end
        'TikTok' => [
        ],
        '联运-VIVO' => [
        ],
        '联运-OPPO' => [
        ],
    ];

    public $postData = array('frombg' => 1, 'mod' => '', 'act' => '', 'lid' => 1, 'sid' => 1);

    public $extensionList = [
        'Facebook',
        'Google_ads',
        'IronSource',
        'Unity',
        'Applovin',
        'Vungle',
        'Chartboost'
        ,'Mintegral'
        ,'TikTok'
        ,'苹果商店页搜索广告'

        ,'网盟-Inplayable'
        ,'网盟-Linkme'
        ,'网盟-Tecdo'
        ,'网盟-Virgrilmedia'
        ,'网盟-Youmi'
        ,'网盟-Adinall'
        ,'网盟-Chestnut'
        ,'网盟-Nativex'
        ,'网盟-Autumnant'
        ,'网盟-Coinads'
        ,'网盟-Gemmob'

    ];

    public $网盟CPI = [
        'Inplayable' => 1,
        'Linkme' => 1,
        'Tecdo' => 1,
        'Virgrilmedia' => 1,
        'Youmi' => 1,
        'Adinall' => 1,
        'Chestnut' => 1,
        'Nativex' => 1,
        'Autumnant' => 1,
        'Coinads' => 1,
        'Gemmob' => 1,
    ];
    public $adUsers = [
        'Cindy'
        ,'Winnie'
        ,'Ada'
        ,'Yvette'
        ,'Lulu'
        ,'JJY'
    ];
    public $paymentChannels = [
         'Facebook'
        ,'Google_ads'
        ,'苹果商店页搜索广告'
        ,'Unity'
        ,'Applovin'
        ,'IronSource'
        ,'Chartboost'
        ,'Mintegral'
        ,'Vungle'
        ,'TikTok'
//        ,'Prodege'
//        ,'AdAction'
//        ,'Mistplay'

//        ,'Virgrilmedia'
//        ,'Linkme'
    ];
    public function base($objPHPExcel,$outPutFileName){
        // 设置第一个sheet为工作的sheet
        $objPHPExcel->setActiveSheetIndex(0);

        header('Content-Type: applicationnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$outPutFileName.'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }

    //Adjust日报
    public function dayReport($type = 'day'){
        $stime = get_cookie('stime') ?? date("Y-m-d",strtotime("-7 days 0:0:0"));
        $etime = get_cookie('etime') ?? date("Y-m-d",strtotime("-1 days 0:0:0"));
        $address = get_cookie('address') ?? '';//国家
        $trackers_group_type = get_cookie('trackers_group_type') ?? '';//广告渠道
        $user_os = get_cookie('user_os') ?? '';//版本
        $data = [];
        //adjust数据 细到广告ID层
        $ajustPeriodDataTb = otable::ajustPeriodData();
        $where = '';
        if($trackers_group_type){
            $where .= " AND trackers_group_type = '{$trackers_group_type}'";
        }
        $sdate = date("Y-m-d H:i:s",strtotime($stime . " 0:0:0"));
        $edate = date("Y-m-d H:i:s",strtotime($etime . " 0:0:0"));
        $sql = "SELECT * FROM {$ajustPeriodDataTb} WHERE date >= '{$sdate}' AND date <= '{$edate}' {$where}";
        $ajustPeriodData = oo::commonOprDb('report')->getAll($sql,1);

        //广告分组数据 细到广告分组层
        $facebookAdsetTb = otable::facebookAdset();
        $where = '';
        if($user_os){
            $where .= " AND user_os = '{$user_os}'";
        }
        if($address && $address != 'all'){
            $where .= " AND countries LIKE '%{$address}%'";
        }
        $sql = "SELECT * FROM {$facebookAdsetTb} WHERE date_start >= '{$stime}' AND date_start <= '{$etime}' {$where}";
        $facebookAdsetData = oo::commonOprDb('report')->getAll($sql,1);
        $adset = [];
        foreach($facebookAdsetData as $row){
            $date = date("Ymd", strtotime($row['date_start']));
            $adset[$date][$row['id']] = $row;
        }

        //广告成本数据（广告详情表）
        $facebookAdsTb = otable::facebookAds();
        $where = '';
        if($address && $address != 'all'){
            $where .= " AND country = '{$address}'";
        }
        $sql = "SELECT * FROM {$facebookAdsTb} WHERE date_start >= '{$stime}' AND date_start <= '{$etime}' {$where}";
        $facebookAdsData = oo::commonOprDb('report')->getAll($sql,1);
        $ads = [];
        foreach($facebookAdsData as $row){
            $adset_id = $row['adset_id'];
            $date = date("Ymd", strtotime($row['date_start']));
            if(!in_array($row['country'],$ads[$date][$adset_id]['country']??[])){
                $ads[$date][$adset_id]['country'][] = $row['country'];
            }
            if(!in_array($row['country'],$ads[$date][$adset_id]['country'])){
                $ads[$date][$adset_id]['country'][] = $row['country'];
            }
            foreach(['clicks','impressions','inline_link_clicks','reach','spend','cpc','link_click','mobile_app_install','three_sec_video_view',
                        'video_play_actions','video_avg_time_watched_actions','video_p25_watched_actions','video_p50_watched_actions',
                        'video_p75_watched_actions','video_p95_watched_actions','video_p100_watched_actions'] as $key){
                $ads[$date][$adset_id][$key] += $row[$key];
            }
        }

        $dateTemp = [];
        for($i=0;$i<=$this->diffBetweenTwoDays($stime,$etime);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $list = [];
        //按照 日期、国家、广告渠道分组聚合
        foreach($ajustPeriodData as $row){
            $adgroups_id = $row['adgroups_id'];
            $temp = [];
            $temp['date'] = date("Ymd",strtotime($row['date']));
            $temp['user_os'] = $adset[$temp['date']][$adgroups_id]['user_os'];//版本
            $temp['countries'] = $adset[$temp['date']][$adgroups_id]['countries'];
            $temp['country'] = $ads[$temp['date']][$adgroups_id]['country'];
            $temp['trackers_group_type'] = $row['trackers_group_type'];//渠道
            if($address == "all"){
                $tempAddress = "all";
            }else{
                $tempAddress = $temp['countries'] ?? (is_array($temp['country'])?(implode(",",$temp['country'])):$temp['country']);//国家
            }

            if($address && $tempAddress != $address){
                continue;
            }
            if($user_os && $temp['user_os'] != $user_os){
                continue;
            }
            foreach([0,1,2,6,14,29,59,89,119] as $num){
                $temp["period_{$num}_kpis"] = json_decode($row["period_{$num}_kpis"],1);
            }
            $temp['spend'] = $ads[$temp['date']][$adgroups_id]['spend'];//广告成本
            $temp['dau'] = $temp['period_0_kpis'][1] ?? 0;//DAU
            $temp['install'] = $temp['period_0_kpis'][0] ?? 0;//安装量
            if( in_array($type,["month","ltv"]) ){
                $temp['date'] = date("Ym",strtotime($temp["date"]));
            }else if($type == "week"){
                $temp['date'] = $this->getWeekDate($temp['date']);
            }
            if(isset($list[$temp['date']][$temp['user_os']][$tempAddress][$temp['trackers_group_type']])){
                $temp['dau'] += ($list[$temp['date']][$temp['user_os']][$tempAddress][$temp['trackers_group_type']]['dau']);//DAU
                $temp['install'] += ($list[$temp['date']][$temp['user_os']][$tempAddress][$temp['trackers_group_type']]['install']);//安装量
                $temp['spend'] += ($list[$temp['date']][$temp['user_os']][$tempAddress][$temp['trackers_group_type']]['spend']);//广告成本
                foreach([0,1,2,6,14,29,59,89,119] as $num){
                    $tempAdvert = ($temp["period_{$num}_kpis"][0] * $temp["period_{$num}_kpis"][5] - $temp["period_{$num}_kpis"][4]);
                    $temp["advert_{$num}"] = $tempAdvert < 0 ? 0 :$tempAdvert;//广告收入
                    foreach($temp["period_{$num}_kpis"] ?? [] as $k => $v){
                        $temp["period_{$num}_kpis"][$k] += ($list[$temp['date']][$temp['user_os']][$tempAddress][$temp['trackers_group_type']]["period_{$num}_kpis"][$k]);
                    }
                    $temp["advert_{$num}"] += ($list[$temp['date']][$temp['user_os']][$tempAddress][$temp['trackers_group_type']]["advert_{$num}"]);//广告收入
                }
            }else{
                foreach([0,1,2,6,14,29,59,89,119] as $num) {
                    $tempAdvert = ($temp["period_{$num}_kpis"][0] * $temp["period_{$num}_kpis"][5] - $temp["period_{$num}_kpis"][4]);
                    $temp["advert_{$num}"] = $tempAdvert < 0 ? 0 :$tempAdvert;//广告收入
                }
            }
            $list[$temp['date']][$temp['user_os']][$tempAddress][$temp['trackers_group_type']] = $temp;
        }
        $data['list'] = $list;
        $data['stime'] = $stime;
        $data['etime'] = $etime;
        $data['user_os'] = $user_os;
        $data['trackers_group_type'] = $trackers_group_type;
        $data['address'] = $address;
        $data['date'] = $dateTemp;
        $data['type'] = $type;

        //标题名称
        $data["title"] = "Adjust日报";
        if($type == "month"){
            $data["title"] = "Adjust月报";
            $this->load->view('report/dayReport', $data);
        }else if($type == "week"){
            $data["title"] = "Adjust周报";
            $this->load->view('report/dayReport', $data);
        }else if($type == "ltv"){
            $data["title"] = "ltv月报";
            $this->load->view('report/ltvReport', $data);
        }else if($type == "day"){
            $this->load->view('report/dayReport', $data);
        }
    }

    //Adjust日报明细
    public function dayReportView($page = 0){
        $stime = get_cookie('stime') ?? date("Y-m-d",strtotime("-7 days 0:0:0"));
        $etime = get_cookie('etime') ?? date("Y-m-d",strtotime("-1 days 0:0:0"));
        $address = get_cookie('address') ?? '';//国家
        $trackers_group_type = get_cookie('trackers_group_type') ?? '';//广告渠道
        $user_os = get_cookie('user_os') ?? '';//版本
        $campaigns_name = get_cookie('campaigns_name') ?? '';//广告系列
        $adgroups_name = get_cookie('adgroups_name') ?? '';//广告组
        $creatives_name = get_cookie('creatives_name') ?? '';//广告
        $data = [];
        //adjust数据 细到广告ID层
        $ajustPeriodDataTb = otable::ajustPeriodData();
        $where = '';
        if($trackers_group_type){
            $where .= " AND trackers_group_type = '{$trackers_group_type}'";
        }
        if($adgroups_name){
            $where .= " AND adgroups_name = '{$adgroups_name}'";
        }
        if($campaigns_name){
            $where .= " AND campaigns_name = '{$campaigns_name}'";
        }
        if($creatives_name){
            $where .= " AND creatives_name = '{$creatives_name}'";
        }
        $sdate = date("Y-m-d H:i:s",strtotime($stime . " 0:0:0"));
        $edate = date("Y-m-d H:i:s",strtotime($etime . " 0:0:0"));
        $sql = "SELECT * FROM {$ajustPeriodDataTb} WHERE date >= '{$sdate}' AND date <= '{$edate}' {$where}";
        $ajustPeriodData = oo::commonOprDb('report')->getAll($sql,1);

        //广告分组数据 细到广告分组层
        $facebookAdsetTb = otable::facebookAdset();
        $where = '';
        if($user_os){
            $where .= " AND user_os = '{$user_os}'";
        }
        if($address){
            $where .= " AND countries LIKE '%{$address}%'";
        }
        $sql = "SELECT * FROM {$facebookAdsetTb} WHERE date_start >= '{$stime}' AND date_start <= '{$etime}' {$where}";
        $facebookAdsetData = oo::commonOprDb('report')->getAll($sql,1);
        $adset = [];
        foreach($facebookAdsetData as $row){
            $date = date("Ymd", strtotime($row['date_start']));
            $adset[$date][$row['id']] = $row;
        }

        //广告成本数据（广告详情表）
        $facebookAdsTb = otable::facebookAds();
        $where = '';
        if($address){
            $where .= " AND country = '{$address}'";
        }
        $sql = "SELECT * FROM {$facebookAdsTb} WHERE date_start >= '{$stime}' AND date_start <= '{$etime}' {$where}";
        $facebookAdsData = oo::commonOprDb('report')->getAll($sql,1);
        $ads = [];
        foreach($facebookAdsData as $row){
            $adset_id = $row['adset_id'];
            $ad_id = $row['ad_id'];
            $date = date("Ymd", strtotime($row['date_start']));
            if(!in_array($row['country'],$ads[$date][$ad_id]['country']??[])){
                $ads[$date][$ad_id]['country'][] = $row['country'];
            }
            if(!in_array($row['country'],$ads[$date][$ad_id]['country'])){
                $ads[$date][$ad_id]['country'][] = $row['country'];
            }
            foreach(['clicks','impressions','inline_link_clicks','reach','spend','cpc','link_click','mobile_app_install','three_sec_video_view',
                        'video_play_actions','video_avg_time_watched_actions','video_p25_watched_actions','video_p50_watched_actions',
                        'video_p75_watched_actions','video_p95_watched_actions','video_p100_watched_actions'] as $key){
                $ads[$date][$ad_id][$key] += $row[$key];
            }
        }

        $dateTemp = [];
        for($i=0;$i<=$this->diffBetweenTwoDays($stime,$etime);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $list = [];
        //按照 日期、国家、广告渠道分组聚合
        foreach($ajustPeriodData as $row){
            $adgroups_id = $row['adgroups_id'];
            $creatives_id = $row['creatives_id'];
            $temp = [];
            $temp['date'] = date("Ymd",strtotime($row['date']));
            $temp['user_os'] = $adset[$temp['date']][$adgroups_id]['user_os'];//版本
            $temp['countries'] = $adset[$temp['date']][$adgroups_id]['countries'];
            $temp['country'] = $ads[$temp['date']][$creatives_id]['country'];
            $temp['trackers_group_type'] = $row['trackers_group_type'];//渠道
            $temp['campaigns_name'] = $row['campaigns_name'];//广告系列
            $temp['adgroups_name'] = $row['adgroups_name'];//广告组名
            $temp['creatives_name'] = $row['creatives_name'];//广告名
            $temp['address'] = empty($temp['country']) ? $temp['countries'] : implode(",",$temp['country']);//国家
            if($address && $temp['address'] != $address){
                continue;
            }
            if($user_os && $temp['user_os'] != $user_os){
                continue;
            }
            foreach([0,1,2,6,14,29,59,89,119] as $num){
                $temp["period_{$num}_kpis"] = json_decode($row["period_{$num}_kpis"],1);
            }
            $temp['spend'] = $ads[$temp['date']][$creatives_id]['spend'];//广告成本
            $temp['dau'] = $temp['period_0_kpis'][1] ?? 0;//DAU
            $temp['install'] = $temp['period_0_kpis'][0] ?? 0;//安装量
            $list[] = $temp;
        }

        $data['list'] = array_slice($list,$page,10);
        $data['stime'] = $stime;
        $data['etime'] = $etime;
        $data['user_os'] = $user_os;
        $data['trackers_group_type'] = $trackers_group_type;
        $data['campaigns_name'] = $campaigns_name;
        $data['adgroups_name'] = $adgroups_name;
        $data['creatives_name'] = $creatives_name;
        $data['address'] = $address;
        $data['date'] = $dateTemp;

        //分页
        $data['total'] = count($list);
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#adjuststa/dayReportView');
        $pageConfig['total_rows'] = $data['total'];
        $pageConfig['per_page'] = 10;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;
        $data['page'] = $page;

        $this->load->view('report/dayReportView', $data);
    }

    //FB素材成效数据
    public function facebookAds($page = 0){
        $stime = get_cookie('stime') ?? date("Y-m-d",strtotime("-7 days 0:0:0"));
        $etime = get_cookie('etime') ?? date("Y-m-d",strtotime("-1 days 0:0:0"));
        $address = get_cookie('address') ?? '';//国家
        $trackers_group_type = get_cookie('trackers_group_type') ?? '';//广告渠道
        $user_os = get_cookie('user_os') ?? '';//版本
        $campaigns_name = get_cookie('campaigns_name') ?? '';//广告系列
        $adgroups_name = get_cookie('adgroups_name') ?? '';//广告组
        $creatives_name = get_cookie('creatives_name') ?? '';//广告
        $data = [];
        //adjust数据 细到广告ID层
        $ajustPeriodDataTb = otable::ajustPeriodData();
        $where = '';
        if($trackers_group_type){
            $where .= " AND trackers_group_type = '{$trackers_group_type}'";
        }
        if($adgroups_name){
            $where .= " AND adgroups_name = '{$adgroups_name}'";
        }
        if($campaigns_name){
            $where .= " AND campaigns_name = '{$campaigns_name}'";
        }
        if($creatives_name){
            $where .= " AND creatives_name = '{$creatives_name}'";
        }
        $sdate = date("Y-m-d H:i:s",strtotime($stime . " 0:0:0"));
        $edate = date("Y-m-d H:i:s",strtotime($etime . " 0:0:0"));
        $sql = "SELECT * FROM {$ajustPeriodDataTb} WHERE date >= '{$sdate}' AND date <= '{$edate}' {$where}";
        $ajustPeriodData = oo::commonOprDb('report')->getAll($sql,1);

        //广告分组数据 细到广告分组层
        $facebookAdsetTb = otable::facebookAdset();
        $where = '';
        if($user_os){
            $where .= " AND user_os = '{$user_os}'";
        }
        if($address){
            $where .= " AND countries LIKE '%{$address}%'";
        }
        $sql = "SELECT * FROM {$facebookAdsetTb} WHERE date_start >= '{$stime}' AND date_start <= '{$etime}' {$where}";
        $facebookAdsetData = oo::commonOprDb('report')->getAll($sql,1);
        $adset = [];
        foreach($facebookAdsetData as $row){
            $date = date("Ymd", strtotime($row['date_start']));
            $adset[$date][$row['id']] = $row;
        }

        //广告成本数据（广告详情表）
        $facebookAdsTb = otable::facebookAds();
        $where = '';
        if($address){
            $where .= " AND country = '{$address}'";
        }
        $sql = "SELECT * FROM {$facebookAdsTb} WHERE date_start >= '{$stime}' AND date_start <= '{$etime}' {$where}";
        $facebookAdsData = oo::commonOprDb('report')->getAll($sql,1);
        $ads = [];
        foreach($facebookAdsData as $row){
            $adset_id = $row['adset_id'];
            $ad_id = $row['ad_id'];
            $date = date("Ymd", strtotime($row['date_start']));
            if(!in_array($row['country'],$ads[$date][$ad_id]['country']??[])){
                $ads[$date][$ad_id]['country'][] = $row['country'];
            }
            if(!in_array($row['country'],$ads[$date][$ad_id]['country'])){
                $ads[$date][$ad_id]['country'][] = $row['country'];
            }
            foreach(['clicks','impressions','inline_link_clicks','reach','spend','cpc','link_click','mobile_app_install','three_sec_video_view',
                        'video_play_actions','video_avg_time_watched_actions','video_p25_watched_actions','video_p50_watched_actions',
                        'video_p75_watched_actions','video_p95_watched_actions','video_p100_watched_actions'] as $key){
                $ads[$date][$ad_id][$key] += $row[$key];
            }
        }

        $dateTemp = [];
        for($i=0;$i<=$this->diffBetweenTwoDays($stime,$etime);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $list = [];
        //按照 日期、国家、广告渠道分组聚合
        foreach($ajustPeriodData as $row){
            $adgroups_id = $row['adgroups_id'];
            $creatives_id = $row['creatives_id'];
            $temp = [];
            $temp['date'] = date("Ymd",strtotime($row['date']));
            $temp['user_os'] = $adset[$temp['date']][$adgroups_id]['user_os'];//版本
            $temp['countries'] = $adset[$temp['date']][$adgroups_id]['countries'];
            $temp['country'] = $ads[$temp['date']][$creatives_id]['country'];
            $temp['trackers_group_type'] = $row['trackers_group_type'];//渠道
            $temp['campaigns_name'] = $row['campaigns_name'];//广告系列
            $temp['adgroups_name'] = $row['adgroups_name'];//广告组名
            $temp['creatives_name'] = $row['creatives_name'];//广告名
            $temp['address'] = empty($temp['country']) ? $temp['countries'] : implode(",",$temp['country']);//国家
            $temp['clicks'] = $ads[$temp['date']][$creatives_id]['clicks'];//点击次数
            $temp['impressions'] = $ads[$temp['date']][$creatives_id]['impressions'];//展示次数
            $temp['inline_link_clicks'] = $ads[$temp['date']][$creatives_id]['inline_link_clicks'];//链接点击次数
            $temp['reach'] = $ads[$temp['date']][$creatives_id]['reach'];//展示次数
            $temp['video_avg_time_watched_actions'] = $ads[$temp['date']][$creatives_id]['video_avg_time_watched_actions'];//视频平均观看时长(秒)
            $temp['video_play_actions'] = $ads[$temp['date']][$creatives_id]['video_play_actions'];//视频观看总次数
            $temp['three_sec_video_view'] = $ads[$temp['date']][$creatives_id]['three_sec_video_view'];//actions内观看3秒视频次数
            $temp['video_p25_watched_actions'] = $ads[$temp['date']][$creatives_id]['video_p25_watched_actions'];//观看视频25%的人数
            $temp['video_p50_watched_actions'] = $ads[$temp['date']][$creatives_id]['video_p50_watched_actions'];//观看视频50%的人数
            $temp['video_p75_watched_actions'] = $ads[$temp['date']][$creatives_id]['video_p75_watched_actions'];//观看视频75%的人数
            $temp['video_p95_watched_actions'] = $ads[$temp['date']][$creatives_id]['video_p95_watched_actions'];//观看视频95%的人数
            $temp['video_p100_watched_actions'] = $ads[$temp['date']][$creatives_id]['video_p100_watched_actions'];//观看视频100%的人数
            if($address && $temp['address'] != $address){
                continue;
            }
            if($user_os && $temp['user_os'] != $user_os){
                continue;
            }
            foreach([0,1,2,6,14,29,59,89,119] as $num){
                $temp["period_{$num}_kpis"] = json_decode($row["period_{$num}_kpis"],1);
            }
            $temp['spend'] = $ads[$temp['date']][$creatives_id]['spend'];//广告成本
            $temp['dau'] = $temp['period_0_kpis'][1] ?? 0;//DAU
            $temp['install'] = $temp['period_0_kpis'][0] ?? 0;//安装量
            $list[] = $temp;
        }

        $data['list'] = array_slice($list,$page,10);
        $data['stime'] = $stime;
        $data['etime'] = $etime;
        $data['user_os'] = $user_os;
        $data['trackers_group_type'] = $trackers_group_type;
        $data['campaigns_name'] = $campaigns_name;
        $data['adgroups_name'] = $adgroups_name;
        $data['creatives_name'] = $creatives_name;
        $data['address'] = $address;
        $data['date'] = $dateTemp;

        //分页
        $data['total'] = count($list);
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#adjuststa/facebookAds');
        $pageConfig['total_rows'] = $data['total'];
        $pageConfig['per_page'] = 10;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;
        $data['page'] = $page;

        $this->load->view('report/facebookAds', $data);
    }

    //登陆注册回头率
    public function returnRate(){

        $this->load->view('report/returnRate', $data);
    }

    //每日支付数据
    public function dayPayData($page = 0){
        $stime = get_cookie('stime') ?? date("Y-m-d",strtotime("-7 days 0:0:0"));
        $etime = get_cookie('etime') ?? date("Y-m-d",strtotime("-1 days 0:0:0"));
        $address = strtolower(get_cookie('address')) ?? '';//国家
        $trackers_group_type = get_cookie('trackers_group_type') ?? '';//广告渠道
        $user_os = get_cookie('user_os') ?? '';//版本
        $data = [];
        //adjust数据 细到广告ID层
        $ajustPeriodDataTb = otable::ajustPeriodData();
        $where = '';
        if($trackers_group_type){
            $where .= " AND trackers_group_type = '{$trackers_group_type}'";
        }
        $sdate = date("Y-m-d H:i:s",strtotime($stime . " 0:0:0"));
        $edate = date("Y-m-d H:i:s",strtotime($etime . " 0:0:0"));
        $sql = "SELECT * FROM {$ajustPeriodDataTb} WHERE date >= '{$sdate}' AND date <= '{$edate}' {$where}";
        $ajustPeriodData = oo::commonOprDb('report')->getAll($sql,1);

        //广告分组数据 细到广告分组层
        $facebookAdsetTb = otable::facebookAdset();
        $where = '';
        if($user_os){
            $where .= " AND user_os = '{$user_os}'";
        }
        if($address){
            $where .= " AND countries LIKE '%{$address}%'";
        }
        $sql = "SELECT * FROM {$facebookAdsetTb} WHERE date_start >= '{$stime}' AND date_start <= '{$etime}' {$where}";
        $facebookAdsetData = oo::commonOprDb('report')->getAll($sql,1);
        $adset = [];
        foreach($facebookAdsetData as $row){
            $date = date("Ymd", strtotime($row['date_start']));
            $adset[$date][$row['id']] = $row;
        }

        //广告成本数据（广告详情表）
        $facebookAdsTb = otable::facebookAds();
        $where = '';
        if($address){
            $where .= " AND country = '{$address}'";
        }
        $sql = "SELECT * FROM {$facebookAdsTb} WHERE date_start >= '{$stime}' AND date_start <= '{$etime}' {$where}";
        $facebookAdsData = oo::commonOprDb('report')->getAll($sql,1);
        $ads = [];
        foreach($facebookAdsData as $row){
            $adset_id = $row['adset_id'];
            $date = date("Ymd", strtotime($row['date_start']));
            if(!in_array($row['country'],$ads[$date][$adset_id]['country']??[])){
                $ads[$date][$adset_id]['country'][] = $row['country'];
            }
            if(!in_array($row['country'],$ads[$date][$adset_id]['country'])){
                $ads[$date][$adset_id]['country'][] = $row['country'];
            }
            foreach(['clicks','impressions','inline_link_clicks','reach','spend','cpc','link_click','mobile_app_install','three_sec_video_view',
                        'video_play_actions','video_avg_time_watched_actions','video_p25_watched_actions','video_p50_watched_actions',
                        'video_p75_watched_actions','video_p95_watched_actions','video_p100_watched_actions'] as $key){
                $ads[$date][$adset_id][$key] += $row[$key];
            }
        }

        $dateTemp = [];
        for($i=0;$i<=$this->diffBetweenTwoDays($stime,$etime);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }
        $list = [];
        //按照 日期、国家、广告渠道分组聚合
        foreach($ajustPeriodData as $row){
            $adgroups_id = $row['adgroups_id'];
            $temp = [];
            $temp['date'] = date("Ymd",strtotime($row['date']));
            $temp['user_os'] = $adset[$temp['date']][$adgroups_id]['user_os'];//版本
            $temp['countries'] = $adset[$temp['date']][$adgroups_id]['countries'];
            $temp['country'] = $ads[$temp['date']][$adgroups_id]['country'];
            $temp['trackers_group_type'] = $row['trackers_group_type'];//渠道
            $tempAddress = $temp['countries'] ?? (is_array($temp['country'])?(implode(",",$temp['country'])):$temp['country']);//国家
            if($address && $tempAddress != $address){
                continue;
            }
            if($user_os && $temp['user_os'] != $user_os){
                continue;
            }
            foreach([0,1,2,6,14,29,59,89,119] as $num){
                $temp["period_{$num}_kpis"] = json_decode($row["period_{$num}_kpis"],1);
            }
            $temp['spend'] = $ads[$temp['date']][$adgroups_id]['spend'];//广告成本
            $temp['dau'] = $temp['period_0_kpis'][1] ?? 0;//DAU
            $temp['install'] = $temp['period_0_kpis'][0] ?? 0;//安装量
            if( in_array($type,["month","ltv"]) ){
                $temp['date'] = date("Ym",strtotime($temp["date"]));
            }else if($type == "week"){
                $temp['date'] = $this->getWeekDate($temp['date']);
            }
            if(isset($list[$temp['date']][$temp['user_os']][$tempAddress][$temp['trackers_group_type']])){
                $temp['dau'] += ($list[$temp['date']][$temp['user_os']][$tempAddress][$temp['trackers_group_type']]['dau']);//DAU
                $temp['install'] += ($list[$temp['date']][$temp['user_os']][$tempAddress][$temp['trackers_group_type']]['install']);//安装量
                $temp['spend'] += ($list[$temp['date']][$temp['user_os']][$tempAddress][$temp['trackers_group_type']]['spend']);//广告成本
                foreach([0,1,2,6,14,29,59,89,119] as $num){
                    $tempAdvert = ($temp["period_{$num}_kpis"][0] * $temp["period_{$num}_kpis"][5] - $temp["period_{$num}_kpis"][4]);
                    $temp["advert_{$num}"] = $tempAdvert < 0 ? 0 :$tempAdvert;//广告收入
                    foreach($temp["period_{$num}_kpis"] ?? [] as $k => $v){
                        $temp["period_{$num}_kpis"][$k] += ($list[$temp['date']][$temp['user_os']][$tempAddress][$temp['trackers_group_type']]["period_{$num}_kpis"][$k]);
                    }
                    $temp["advert_{$num}"] += ($list[$temp['date']][$temp['user_os']][$tempAddress][$temp['trackers_group_type']]["advert_{$num}"]);//广告收入
                }
            }else{
                foreach([0,1,2,6,14,29,59,89,119] as $num) {
                    $tempAdvert = ($temp["period_{$num}_kpis"][0] * $temp["period_{$num}_kpis"][5] - $temp["period_{$num}_kpis"][4]);
                    $temp["advert_{$num}"] = $tempAdvert < 0 ? 0 :$tempAdvert;//广告收入
                }
            }
            $list[$temp['date']][$temp['user_os']][$tempAddress][$temp['trackers_group_type']] = $temp;
        }
        $data['list'] = $list;
        $data['stime'] = $stime;
        $data['etime'] = $etime;
        $data['user_os'] = $user_os;
        $data['trackers_group_type'] = $trackers_group_type;
        $data['address'] = $address;
        $data['date'] = $dateTemp;
        $data['type'] = $type;

        $this->load->view('report/dayPayData', $data);
    }

    public function exportAdjustReportCli(){
        if(PHP_SAPI != 'cli')return;
        set_time_limit(0);
        ini_set('max_execution_time', '0');
        ini_set('memory_limit', -1);
        $stime = '2022-01-01';
        $etime = '2022-12-31';
        $etime = '2022-01-01';
        $type = 'day';
        $trackers_group_type = 'all';
        $showList = [0,2,6,14,29];
        $periodList = [0,1,2,6,14,29,59,89,119];

        $header = $this->getAdjustThead($type);
        $header = array_combine($header, $header);

        $list = $this->getAdjustData($stime,$etime,$type,'all','all','all',$this->extensionList,$periodList);

        $rows = [];
        $validSpend = 0;
        foreach($list as $date => $countryMap) {
            if($type == 'day') $date = date('Ymd', strtotime($date));
            $rows[$date] = [];
            foreach ($countryMap as $country => $osMap) {
                foreach ($osMap as $os => $channelMap) {
                    foreach ($channelMap as $channel => $row) {
                        $extensionRemain = $row["extensionRemain"];//推广

                        $extension = $row["extension"] ;

                        $naturalRemain = $row["period_1_kpis"][0] - $row["extensionRemain"];//自然
                        $natural = $row["kpi_values"][1] - $row["extension"];

                        $naturalRate = number_format(($natural / $row["kpi_values"][1]) * 100, 2);

                        $tmp = [
                            '日期' => $date,
                            '国家' => $country,
                            '版本' => $os,
                            '广告渠道' => $channel,
                            'DAU' => round($row["kpi_values"][0]) ?? 0,
                            '花费$' => number_format($row["spend"],2,".","") ?? 0,
                            '总安装' => $row["kpi_values"][1] ?? 0,
                            '推广安装' => $extension,
                            '自然量安装' => $natural,
                            '自然量占比' => $naturalRate . '%',
                            '买量CPI$' => empty($extension) ? '' : number_format($row["spend"] / $extension,2,".","") ?? "",
                            '均价CPI$' => empty($row["kpi_values"][1]) ? '' : number_format($row["spend"] / $row["kpi_values"][1],2,".","") ?? "",
                            '推广次留' => empty($extension) ? '' : number_format($extensionRemain / $extension * 100,2,".","")."%" ?? '',
                            '自然量次留' => empty($natural) ? '' : number_format($naturalRemain / $natural * 100,2,".","")."%" ?? '',

                        ];
                        $日留存7 = empty($row["kpi_values"][1]) ? 0 :$row["period_6_kpis"][0] / $row["kpi_values"][1];
                        $roi7 = empty($row["spend"]) ? 0 :$row["period_6_kpis"][2] * $this->fcce / $row["spend"];
                        foreach ($showList as $time){
                            if($time == 0)$time = 1;
                            $key = $time == 1 ? '次留' : intval($time+1) .'日留存';
                            $tmp[$key] = empty($row["kpi_values"][1]) ? '' : number_format($row["period_{$time}_kpis"][0] / $row["kpi_values"][1] * 100,2,".","")."%" ?? '';

                            $key = $time == 1 ? '次留人数' : intval($time+1) .'日留存人数';
                            $tmp[$key] = intval($row["period_{$time}_kpis"][0]);
                        }
                        $tmp['付费人数'] = $row["period_0_kpis"][1] ?? 0;;
                        $tmp['付费率'] = empty($row["kpi_values"][1]) ? '' : number_format($row["period_0_kpis"][1] / $row["kpi_values"][1] * 100,2,".","")."%" ?? '';;
                        $tmp['当日ARPU'] = empty($row["kpi_values"][1]) ? '' : number_format($row["period_0_kpis"][2] / $row["kpi_values"][1],2,".","") ?? '';;
                        $tmp['当日ARPPU'] = empty($row["period_0_kpis"][1]) ? '' : number_format($row["period_0_kpis"][2] / $row["period_0_kpis"][1],2,".","") ?? '';;
                        foreach ($showList as $time){
                            $key = empty($time) ? '首日内购ROI' : intval($time+1) .'日内购ROI';
                            $tmp[$key] = empty($row["spend"]) ? '' : number_format($row["period_{$time}_kpis"][2] * $this->fcce / $row["spend"] * 100,2,".","")."%" ?? '';
                        }
                        $tmp['内购收入'] =     number_format($row["kpi_values"][2],2,".","") ?? 0; ;
                        $tmp['分成后总收入'] = number_format($row["kpi_values"][2] * $this->fcce,2,".","") ?? 0;;
                        foreach ($showList as $time){
                            $key = empty($time) ? '首日内购收入' : intval($time + 1) .'日内购收入';
                            $tmp[$key] = number_format($row["period_{$time}_kpis"][2],2,".","") ?? 0;
                        }
                        $tmp['推广次留用户数'] = $extensionRemain;
                        $tmp['自然次留用户数'] = $naturalRemain;
                        $tmp['AE']  = $this->getAE($日留存7, $roi7);
                        $tmp['AEA'] = number_format($this->getAE($日留存7, $roi7) * $row["spend"], 2, '.', '');
                        if(in_array($trackers_group_type,['Tecdo','Inplayable'])){
                            $tmp['花费$'] = $tmp['总安装'] * 3;
                        }
                        $ce = $this->getCE($tmp['AE']);
                        $validSpend += $ce * $tmp['花费$'];
                        $tmp['有效投放金额(累计)'] = number_format($validSpend, 2, '.','');
                        $tmp['合格系数'] = $ce;
                        $rows[$date] = $tmp;
                    }
                }
            }
        }
        unset($list);
        $this->exportDataCli($header, $rows, 'exportdata-2022');
    }
    public function dayReport2($type = "day",$sort = "ASC"){
        if($type != 'day')return $this->adjustReport($type, $sort);
        set_time_limit(0);
        $stime = get_cookie('stime') ?? date("Y-m-d",strtotime("-7 days 0:0:0"));
        $etime = get_cookie('etime') ?? date("Y-m-d",strtotime("-1 days 0:0:0"));
        $address = get_cookie('address') ?? 'all';//国家
        if(strpos($address,',') !== false && strpos($address,'all') === false){
            $address = explode(",",$address);
        }else if(strpos($address,',') !== false && strpos($address,'all') !== false){
            $address = "all";
        }

        $trackers_group_type = get_cookie('trackers_group_type') ?? 'all';//广告渠道
        $user_os = get_cookie('user_os') ?? 'all';//版本
        $extensionList = $this->extensionList;//推广渠道
        $periodList = [0,1,2,6,14,29,59,89,119];

        $data["title"] = "Adjust日报";
        $showList = [0,2,6,14,29];
        if($type == "week"){
            $data["title"] = "Adjust周报";
            $showList = array_merge($showList,[59,89,119]);
        }else if($type == "month"){
            $data["title"] = "Adjust月报";
            $showList = array_merge($showList,[59,89,119]);
        }
        $list = $this->getAdjustData($stime,$etime,$type,$address,$trackers_group_type,$user_os,$extensionList,$periodList);

        $rows = [];
        $validSpend = 0;
        foreach($list as $date => $countryMap) {
            if($type == 'day') $date = date('Ymd', strtotime($date));
            $rows[$date] = [];
            foreach ($countryMap as $country => $osMap) {
                foreach ($osMap as $os => $channelMap) {
                    foreach ($channelMap as $channel => $row) {
                        $extensionRemain = $row["extensionRemain"];//推广

                        $extension = $row["extension"] ;

                        $naturalRemain = $row["period_1_kpis"][0] - $row["extensionRemain"];//自然
                        $natural = $row["kpi_values"][1] - $row["extension"];

                        $naturalRate = number_format(($natural / $row["kpi_values"][1]) * 100, 2);

                        $tmp = [
                            '日期' => $date,
                            '国家' => $country,
                            '版本' => $os,
                            '广告渠道' => $channel,
                            'DAU' => round($row["kpi_values"][0]) ?? 0,
                            '花费$' => number_format($row["spend"],2,".","") ?? 0,
                            '总安装' => $row["kpi_values"][1] ?? 0,
                            '推广安装' => $extension,
                            '自然量安装' => $natural,
                            '自然量占比' => $naturalRate . '%',
                            '买量CPI$' => empty($extension) ? '' : number_format($row["spend"] / $extension,2,".","") ?? "",
                            '均价CPI$' => empty($row["kpi_values"][1]) ? '' : number_format($row["spend"] / $row["kpi_values"][1],2,".","") ?? "",
                            '推广次留' => empty($extension) ? '' : number_format($extensionRemain / $extension * 100,2,".","")."%" ?? '',
                            '自然量次留' => empty($natural) ? '' : number_format($naturalRemain / $natural * 100,2,".","")."%" ?? '',

                        ];
                        $日留存7 = empty($row["kpi_values"][1]) ? 0 :$row["period_6_kpis"][0] / $row["kpi_values"][1];
                        $roi7 = empty($row["spend"]) ? 0 :$row["period_6_kpis"][2] * $this->fcce / $row["spend"];
                        foreach ($showList as $time){
                            if($time == 0)$time = 1;
                            $key = $time == 1 ? '次留' : intval($time+1) .'日留存';
                            $tmp[$key] = empty($row["kpi_values"][1]) ? '' : number_format($row["period_{$time}_kpis"][0] / $row["kpi_values"][1] * 100,2,".","")."%" ?? '';

                            $key = $time == 1 ? '次留人数' : intval($time+1) .'日留存人数';
                            $tmp[$key] = intval($row["period_{$time}_kpis"][0]);
                        }
                        $tmp['付费人数'] = $row["period_0_kpis"][1] ?? 0;;
                        $tmp['付费率'] = empty($row["kpi_values"][1]) ? '' : number_format($row["period_0_kpis"][1] / $row["kpi_values"][1] * 100,2,".","")."%" ?? '';;
                        $tmp['当日ARPU'] = empty($row["kpi_values"][1]) ? '' : number_format($row["period_0_kpis"][2] / $row["kpi_values"][1],2,".","") ?? '';;
                        $tmp['当日ARPPU'] = empty($row["period_0_kpis"][1]) ? '' : number_format($row["period_0_kpis"][2] / $row["period_0_kpis"][1],2,".","") ?? '';;
                        foreach ($showList as $time){
                            $key = empty($time) ? '首日内购ROI' : intval($time+1) .'日内购ROI';
                            $tmp[$key] = empty($row["spend"]) ? '' : number_format($row["period_{$time}_kpis"][2] * $this->fcce / $row["spend"] * 100,2,".","")."%" ?? '';
                        }
                        $tmp['内购收入'] =     number_format($row["kpi_values"][2],2,".","") ?? 0; ;
                        $tmp['分成后总收入'] = number_format($row["kpi_values"][2] * $this->fcce,2,".","") ?? 0;;
                        foreach ($showList as $time){
                            $key = empty($time) ? '首日内购收入' : intval($time + 1) .'日内购收入';
                            $tmp[$key] = number_format($row["period_{$time}_kpis"][2],2,".","") ?? 0;
                        }
                        $tmp['推广次留用户数'] = $extensionRemain;
                        $tmp['自然次留用户数'] = $naturalRemain;
                        $tmp['AE']  = $this->getAE($日留存7, $roi7);
                        $tmp['AEA'] = number_format($this->getAE($日留存7, $roi7) * $row["spend"], 2, '.', '');
                        if(in_array($trackers_group_type,['Tecdo','Inplayable'])){
                            $tmp['花费$'] = $tmp['总安装'] * 3;
                        }
                        $ce = $this->getCE($tmp['AE']);
                        $validSpend += $ce * $tmp['花费$'];
                        $tmp['有效投放金额(累计)'] = number_format($validSpend, 2, '.','');
                        $tmp['合格系数'] = $ce;
                        $rows[$date][] = $tmp;
                    }
                }
            }
        }
        unset($list);
        if($sort == "DESC"){
            krsort($rows,true);
        }else{
            ksort($rows,true);
        }
        $data['list'] = $rows;
        $data['address'] = $address;
        $data['stime'] = $stime;
        $data['etime'] = $etime;
        $data['trackers_group_type'] = is_array($trackers_group_type) ? $trackers_group_type : explode(',', $trackers_group_type);
        $data['user_os'] = $user_os;
        $data["extensionList"] = $extensionList;
        $data["sort"] = $sort;
        $data["type"] = $type;
        $data["showList"] = $showList;
        $data["headerTable"] = $this->getAdjustThead($type);
        $data["trackTokens"] = $this->trackTokens;
        $data["addressList"] = $this->getCountryList();

        $this->load->view('report/dayReport2', $data);
    }
    public function adjustReport($type = 'month', $sort = "ASC"){
        set_time_limit(0);
        $stime = get_cookie('stime') ?? date("Y-m-d",strtotime("-7 days 0:0:0"));
        $etime = get_cookie('etime') ?? date("Y-m-d",strtotime("-1 days 0:0:0"));
        $address = get_cookie('address') ?? 'all';//国家
        if(strpos($address,',') !== false && strpos($address,'all') === false){
            $address = explode(",",$address);
        }else if(strpos($address,',') !== false && strpos($address,'all') !== false){
            $address = "all";
        }

        $trackers_group_type = get_cookie('trackers_group_type') ?? 'all';//广告渠道
        $user_os = get_cookie('user_os') ?? 'all';//版本
        $extensionList = $this->extensionList;//推广渠道
        $showList = $this->getPeriodTimes($type);
        switch ($type){
            case 'day':$typeText = '日';break;
            case 'month':$typeText = '月';break;
            case 'week':$typeText = '周';break;
            default: return [];
        }
        $data["title"] = "Adjust{$typeText}报";
        $list = $this->getAdjustReportData($stime,$etime,$type,$address,$trackers_group_type,$user_os,$extensionList);

        if($sort == "DESC"){
            krsort($list,true);
        }else{
            ksort($list,true);
        }
        $data['list'] = $list;
        $data['address'] = $address;
        $data['stime'] = $stime;
        $data['etime'] = $etime;
        $data['trackers_group_type'] = is_array($trackers_group_type) ? $trackers_group_type : explode(',', $trackers_group_type);
        $data['user_os'] = $user_os;
        $data["extensionList"] = $extensionList;
        $data["sort"] = $sort;
        $data["type"] = $type;
        $data["showList"] = $showList;
        $data["headerTable"] = $this->getAdjustReportThead($type, $showList);
        $data["trackTokens"] = $this->trackTokens;
        $data["addressList"] = $this->getCountryList();

        $this->load->view('report/dayReport2', $data);
    }

    public function fbAdSource($sort = "DESC"){
        $stime = get_cookie('stime') ?? date("Y-m-d",strtotime("-7 days 0:0:0"));
        $etime = get_cookie('etime') ?? date("Y-m-d",strtotime("-1 days 0:0:0"));
        $address = get_cookie('address') ?? 'all';//国家
        if(strpos($address,',') !== false && strpos($address,'all') === false){
            $address = explode(",",$address);
        }else if(strpos($address,',') !== false && strpos($address,'all') !== false){
            $address = "all";
        }
        $trackers_group_type = get_cookie('trackers_group_type') ?? 'all';//广告渠道
        $user_os = get_cookie('user_os') ?? 'all';//版本
        $campaign_id = get_cookie('campaign_id') ?? 'all';//广告系列
        $adset_id = get_cookie('adset_id') ?? 'all';//广告组
        $ad_id = get_cookie('ad_id') ?? 'all';//广告

        $columns = get_cookie('columns')  ?? 'all';//自定义列
        $columns = explode(',',  $columns);
        $headerTable = $this->getFbAdSourceThead();
        if(in_array('all', $columns)){
            $columns = ['all'];
            $showColumns = $headerTable;
        }else{
            $showColumns = $columns;
        }

        $redColumns = get_cookie('redColumns')  ?? '';//标红列
        $redColumns = explode(',',  $redColumns);
        if(in_array('all', $redColumns)){
            $redColumns = array_merge($headerTable,['all']);
        }
        $redIndex = [];
        foreach ($redColumns as $redColumn){
            $idx = array_search($redColumn, $showColumns);
            if($idx === false)continue;
            $redIndex[] = $idx;
        }
        if(in_array('all', $redColumns)){
            $redColumns = ['all'];
        }

        $periodList = [0,1,2,6,14,29,59,89,119];

        $ads = $this->getFbAdSourceData($stime,$etime,$address,$trackers_group_type,$user_os,$campaign_id,$adset_id,$ad_id,$periodList);

        if($sort == "DESC"){
            krsort($ads,true);
        }else{
            ksort($ads,true);
        }
        foreach($ads as $date => $arr){
            array_multisort(
                array_column($ads[$date],"国家"), SORT_ASC,
                array_column($ads[$date],"版本"), SORT_ASC,
                array_column($ads[$date],"广告系列"), SORT_ASC,
                array_column($ads[$date],"广告组"), SORT_ASC,
                array_column($ads[$date],"广告"), SORT_ASC,
                $ads[$date]);
        }
        $data['redColumns'] = $redColumns;
        $data['columns'] = $columns;
        $data['showColumns'] = $showColumns;
        $data['redIndex'] = $redIndex;
        $data["list"] = $ads;
        $data['address'] = $address;
        $data['stime'] = $stime;
        $data['etime'] = $etime;
        $data['sort'] = $sort;
        $data['trackers_group_type'] = $trackers_group_type;
        $data['user_os'] = $user_os;
        $data["addressList"] = $this->getCountryList();
        $data["campaign_id"] = $campaign_id;
        $data["adset_id"] = $adset_id;
        $data["ad_id"] = $ad_id;
        $data["headerTable"] = $headerTable;

        $where = "";
        if($address && $address != "all"){
            if(is_array($address)){
                $addressTemp = [];
                foreach($address as $addr){
                    $addressTemp[] = strtoupper($addr);
                }
                $addressTemp = "'".implode("','",$addressTemp)."'";
                $where .= " AND country in($addressTemp)";
            }else{
                $addressTemp = strtoupper($address);
                $where .= " AND country = '{$addressTemp}'";
            }
        }

        if($user_os && $user_os != "all"){
            switch ($user_os){
                case 'android':
                    $where .= " AND campaign_name like '%and%'";
                    break;
                case 'ios':
                    $where .= " AND campaign_name like '%ios%'";
                    break;
            }

        }

        //广告系列
        $facebookAdsTb = otable::facebookAds();
        $sql = "SELECT campaign_id,campaign_name FROM {$facebookAdsTb} WHERE date_start >= '{$stime}' AND date_start <= '{$etime}' {$where}group by campaign_id,campaign_name";
        $ret = oo::commonOprDb("report")->getAll($sql,1);
        $data["campaignList"] = $ret;

        if($campaign_id && $campaign_id != "all"){
            $where .= " AND campaign_id = '{$campaign_id}'";
        }
        //广告组
        $sql = "SELECT adset_id,adset_name FROM {$facebookAdsTb} WHERE date_start >= '{$stime}' AND date_start <= '{$etime}' {$where}group by adset_id,adset_name";
        $ret = oo::commonOprDb("report")->getAll($sql,1);
        $data["adsetList"] = $ret;

        if($adset_id && $adset_id != "all"){
            $where .= " AND adset_id = '{$adset_id}'";
        }
        //广告
        $sql = "SELECT ad_id,ad_name FROM {$facebookAdsTb} WHERE date_start >= '{$stime}' AND date_start <= '{$etime}' {$where}group by ad_id,ad_name";
        $ret = oo::commonOprDb("report")->getAll($sql,1);
        $data["adList"] = $ret;

        $this->load->view('report/fbAdSource', $data);
    }

    //Adjust日报明细
    public function dayReportView2($sort = "DESC"){
        $stime = get_cookie('stime') ?? date("Y-m-d",strtotime("-7 days 0:0:0"));
        $etime = get_cookie('etime') ?? date("Y-m-d",strtotime("-1 days 0:0:0"));
        $address = get_cookie('address') ?? 'all';//国家
        if(strpos($address,',') !== false && strpos($address,'all') === false){
            $address = explode(",",$address);
        }else if(strpos($address,',') !== false && strpos($address,'all') !== false){
            $address = "all";
        }
        $trackers_group_type = get_cookie('trackers_group_type') ?? 'Facebook';//广告渠道
        $user_os = get_cookie('user_os') ?? 'all';//版本
        $campaign_id = get_cookie('campaign_id') ?? 'all';//广告系列
        $adset_id = get_cookie('adset_id') ?? 'all';//广告组
        $ad_id = get_cookie('ad_id') ?? 'all';//广告
        $columns = get_cookie('columns')  ?? 'all';//展示列
        $columns = explode(',',  $columns);


        $headerTable = $this->getDayReportViewThead($trackers_group_type);
        if(in_array('all', $columns)){
            $columns = ['all'];
            $showColumns = $headerTable;
        }
        else{
            if($trackers_group_type == 'Google_ads'){ #非谷歌， 不显示国家
                foreach (['国家'] as $item){
                    $idx = array_search($item, $columns);
                    if($idx === false)continue;
                    unset($columns[$idx]);
                }
            }
            $showColumns = $columns;
        }
        $redColumns = get_cookie('redColumns')  ?? '';//标红列
        $redColumns = explode(',',  $redColumns);
        if(in_array('all', $redColumns)){
            $redColumns = array_merge($headerTable,['all']);
        }
        $redIndex = [];
        foreach ($redColumns as $redColumn){
            $idx = array_search($redColumn, $showColumns);
            if($idx === false)continue;
            $redIndex[] = $idx;
        }
        if(in_array('all', $redColumns)){
            $redColumns = ['all'];
        }
        $list = $this->getDayReportViewData($stime,$etime,$address,$trackers_group_type,$user_os,$campaign_id,$adset_id,$ad_id,$sort);
        $data['redColumns'] = $redColumns;
        $data['columns'] = $columns;
        $data['showColumns'] = $showColumns;
        $data['redIndex'] = $redIndex;
        $data["list"] = $list;
        $data['address'] = $address;
        $data['stime'] = $stime;
        $data['etime'] = $etime;
        $data['sort'] = $sort;
        $data['trackers_group_type'] = $trackers_group_type;
        $data['user_os'] = $user_os;
        $data["addressList"] = $this->getCountryList();
        $data["campaign_id"] = $campaign_id;
        $data["adset_id"] = $adset_id;
        $data["ad_id"] = $ad_id;
        $data["headerTable"] = $headerTable;

        //搜索
        $where = "";
        if($trackers_group_type && $trackers_group_type != "all"){
            $where .= " AND trackers_group_type = '{$trackers_group_type}'";
        }
        if($address && $address != "all"){
            if(is_array($address)){
                $addressTemp = "'".implode("','",$address)."'";
                $where .= " AND countries in($addressTemp)";
            }else{
                $where .= " AND countries = '{$address}'";
            }
        }
        if($user_os && $user_os != "all"){
            $where .= " AND os_names = '{$user_os}'";
        }

        $tb = otable::TAdjustPeriodView($trackers_group_type);
        switch ($trackers_group_type){
            case 'all':
            case 'Facebook':
            case 'Google_ads':
            case 'TikTok':
            case '苹果商店页搜索广告':
                $sql = "SELECT campaigns_id,campaigns_name FROM {$tb} WHERE date >= '{$stime}' AND date <= '{$etime}' {$where} group by campaigns_id";
                break;
            case 'Mintegral':
                $sql = "SELECT campaigns_name as campaigns_id,campaigns_name as campaigns_name FROM {$tb} WHERE date >= '{$stime}' AND date <= '{$etime}' {$where} group by campaigns_name";
                break;
            case 'IronSource':
            case 'Unity':
                $sql = "SELECT campaigns_id,campaigns_name FROM {$tb} WHERE date >= '{$stime}' AND date <= '{$etime}' {$where} group by campaigns_name";
                break;
        }
        $ret = oo::commonOprDb("report")->getAll($sql,1);
        foreach($ret as $key => $row){
            if(empty($row["campaigns_id"])) $ret[$key]["campaigns_id"] = $row["campaigns_name"];
        }
        $data["campaignList"] = $ret;

        if($campaign_id && $campaign_id != "all" && in_array($trackers_group_type,["all","Google_ads","Facebook","TikTok"])){
            $where .= " AND campaigns_id = '{$campaign_id}'";
        }
        if(in_array($trackers_group_type,["IronSource","Unity"])){
            $where .= " AND campaigns_name = '{$campaign_id}'";
        }


        switch ($trackers_group_type){
            case 'all':
            case 'Facebook':
            case 'TikTok':
            case '苹果商店页搜索广告':
                $adgroupsSql = "SELECT adgroups_id,adgroups_name FROM {$tb} WHERE date >= '{$stime}' AND date <= '{$etime}' {$where} group by adgroups_name";
                break;
            case 'Mintegral':
            case 'Google_ads':
                $adgroupsSql = "SELECT adgroups_name as adgroups_id,adgroups_name FROM {$tb} WHERE date >= '{$stime}' AND date <= '{$etime}' {$where} group by adgroups_name";
                break;
        }
        if(!empty($adgroupsSql)){
            $ret = oo::commonOprDb("report")->getAll($adgroupsSql,1);
            $data["adsetList"] = $ret;
        }

        switch ($trackers_group_type){
            case 'all':
            case 'Facebook':
            case 'TikTok':
                $where .= " and adgroups_id='{$adset_id}'";
                $adsSql = "SELECT creatives_id,creatives_name FROM {$tb} WHERE date >= '{$stime}' AND date <= '{$etime}' {$where} group by creatives_id";
                break;
        }
        if(!empty($adsSql)){
            $ret = oo::commonOprDb("report")->getAll($adsSql,1);
            $data["adList"] = $ret;
        }
        $data['channels'] = $this->paymentChannels;
        $this->load->view('report/dayReportView2', $data);
    }

    // 投放明细
    public function dayReportDetail($reportType = 'day', $sort = "ASC"){
        $stime = get_cookie('stime') ?? date("Y-m-d",strtotime("-7 days 0:0:0"));
        $etime = get_cookie('etime') ?? date("Y-m-d",strtotime("-1 days 0:0:0"));
        $address = get_cookie('address') ?? 'all';//国家
        $trackers_group_type = get_cookie('trackers_group_type') ?? 'all';//广告渠道
        $user_os = get_cookie('user_os') ?? 'android';//版本
        $columns = get_cookie('columns')  ?? 'all';//展示列
        $users = get_cookie('users')  ?? 'all';//投放人
        $columns = explode(',',  $columns);
//        $user_os = 'android';

        $headerTable = $this->getDayReportDetailThead();
        if(in_array('all', $columns)){
            $columns = ['all'];
            $showColumns = $headerTable;
        }
        $redColumns = get_cookie('redColumns')  ?? '';//标红列
        $redColumns = explode(',',  $redColumns);
        if(in_array('all', $redColumns)){
            $redColumns = array_merge($headerTable,['all']);
        }
        $redIndex = [];
        foreach ($redColumns as $redColumn){
            $idx = array_search($redColumn, $showColumns);
            if($idx === false)continue;
            $redIndex[] = $idx;
        }
        if(in_array('all', $redColumns)){
            $redColumns = ['all'];
        }
        $periodList = [0,1,2,6,14,29,59,89,119];
        $list = $this->getDayReportDetailData($reportType, $stime, $etime, $address, $trackers_group_type, $user_os, $users, $periodList, $sort);
        $formaterList = [];
        $data['redColumns'] = $redColumns;
        $data['columns'] = $columns;
        $data['showColumns'] = $showColumns;
        $data['redIndex'] = $redIndex;
        $data["list"] = $list;
        $data['address'] = is_array($address) ? $address : explode(',', $address);;
        $data['stime'] = $stime;
        $data['etime'] = $etime;
        $data['sort'] = $sort;
        $data['users'] = is_array($users) ? $users : explode(',', $users);
        $data['trackers_group_type'] = is_array($trackers_group_type) ? $trackers_group_type : explode(',', $trackers_group_type);
        $data['user_os'] = $user_os;
        $data["addressList"] = $this->getCountryList();
        $data["headerTable"] = $headerTable;
        $data["adusers"] = $this->adUsers;
        $data["reportType"] = $reportType;
        $data['channels'] = $this->paymentChannels;
        $this->load->view('report/dayReportDetail', $data);
    }

    //获取fb广告数据
    function getFbSpendData($stime,$etime,$address,$user_os,$campaign_id,$adset_id,$ad_id){
        $tb = otable::facebookAds();
        $where = '';
        if($address && $address != "all"){
            if(is_array($address)){
                foreach($address as $key => $addr){
                    $address[$key] = strtoupper($addr);
                }
                $address = "'".implode("','",$address)."'";
                $where .= " AND country in($address)";
            }else{
                $where .= " AND country = '{$address}'";
            }
        }
        if($user_os && $user_os != "all"){
            switch ($user_os){
                case 'android':
                    $where .= " AND campaign_name like '%and%'";
                    break;
                case 'ios':
                    $where .= " AND campaign_name like '%ios%'";
                    break;
            }
        }
        if($campaign_id && $campaign_id != "all"){
            $where .= " AND campaign_id = '{$campaign_id}'";
        }
        if($adset_id && $adset_id != "all"){
            $where .= " AND adset_id = '{$adset_id}'";
        }
        if($ad_id && $ad_id != "all"){
            $where .= " AND ad_id = '{$ad_id}'";
        }
        $sql = "SELECT * FROM {$tb} WHERE date_start >= '{$stime}' AND date_start <= '{$etime}' {$where}";
        $ret = oo::commonOprDb("report")->getAll($sql,1);
        $out = [];
        foreach($ret as $row){
//            $row['spend'] = $row['spend']*$this->spendCeList['fb'];
            $date = $row["date_start"];
            $out[$date][$row["ad_id"]][] = $row;
        }
        return $out;
    }
    function getTikTokSpendData($stime,$etime,$address,$user_os,$campaign_id,$adset_id,$ad_id){
        $tb = otable::TTypeCampain('TikTok');
        $where = '';
        if($address && $address != "all"){
            if(is_array($address)){
                foreach($address as $key => $addr){
                    $address[$key] = strtoupper($addr);
                }
                $address = "'".implode("','",$address)."'";
                $where .= " AND country in($address)";
            }else{
                $where .= " AND country = '{$address}'";
            }
        }
        if($user_os == 'ios')$user_os = 'iphone';
        if($user_os && $user_os != "all"){
            $where .= " AND user_os='{$user_os}'";
        }
        if($campaign_id && $campaign_id != "all"){
            $where .= " AND campain_id = '{$campaign_id}'";
        }
        if($adset_id && $adset_id != "all"){
            $where .= " AND adgroup_id = '{$adset_id}'";
        }
        if($ad_id && $ad_id != "all"){
            $where .= " AND ad_id = '{$ad_id}'";
        }
        $sql = "SELECT * FROM {$tb} WHERE data_start >= '{$stime}' AND data_start <= '{$etime}' {$where}";
        $ret = oo::commonOprDb("report")->getAll($sql,1);
        $out = [];
        foreach($ret as $row){
//            $row['spend'] = $row['spend']*$this->spendCeList['tt'];
            $date = $row["data_start"];
            $out[$date][$row["ad_id"]][] = $row;
        }
        return $out;
    }
    function getAppleSpendData($stime,$etime,$address,$user_os,$campaign_id,$adset_id,$ad_id){
        $tb = otable::TTypeCampain('apple');
        $where = '';
        if($address && $address != "all"){
            if(is_array($address)){
                foreach($address as $key => $addr){
                    $address[$key] = strtoupper($addr);
                }
                $address = "'".implode("','",$address)."'";
                $where .= " AND country in($address)";
            }else{
                $where .= " AND country = '{$address}'";
            }
        }
        if($user_os && $user_os != "all"){
            $where .= " AND user_os='{$user_os}'";
        }
        if($campaign_id && $campaign_id != "all"){
            $where .= " AND campain_id = '{$campaign_id}'";
        }
        if($adset_id && $adset_id != "all"){
            $where .= " AND adgroup_id = '{$adset_id}'";
        }
        $sql = "SELECT * FROM {$tb} WHERE data_start >= '{$stime}' AND data_start <= '{$etime}' {$where}";
        $ret = oo::commonOprDb("report")->getAll($sql,1);
        $out = [];
        foreach($ret as $row){
            $date = $row["data_start"];
            $out[$date][$row["adgroup_id"]][] = $row;
        }
        return $out;
    }

    //获取其他渠道花费等数据
    function getOtherSpendData($stime,$etime,$address,$user_os,$trackers_group_type,$campaign_id){
        $tb = $where = $dateStr = $campaignName = "";
        if($trackers_group_type == "Google_ads"){
            $tb = otable::tGoogleViews();
            $dateStr = "data_start";
            $campaignName = "campaign_id";
        }else if($trackers_group_type == "IronSource"){
            $tb = otable::TIronsourceCampain();
            $dateStr = "data_start";
            $campaignName = "name";
        }else if($trackers_group_type == "Unity"){
            $tb = otable::TUnityCampain();
            $dateStr = "data_start";
            $campaignName = "name";
        }else if(in_array($trackers_group_type,['Applovin', 'Chartboost', 'Mintegral'])){
            $tb = otable::TTypeCampain($trackers_group_type);
            $dateStr = "data_start";
            $campaignName = "name";
            if($trackers_group_type == 'Mintegral'){
                $campaignName = 'id';
            }
        }
        if(empty($tb)){
            return [];
        }
        if($user_os && $user_os != "all" && $trackers_group_type == "Google_ads"){
//            switch ($user_os){
//                case 'android':
//                    $where .= " AND campaign_name like '%and%'";
//                    break;
//                case 'ios':
//                    $where .= " AND campaign_name like '%ios%'";
//                    break;
//            }
            $where .= " AND user_os = '{$user_os}'";
        }else if($user_os && $user_os != "all" && in_array($trackers_group_type,["IronSource","Unity"])){
            $where .= " AND user_os = '{$user_os}'";
        }
        if($address && $address != "all" &&  $trackers_group_type != "Google_ads"){
            if(is_array($address)){
                foreach($address as $key => $addr){
                    $address[$key] = strtoupper($addr);
                }
                $address = "'".implode("','",$address)."'";
                $where .= " AND country in($address)";
            }else{
                $address = strtoupper($address);
                $where .= " AND country = '{$address}'";
            }
        }
        if($campaign_id && $campaign_id != "all"){
            $where .= " AND {$campaignName} = '{$campaign_id}'";
        }
        $where .= " AND {$dateStr} >= '{$stime}' AND {$dateStr} <= '{$etime}'";
        $sql = "SELECT * FROM {$tb} WHERE 1=1 {$where}";
        $ret = oo::commonOprDb("report")->getAll($sql,1);
        $out = [];
        foreach($ret as $row){
            $date = $row[$dateStr];
            $out[$date][$row[$campaignName]][] = $row;
        }
        return $out;
    }

    function array_sort($arrays,$sort_key,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC ) {
        if(is_array($arrays)) {
            foreach ($arrays as $array) {
                if(is_array($array)) {
                    $key_arrays[] = iconv('utf-8', 'GB2312//IGNORE', $array[$sort_key]);
                } else {
                    return false;
                }
            }
        } else {
            return false;
        }
        array_multisort($key_arrays,$sort_order,$sort_type,$arrays);
        return $arrays;
    }

    public function getThreeType(){
        $postData = $this->input->post();
        $type = $postData["type"];
        $class = $postData["class"] ?? "fb";
        $stime = $postData["stime"];
        $etime = $postData["etime"];
        $address = $postData['address'] ?? 'all';//国家
        $user_os = $postData['user_os'] ?? 'all';//版本
        if($class == 'Facebook')$class='fb';
        $tb = $class == "fb" ? otable::facebookAds() : otable::TAdjustPeriodView();
        $ret = [];
        $where = "";
        if(strpos($address,"all") !== false){
            $address = "all";
        }
        if($address && $address != "all" && ($class != 'Google_ads')){
            if(strpos($address,",") !== false){
                $address = explode(",",$address);
                $addressTemp = [];
                foreach($address as $addr){
                    $addressTemp[] = strtoupper($addr);
                }
                $addressTemp = "'".implode("','",$addressTemp)."'";
                $class == "fb" ? ($where .= " AND country in ({$addressTemp})") : ($where .= " AND countries in($addressTemp)");
            }else{
                $addressTemp = strtoupper($address);
                $class == "fb" ? ($where .= " AND country = '{$addressTemp}'") : ($where .= " AND countries = '{$address}'");
            }
        }

        if($user_os && $user_os != "all"){
            if($class == "fb"){
                switch ($user_os){
                    case 'android':
                        $where .= " AND campaign_name like '%and%'";
                        break;
                    case 'ios':
                        $where .= " AND campaign_name like '%ios%'";
                        break;
                }
            }else{
                $where .= " AND os_names = '{$user_os}'";
            }
        }
        switch ($type){
            case "channel":
                $channel = $postData["channel"];
                switch ($class){
                    case 'fb':
                        $sql = "SELECT campaign_id as adset_id,campaign_name as adset_name FROM {$tb} WHERE date_start >= '{$stime}' AND date_start <= '{$etime}'  {$where} GROUP BY  campaign_id,campaign_name";
                        break;
                    case 'Google_ads':
                        $sql = "SELECT campaigns_id as adset_id,campaigns_name as adset_name FROM {$tb} WHERE date >= '{$stime}' AND date <= '{$etime}' AND trackers_group_type = '{$channel}' {$where} GROUP BY adset_id,adset_name";
                        break;
                    case 'Mintegral':
                        $sql = "SELECT campaigns_name as adset_id,campaigns_name as adset_name FROM {$tb} WHERE date >= '{$stime}' AND date <= '{$etime}' AND trackers_group_type = '{$channel}' {$where} GROUP BY adset_id,adset_name";
                        break;
                    case 'TikTok':
                    case '苹果商店页搜索广告':
                        $sql = "SELECT campaigns_id as adset_id,campaigns_name as adset_name FROM {$tb} WHERE date >= '{$stime}' AND date <= '{$etime}' AND trackers_group_type = '{$channel}' and campaigns_id<>'' {$where} GROUP BY adset_id,adset_name";
                        break;
                }
                $ret = oo::commonOprDb("report")->getAll($sql,1);
                break;
            case "campaign":
                $campaign_id = $postData["campaign_id"];
                switch ($class){
                    case 'fb':
                        $sql = "SELECT adset_id,adset_name FROM {$tb} WHERE date_start >= '{$stime}' AND date_start <= '{$etime}' AND campaign_id = '{$campaign_id}' {$where} GROUP BY adset_id,adset_name";
                        break;
                    case 'Google_ads':
                        $sql = "SELECT adgroups_name as adset_id,adgroups_name as adset_name FROM {$tb} WHERE date >= '{$stime}' AND date <= '{$etime}' AND campaigns_id = '{$campaign_id}' {$where} GROUP BY adset_id,adset_name";
                        break;
                    case 'Mintegral':
                        $sql = "SELECT adgroups_name as adset_id,adgroups_name as adset_name FROM {$tb} WHERE date >= '{$stime}' AND date <= '{$etime}' AND campaigns_name = '{$campaign_id}' {$where} GROUP BY adset_id,adset_name";
                        break;
                    case 'TikTok':
                    case '苹果商店页搜索广告':
                        $sql = "SELECT adgroups_id as adset_id,adgroups_name as adset_name FROM {$tb} WHERE date >= '{$stime}' AND date <= '{$etime}' AND campaigns_id = '{$campaign_id}' {$where} GROUP BY adset_id,adset_name";
                        break;
                }
                $ret = oo::commonOprDb("report")->getAll($sql,1);
                break;
            case "adset":
                $adset_id = $postData["adset_id"];
                switch ($class){
                    case 'fb':
                        $sql = "SELECT ad_id,ad_name FROM {$tb} WHERE date_start >= '{$stime}' AND date_start <= '{$etime}' AND adset_id = '{$adset_id}' {$where} GROUP BY ad_id,ad_name";
                        break;
//                    case 'Google_ads':
//                        $sql = "SELECT adgroups_name as ad_id,adgroups_name as ad_name FROM {$tb} WHERE date >= '{$stime}' AND date <= '{$etime}' AND campaigns_id = '{$adset_id}' {$where} GROUP BY ad_id,ad_name";
//                        break;
//                    case 'Mintegral':
//                        $sql = "SELECT adgroups_name as ad_id,adgroups_name as ad_name FROM {$tb} WHERE date >= '{$stime}' AND date <= '{$etime}' AND campaigns_name = '{$adset_id}' {$where} GROUP BY ad_id,ad_name";
//                        break;
                    case 'TikTok':
                    case '苹果商店页搜索广告':
                        $sql = "SELECT creatives_id as ad_id,creatives_name as ad_name FROM {$tb} WHERE date >= '{$stime}' AND date <= '{$etime}' AND adgroups_id = '{$adset_id}' {$where} GROUP BY ad_id,ad_name";
                        break;
                }
                $ret = oo::commonOprDb("report")->getAll($sql,1);
                break;
        }
        echo $this->response(empty($ret)?1:0, empty($ret)?'操作失败':'操作成功', $ret,true);
    }

    public function diffBetweenTwoDays ($day1, $day2){
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);

        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return ($second1 - $second2) / 86400;
    }

    //根据日期返回属于第几周
    function getWeekDate($date){
        $date = date("Ymd",strtotime($date));
        $w = date("w",strtotime($date));
        switch($w){
            case 0:
                //周日
                $s = date("Ymd",strtotime($date." -6 days 0:0:0"));
                $e = $date;
                break;
            case 1:
                //周一
                $s = $date;
                $e = date("Ymd",strtotime($date." +6 days 0:0:0"));
                break;
            default:
                $s = date("Ymd",strtotime($date." -".($w-1)." days 0:0:0"));
                $e = date("Ymd",strtotime($date." +".(7-$w)." days 0:0:0"));
        }
        return $s."~".$e;
    }

    //返回给定时间戳当月内第一天和最后一天
    function getMonthDate($date){
        $s = date('Y-m-01', strtotime($date));
        $e = date('Ymd', strtotime("$s +1 month -1 day"));
        $s = date("Ymd",strtotime($s));
        return $s."~".$e;
    }

    //获取FB花费
    function getFbSpend($date,$countriesTemp,$os_namesTemp, $users = []){
        return $this->getFbSpend2($date,$countriesTemp,$os_namesTemp, $users);
    }

    //FB花费方案一 连表查询
    function getFbSpend1($date,$countriesTemp,$os_namesTemp){
        $facebookAds = otable::facebookAds();
        $facebookAdset = otable::facebookAdset();

        $where = '';
        if($countriesTemp && $countriesTemp != "all"){
            $countriesTempT = strtoupper($countriesTemp);
            $where .= " AND countries = '{$countriesTempT}'";
        }
        if($os_namesTemp && $os_namesTemp != "all"){
            switch ($os_namesTemp){
                case "android":
                    $os_namesTempT = "Android";
                    break;
                case "ios":
                    $os_namesTempT = "iOS";
                    break;
            }
            $os_namesTempT && $where .= " AND user_os = '{$os_namesTempT}'";
        }
        $sql = "SELECT sum(spend) as total FROM {$facebookAds} ads,{$facebookAdset} adset WHERE ads.adset_id = adset.id AND ads.date_start = '{$date}' AND adset.date_start = '{$date}' {$where}";
        $ret = oo::commonOprDb('report')->getOne($sql,1);
        return $ret['total'] ?? 0;
    }

    //FB花费方案二 根据系列名称查询 不区分设备可以要这个
    function getFbSpend2($date,$countriesTemp,$os_namesTemp, $users = []){
        //采用like 区别设备，因为连表后查询数据有问题，两表保存数据不一致问题
        $facebookAds = otable::facebookAds();
        $where = '';
        if($countriesTemp && $countriesTemp != "all"){
            if(strpos($countriesTemp,",") !== false){
                $countriesTempT = strtoupper($countriesTemp);
                $countriesTempT = explode(",",$countriesTempT);
                $countriesTempT = "'".implode("','",$countriesTempT)."'";
                $where .= " AND country in({$countriesTempT})";
            }else{
                $countriesTempT = strtoupper($countriesTemp);
                $where .= " AND country = '{$countriesTempT}'";
            }
        }
        if($os_namesTemp && $os_namesTemp != "all"){
            switch ($os_namesTemp){
                case "android":
                    $where .= " AND campaign_name like '%and%'";
                    break;
                case "ios":
                    $where .= " AND campaign_name like '%ios%'";
                    break;
            }
        }
        if(strpos($date,"~") !== false){
            $dateTemp = explode("~",$date);
            $stime = date("Y-m-d",strtotime($dateTemp[0]));
            $etime = date("Y-m-d",strtotime($dateTemp[1]));
            $where .= " AND date_start >= '{$stime}' AND date_start <= '{$etime}'";
        }else{
            $where .= " AND date_start = '{$date}'";
        }
        if(!empty($users)){
            $where .= ' and ( 0 ';
            foreach ($users as $user){
                $where .= " or campaign_name like '%{$user}%' ";
            }
            $where .= ')';
        }
        $sql = "select sum(spend) as total from (SELECT spend FROM {$facebookAds} WHERE 1=1 {$where} group by date_start,date_stop, country,ad_id ,spend) t1";
        $ret = oo::commonOprDb('report')->getOne($sql,1);
        return $ret['total'] ?? 0;
    }

    //FB花费方案三 分开查询
    function getFbSpend3($date,$countriesTemp,$os_namesTemp){
        $facebookAds = otable::facebookAds();
        $facebookAdset = otable::facebookAdset();

        //adset取出对应设备的广告组ID
        $whereAdset = '';
        if($os_namesTemp && $os_namesTemp != "all"){
            switch ($os_namesTemp){
                case "android":
                    $os_namesTempT = "Android";
                    break;
                case "ios":
                    $os_namesTempT = "iOS";
                    break;
            }
            $os_namesTempT && $whereAdset .= " AND user_os = '{$os_namesTempT}'";
        }

        $where = '';
        if($countriesTemp && $countriesTemp != "all"){
            $countriesTempT = strtoupper($countriesTemp);
            $where .= " AND country = '{$countriesTempT}'";
        }
        $sql = "SELECT sum(spend) as total FROM {$facebookAds} WHERE date_start = '{$date}' {$where} AND adset_id in( SELECT id FROM {$facebookAdset} WHERE date_start = '{$date}' {$whereAdset} )";
        $ret = oo::commonOprDb('report')->getOne($sql,1);
        return $ret['total'] ?? 0;
    }

    //FB花费方案四 新的fb细分表
    function getFbSpend4($date,$countriesTemp,$os_namesTemp){
        $facebookAds = otable::facebookAds();
        $TAdjustPeriodView = otable::TAdjustPeriodView();

        $where = "";
        if($countriesTemp && $countriesTemp != "all"){
            $countriesTempT = strtolower($countriesTemp);
            $where .= " AND countries = '{$countriesTempT}'";
        }
        if($os_namesTemp && $os_namesTemp != "all"){
            $where .= " AND os_names = '{$os_namesTemp}'";
        }
        $sql = "SELECT sum(spend) as total FROM {$facebookAds} ads,{$TAdjustPeriodView} v WHERE ads.date_start = v.date AND ads.date_start = '{$date}' AND ads.campaign_id = v.campaigns_id AND ads.adset_id = v.adgroups_id AND ads.ad_id = v.creatives_id AND v.countries = ads.country AND v.trackers_group_type = 'Facebook' {$where} ";
        $ret = oo::commonOprDb('report')->getOne($sql,1);
        return $ret['total'] ?? 0;
    }

    //返回Google花费
    function getGoogleSpend($date,$country,$os_names = "android", $users = []){
        return $this->getGoogleSpendFromCampaigns($date,$country,$os_names , $users);
//        return $this->getGoogleSpendFromViews($date,$country,$os_names , $users);
    }
    function getGoogleSpendFromCampaigns($date,$country,$os_names = "android", $users = []){
        $where = '';
        if($country && $country != "all"){
            if(strpos($country,",") !== false){
                $country = explode(",",$country);
                $countryTemp = [];
                foreach($country as $addr){
                    $countryTemp[] = strtoupper($addr);
                }
                $countryTemp = "'".implode("','",$countryTemp)."'";
                $where .= " AND country in ({$countryTemp})";
            }else{
                $where .= " AND country = '{$country}'";
            }
        }
        switch ($os_names){
            case 'all';break;
            case 'android';$where .= " and campaign_name like '%_AND_%'" ;break;
            case 'ios';$where .= " and campaign_name like '%_IOS_%'" ;break;
            default : return 0;

        }

        if(!empty($users)){
            $where .= ' and ( 0 ';
            foreach ($users as $user){
                $where .= " or campaign_name like '%{$user}%' ";
            }
            $where .= ')';
        }
        if(strpos($date,"~") !== false){
            $dateTemp = explode("~",$date);
            $stime = date("Y-m-d",strtotime($dateTemp[0]));
            $etime = date("Y-m-d",strtotime($dateTemp[1]));
            $where .= " AND date_start >= '{$stime}' AND date_start <= '{$etime}'";
        }else{
            $where .= " AND date_start = '{$date}'";
        }
        $googleCampaign = otable::googleCampaign();
        $sql = "SELECT sum(spend) as total FROM {$googleCampaign} WHERE 1=1 {$where}";
        $ret = oo::commonOprDb('report')->getOne($sql,1);
        return $ret['total'] ?? 0;
    }
    function getGoogleSpendFromViews($date,$country,$os_names = "android", $users = []){
        $where = '';
        switch ($os_names){
            case 'all';break;
            case 'android';$where .= " and campaign_name like '%_AND_%'" ;break;
            case 'ios';$where .= " and campaign_name like '%_IOS_%'" ;break;
            default : return 0;

        }

        if(!empty($users)){
            $where .= ' and ( 0 ';
            foreach ($users as $user){
                $where .= " or campaign_name like '%{$user}%' ";
            }
            $where .= ')';
        }
        if(strpos($date,"~") !== false){
            $dateTemp = explode("~",$date);
            $stime = date("Y-m-d",strtotime($dateTemp[0]));
            $etime = date("Y-m-d",strtotime($dateTemp[1]));
            $where .= " AND data_start >= '{$stime}' AND data_start <= '{$etime}'";
        }else{
            $where .= " AND data_start = '{$date}'";
        }
        $googleCampaign = otable::tGoogleViews();
        $sql = "SELECT sum(spend) as total FROM {$googleCampaign} WHERE 1=1 {$where}";
        $ret = oo::commonOprDb('report')->getOne($sql,1);
        return $ret['total'] ?? 0;
    }

    //获取ironsource渠道花费
    function getIronsourceSpend($date,$country,$os_names = "android", $users = []){
        $where = "";
        if($country && $country != "all"){
            if(strpos($country,",") !== false){
                $countryTemp = explode(",",$country);
                $countryTemp = "'".implode("','",$countryTemp)."'";
                $where .= " AND country in ({$countryTemp})";
            }else{
                $where .= " AND country = '{$country}'";
            }
        }
        if($os_names && $os_names != "all"){
            $where .= " AND user_os = '{$os_names}'";
        }
        if(strpos($date,"~") !== false){
            $dateTemp = explode("~",$date);
            $stime = date("Y-m-d",strtotime($dateTemp[0]));
            $etime = date("Y-m-d",strtotime($dateTemp[1]));
            $where .= " AND data_start >= '{$stime}' AND data_start <= '{$etime}'";
        }else{
            $where .= " AND data_start = '{$date}'";
        }
        if(!empty($users)){
            $where .= ' and ( 0 ';
            foreach ($users as $user){
                $where .= " or name like '%{$user}%' ";
            }
            $where .= ')';
        }
        $TIronsourceCampain = otable::TIronsourceCampain();
        $sql = "SELECT sum(spend) as total FROM {$TIronsourceCampain} WHERE 1=1 {$where}";
        $ret = oo::commonOprDb('report')->getOne($sql,1);
        return $ret['total'] ?? 0;
    }

    //获取国家列表
    function getCountryList(){
        $TCountryCode = otable::TCountryCode();
        $sql = "SELECT * FROM {$TCountryCode} order by code ASC";
        $ret = oo::commonOprDb('report')->getAll($sql,1);
        return $ret;
    }

    //重新获取adjust周、月dau
    function getWeekMonth($type,$date,$address,$trackers_group_type,$user_os){

        if($type == "week"){
            $dates = explode("~",$date);
            $dates[0] = date("Y-m-d",strtotime($dates[0]));
            $dates[1] = date("Y-m-d",strtotime($dates[1]));
        }else if($type == "month"){
            $date = $date."01";
            $dates[0] = date("Y-m-d",strtotime($date));
            $dates[1] = date("Y-m-d",strtotime($date." +1 month")-1);
        }
        if($address == "all"){
            $url = "https://api.adjust.com/kpis/v1/rv3fkx1a8em8?start_date={$dates[0]}&end_date={$dates[1]}&grouping=trackers,os_names&kpis=daus&user_token=nDPDkox9PxGoisxoMm9Q&attribution_type=click";
        }else{
            $url = "https://api.adjust.com/kpis/v1/rv3fkx1a8em8?start_date={$dates[0]}&end_date={$dates[1]}&grouping=trackers,os_names&kpis=daus&user_token=nDPDkox9PxGoisxoMm9Q&attribution_type=click&countries={$address}";
        }

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        //设置连接超时时间
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
        //设置请求超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, 20);
        $response = @curl_exec($ch);
        if ($errno = curl_errno($ch))
        {
            //return json_encode(array('errno'=>$errno, 'error'=>curl_error($ch)));
        }
        curl_close($ch);
        $response = json_decode($response,1);
        $dau = 0;
        if($response){
            foreach($response["result_set"]["trackers"] as $row){
                $trackers_group_type_temp = "";
                foreach($this->trackerGroup as $key => $tokenArr){
                    if(in_array($row["token"],$tokenArr)){
                        $trackers_group_type_temp = $key;
                        break;
                    }
                }
                if($trackers_group_type != "all" && $trackers_group_type_temp != $trackers_group_type){
                    continue;
                }

                foreach($row["os_names"] as $os_names){
                    if($user_os != "all" && $os_names["os_name"] != $user_os){
                        continue;
                    }
                    $dau += $os_names["kpi_values"][0];
                }

            }
        }

        return $dau;
    }

    //获取adjust数据
    function getAdjustData($stime,$etime,$type,$address,$trackers_group_type,$user_os,$extensionList,$periodList){
        $cacheKey = $stime."-".$etime."-".$type."-".$address."-".$trackers_group_type."-".$user_os;
        $cache = oo::commonOprRedis('Statistics')->get($cacheKey);
        if($cache){
//            return json_decode($cache,1);
        }
        if(!is_array($address)){
            $address = strtolower($address);
            $address = explode(',', $address);
            if(in_array('all', $address))$address = 'all';
            elseif (count($address) == 1)$address = $address[0];
        }
        $where = "";
        if($address && $address != "all"){
            if(is_array($address)){
                $addressTemp = "'".implode("','",$address)."'";
                $where .= " AND countries in ($addressTemp)";
            }else{
                $where .= " AND countries = '{$address}'";
            }
        }
        if(!is_array($trackers_group_type))$trackers_group_type = explode(',', $trackers_group_type);
        if(!in_array('all', $trackers_group_type)){
            $whereTokens = [];
            foreach ($trackers_group_type as $tmpTracker){
                if(empty($this->trackTokens[$tmpTracker]) || !is_array($this->trackTokens[$tmpTracker]))continue;
                $whereTokens = array_unique(array_merge($whereTokens, $this->trackTokens[$tmpTracker]));
            }
            if(!empty($whereTokens)){
                $whereTokensStr = '"'.implode('","', $whereTokens).'"';
                $where .= " AND trackers_channel_token in ({$whereTokensStr})";
            }
        }else{
            $trackers_group_type = ['all'];
        }
//        if($trackers_group_type && $trackers_group_type != "all"){
//            switch (strtolower($trackers_group_type)){
//                case 'share':
//                    $where .= " AND trackers_channel_token = 'm6tz7ra'";break;
//                case 'organic':
//                    $where .= " AND trackers_channel_token <> 'm6tz7ra' and trackers_group_type='Organic_all'";break;
//                default:
//                    $where .= " AND trackers_group_type = '{$trackers_group_type}'";
//            }
//        }
        if($user_os && $user_os != "all"){
            $where .= " AND os_names = '{$user_os}'";
        }
        if($type == "day" || $type == "ltv"){
            $where .= " AND date >= '{$stime}' AND date <= '{$etime}'";
        }else if($type == "week"){
            $dateArr = [];
            $stimeTemp = date("Ymd",strtotime($stime));
            $etimeTemp = date("Ymd",strtotime($etime));
            for($timei = $stimeTemp; $timei <= $etimeTemp; $timei = date("Ymd",strtotime($timei." +1 days"))){
                $dateArr[$this->getWeekDate($timei)] = 1;
            }
            $dateKeys = array_keys($dateArr);
            $dateKeysStr = "'".implode("','",$dateKeys)."'";
            $where .= " AND date in({$dateKeysStr})";
        }else if($type == "month"){
            $dateArr = [];
            $stimeTemp = date("Ymd",strtotime($stime));
            $etimeTemp = date("Ymd",strtotime($etime));
            for($timei = $stimeTemp; $timei <= $etimeTemp; $timei = date("Ymd",strtotime($timei."+1 days"))){
                $dateArr[$this->getMonthDate($timei)] = 1;
            }

            $dateKeys = array_keys($dateArr);

            $dateKeysStr = "'".implode("','",$dateKeys)."'";
            $where .= " AND date in({$dateKeysStr})";
        }

        $data = [];
        $TAdjust = otable::TAdjust($type);
        $sql = "SELECT * FROM {$TAdjust} WHERE 1=1 {$where}";
        $TAdjustDataRet = oo::commonOprDb('report')->getAll($sql,1);
        $TAdjustData = [];
        $trackers_group_typeKey = implode(',', $trackers_group_type);
        foreach($TAdjustDataRet as $key => $row){
//            $row["trackers_group_type"] = $trackers_group_typeKey;
            $row["kpi_values"] = json_decode($row["kpi_values"],1);
            if(isset($TAdjustData[$row["date"]][$row["countries"]][$row["os_names"]][$row["trackers_channel_token"]])){
                foreach($row["kpi_values"] as $k => $vo){
                    $TAdjustData[$row["date"]][$row["countries"]][$row["os_names"]][$row["trackers_channel_token"]][$k] += $vo;
                }
            }else{
                $TAdjustData[$row["date"]][$row["countries"]][$row["os_names"]][$row["trackers_channel_token"]] = $row["kpi_values"];
            }
        }
        $TAdjustPeriod = otable::TAdjustPeriod($type);
        $sql = "SELECT * FROM {$TAdjustPeriod} WHERE 1=1 {$where}";
        $TAdjustPeriodDataRet = oo::commonOprDb('report')->getAll($sql,1);
        $TAdjustPeriodData = [];
        foreach ($TAdjustPeriodDataRet as $key => $row){
            $row["trackers_group_type"] = $trackers_group_typeKey;
            foreach($periodList as $time){
                $row["period_{$time}_kpis"] = json_decode($row["period_{$time}_kpis"],true);
            }
            if(isset($TAdjustPeriodData[$row["date"]][$row["countries"]][$row["os_names"]][$row["trackers_channel_token"]])){
                foreach($periodList as $time){
                    foreach($row["period_{$time}_kpis"] as $k => $vo){
                        $TAdjustPeriodData[$row["date"]][$row["countries"]][$row["os_names"]][$row["trackers_channel_token"]]["period_{$time}_kpis"][$k] += $vo;
                    }
                }
            }else{
                foreach($periodList as $time){
                    $TAdjustPeriodData[$row["date"]][$row["countries"]][$row["os_names"]][$row["trackers_channel_token"]]["period_{$time}_kpis"] = $row["period_{$time}_kpis"];
                }
            }
        }
        $list = [];

        foreach($TAdjustData as $date => $row){
            $extension = $extensionRemain = [];
            foreach($row as $countriesTemp => $rowTwo){
                $countriesTemp2 = $countriesTemp;
                if($address && $address == "all"){
                    $countriesTemp = "all";
                }else if($address && count($address) > 1){
                    $countriesTemp = implode(",",$address);
                }
                if($user_os && $user_os == "all") {
                    $extension[$countriesTemp2] = 0;//推广安装
                    $extensionRemain[$countriesTemp2] = 0;//推广留存人数
                }
                foreach($rowTwo as $os_namesTemp => $rowThree){
                    $os_namesTemp2 = $os_namesTemp;
                    if($user_os && $user_os == "all"){
                        $os_namesTemp = "all";
                    }else{
                        $extension[$countriesTemp2] = 0;//推广安装
                        $extensionRemain[$countriesTemp2] = 0;//推广留存人数
                    }
                    foreach($rowThree as $trackers_group_typeTemp => $vo){
                        if(in_array($trackers_group_typeTemp,$extensionList)){
                            //计算推广安装
                            $extension[$countriesTemp2] += $vo[1];
                            //计算推广留存人数
                            $extensionRemain[$countriesTemp2] += $TAdjustPeriodData[$date][$countriesTemp2][$os_namesTemp2][$trackers_group_typeTemp]["period_1_kpis"][0];
                        }
                    }
                    foreach($rowThree as $trackers_group_typeTemp => $vo){
                        $trackers_group_typeTemp2 = $trackers_group_typeTemp ;//= $trackers_group_typeKey;
                        if($trackers_group_type && $trackers_group_type == "all"){
                            $trackers_group_typeTemp = "all";
                        }

                        if(isset($list[$date][$countriesTemp][$os_namesTemp][$trackers_group_typeTemp])){
                            foreach($vo as $k => $num){
                                $list[$date][$countriesTemp][$os_namesTemp][$trackers_group_typeTemp]["kpi_values"][$k] += $num;
                            }

                            foreach($periodList as $time){
                                $temp = $TAdjustPeriodData[$date][$countriesTemp2][$os_namesTemp2][$trackers_group_typeTemp2]["period_{$time}_kpis"];
                                if(!empty($temp)){
                                    foreach($temp as $tempK => $tempV){
                                        $list[$date][$countriesTemp][$os_namesTemp][$trackers_group_typeTemp]["period_{$time}_kpis"][$tempK] += $tempV;
                                    }
                                }
                            }
                        }else{
                            $list[$date][$countriesTemp][$os_namesTemp][$trackers_group_typeTemp]["kpi_values"] = $vo;
                            foreach($periodList as $time){
                                $list[$date][$countriesTemp][$os_namesTemp][$trackers_group_typeTemp]["period_{$time}_kpis"] = $TAdjustPeriodData[$date][$countriesTemp2][$os_namesTemp2][$trackers_group_typeTemp2]["period_{$time}_kpis"];
                            }
                        }
                    }
                }
            }
        }
        $listNew = [];
//        $selectedTokens = [];
        $trackTokenReserve = [];
        foreach ($this->trackTokens as $channel => $tokens){
//            if(in_array($channel, $trackers_group_type))$selectedTokens = array_merge($selectedTokens, (array)$tokens);
            foreach ($tokens as $token){
                $trackTokenReserve[$token] = $channel;
            }
        }
        $网盟CPI = 1;
        $cpiList = oo::commonOprDb('report')->getAll('select * from '.otable::wmcpi());
        $cpiList = array_column($cpiList, 'cpi', 'name');
        foreach ($list as $dateKey => $dateItems){
            foreach ($dateItems as $countryKey => $countryItems){
                foreach ($countryItems as $osKey => $osItems){
                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey] = [
                        'extension' => 0,
                        'extensionRemain' => 0,
                        'kpi_values' => [],
                    ];
                    foreach ($periodList as $i){
                        $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["period_{$i}_kpis"] = [];
                    }
                    foreach ($osItems as $trackToken => $items){
                        foreach ($items['kpi_values'] as $k => $v){
                            if(empty($listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]['kpi_values'][$k]))$listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]['kpi_values'][$k] = 0;
                            $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]['kpi_values'][$k] += $v;
                        }
                        foreach ($periodList as $i){
                            foreach ((array)$items["period_{$i}_kpis"] as $k => $v){
                                if(empty($listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["period_{$i}_kpis"][$k]))
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["period_{$i}_kpis"][$k] = 0;
                                $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["period_{$i}_kpis"][$k] += $v;
                            }
                        }
                        if(in_array($trackTokenReserve[$trackToken], $extensionList)){
                            $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]['extension'] += $items['kpi_values'][1];
                            $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]['extensionRemain'] += $items["period_1_kpis"][0];
                        }

                        if(empty($listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"])){
                            $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] = 0;

                            if(in_array("all", $trackers_group_type )){
                                //fb花费 + google花费 + IronSource花费 + Unity花费
                                $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] +=
                                    $this->getFbSpend($dateKey,$countryKey,$osKey)
                                    +$this->getGoogleSpend($dateKey,$countryKey,$osKey)
                                    +$this->getIronsourceSpend($dateKey,$countryKey,$osKey)
                                    +$this->getUnitySpend($dateKey,$countryKey,$osKey)
                                    +$this->getApplovinSpend($dateKey,$countryKey,$osKey)
                                    +$this->getChartboostSpend($dateKey,$countryKey,$osKey)
                                    +$this->getMintegralSpend($dateKey,$countryKey,$osKey)
                                    +$this->getTikTokSpend($dateKey,$countryKey,$osKey)
                                    +$this->getAppleSpend($dateKey,$countryKey,$osKey)
                                    +$this->getProdegeSpend($dateKey,$countryKey,$osKey)
                                    +$this->getAdactionSpend($dateKey,$countryKey,$osKey)
                                    +$this->getMistplaySpend($dateKey,$countryKey,$osKey)
                                ;

                            }
                            else{
                                if(in_array("Facebook", $trackers_group_type )){
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] += $this->getFbSpend($dateKey,$countryKey,$osKey);
                                }
                                if(in_array("Google_ads", $trackers_group_type )){
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] += $this->getGoogleSpend($dateKey,$countryKey,$osKey);
                                }
                                if(in_array("IronSource", $trackers_group_type )){
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] += $this->getIronsourceSpend($dateKey,$countryKey,$osKey);
                                }
                                if(in_array("Unity", $trackers_group_type )){
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] += $this->getUnitySpend($dateKey,$countryKey,$osKey);
                                }
                                if(in_array("Applovin", $trackers_group_type )){
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] += $this->getApplovinSpend($dateKey,$countryKey,$osKey);
                                }
                                if(in_array("Chartboost", $trackers_group_type )){
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] += $this->getChartboostSpend($dateKey,$countryKey,$osKey);
                                }
                                if(in_array("Mintegral", $trackers_group_type )){
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] += $this->getMintegralSpend($dateKey,$countryKey,$osKey);
                                }
                                if(in_array("TikTok", $trackers_group_type )){
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] += $this->getTikTokSpend($dateKey,$countryKey,$osKey);
                                }
                                if(in_array("苹果商店页搜索广告", $trackers_group_type )){
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] += $this->getAppleSpend($dateKey,$countryKey,$osKey);
                                }
                                if(in_array("Prodege", $trackers_group_type )){
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] += $this->getProdegeSpend($dateKey,$countryKey,$osKey);
                                }
                                if(in_array("AdAction", $trackers_group_type )){
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] += $this->getAdactionSpend($dateKey,$countryKey,$osKey);
                                }
                                if(in_array("Mistplay", $trackers_group_type )){
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] += $this->getMistplaySpend($dateKey,$countryKey,$osKey);
                                }
                            }
                        }

                        if(strpos($trackTokenReserve[$trackToken], '网盟')!== false){
                            $wmName = rtrim($trackTokenReserve[$trackToken], '网盟-');
                            $网盟CPI = $cpiList[$wmName] ?? 1;
                            $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] +=$items['kpi_values'][1]*$网盟CPI;
                        }
                    }
                }
            }
        }
        $list = $listNew;
        unset($listNew);
        //合并数据
        if(in_array($type,["month","week"])){
            $out = [];
            foreach($list as $date => $row){
                //$dateTemp = ($type == "week" ? $this->getWeekDate($date) : date("Ym",strtotime($date)));
                $dateTemp = $date;
                foreach($row as $countriesTemp => $rowTwo){
                    foreach($rowTwo as $os_namesTemp => $rowThree){
                        foreach($rowThree as $trackers_group_typeTemp => $vo){
                            if(isset($out[$dateTemp][$countriesTemp][$os_namesTemp][$trackers_group_typeTemp])){
                                //kpi_values []
                                //period_{$time}_kpis []
                                //extension number
                                //extensionRemain number
                                //spend number
                                foreach($periodList as $time){
                                    $temp = $vo["period_{$time}_kpis"];
                                    if(!empty($temp)){
                                        foreach($temp as $tempK => $tempV){
                                            $out[$dateTemp][$countriesTemp][$os_namesTemp][$trackers_group_typeTemp]["period_{$time}_kpis"][$tempK] += $tempV;
                                        }
                                    }
                                }
                                foreach($vo["kpi_values"] as $tempK => $tempV){
                                    $out[$dateTemp][$countriesTemp][$os_namesTemp][$trackers_group_typeTemp]["kpi_values"][$tempK] += $tempV;
                                }
                                $out[$dateTemp][$countriesTemp][$os_namesTemp][$trackers_group_typeTemp]["extension"] += $vo["extension"];
                                $out[$dateTemp][$countriesTemp][$os_namesTemp][$trackers_group_typeTemp]["extensionRemain"] += $vo["extensionRemain"];
                                $out[$dateTemp][$countriesTemp][$os_namesTemp][$trackers_group_typeTemp]["spend"] += $vo["spend"];
                            }else{
                                $out[$dateTemp][$countriesTemp][$os_namesTemp][$trackers_group_typeTemp] = $vo;
                            }
                        }
                    }
                }

            }
            $list = $out;
        }

        if($list){
            oo::commonOprRedis('Statistics')->setex($cacheKey,json_encode($list),600);
        }
        return $list;
    }
    private function getPeriodTimes($type){
        $periodDays = [];
        $max = 0;
        switch ($type){
            case 'week':
                $max = 52;
                break;
            case 'month':
                $max = 13;
                break;
            case 'day':
                $max = 120;
                break;
            default:
                return [];
        }
        for ($i=0;$i<=$max;$i++){
            if($type == 'week'){
                if($i > 1 && $i%4)continue;
            }
            $periodDays[] = $i;
        }
        return $periodDays;
    }
    function getAdjustReportData($stime,$etime,$type,$address,$trackers_group_type,$user_os,$extensionList){
        $paramsKeys = [$stime,$etime,$type,$address,$trackers_group_type,$user_os,$extensionList];
        $cacheKey = '';
        foreach ($paramsKeys as $tmpKey){
            $tmpKey = is_array($tmpKey)?implode('', $tmpKey) : $tmpKey;
            $cacheKey .= $tmpKey;
        }
        $cache = oo::commonOprRedis('Statistics')->get($cacheKey);
        if($cache){
//            return json_decode($cache,1);
        }
        if(!is_array($address)){
            $address = strtolower($address);
            $address = explode(',', $address);
            if(in_array('all', $address))$address = 'all';
            elseif (count($address) == 1)$address = $address[0];
        }

        $where = "";
        if($address && $address != "all"){
            if(is_array($address)){
                $addressTemp = "'".implode("','",$address)."'";
                $where .= " AND countries in ($addressTemp)";
            }else{
                $where .= " AND countries = '{$address}'";
            }
        }
        if(!is_array($trackers_group_type))$trackers_group_type = explode(',', $trackers_group_type);
        if(!in_array('all', $trackers_group_type)){
            $whereTokens = [];
            foreach ($trackers_group_type as $tmpTracker){
                if(empty($this->trackTokens[$tmpTracker]) || !is_array($this->trackTokens[$tmpTracker]))continue;
                $whereTokens = array_unique(array_merge($whereTokens, $this->trackTokens[$tmpTracker]));
            }
            if(!empty($whereTokens)){
                $whereTokensStr = '"'.implode('","', $whereTokens).'"';
                $where .= " AND trackers_channel_token in ({$whereTokensStr})";
            }
        }else{
            $trackers_group_type = ['all'];
        }
        if($user_os && $user_os != "all"){
            $where .= " AND os_names = '{$user_os}'";
        }
        $periodList = $this->getPeriodTimes($type);
        $TAdjust = otable::adjustReport($type);
        if($type == "week"){
            $dateArr = [];
            $stimeTemp = date("Ymd",strtotime($stime));
            $etimeTemp = date("Ymd",strtotime($etime));
            for($timei = $stimeTemp; $timei <= $etimeTemp; $timei = date("Ymd",strtotime($timei." +1 days"))){
                $dateArr[$this->getWeekDate($timei)] = 1;
            }
            $dateKeys = array_keys($dateArr);
            $dateKeysStr = "'".implode("','",$dateKeys)."'";
            $where .= " AND date in({$dateKeysStr})";
        }
        else if($type == "month"){
            $dateArr = [];
            $stimeTemp = date("Ymd",strtotime($stime));
            $etimeTemp = date("Ymd",strtotime($etime));
            for($timei = $stimeTemp; $timei <= $etimeTemp; $timei = date("Ymd",strtotime($timei."+1 days"))){
                $dateArr[$this->getMonthDate($timei)] = 1;
            }
            $dateKeys = array_keys($dateArr);
            $dateKeysStr = "'".implode("','",$dateKeys)."'";
            $where .= " AND date in({$dateKeysStr})";
        }

        $sql = "SELECT * FROM {$TAdjust} WHERE 1=1 {$where} ";
        $TAdjustDataRet = oo::commonOprDb('report')->getAll($sql,1);
        $totalDatas = [];
        foreach ($TAdjustDataRet as $k => $v){
//            $totalDatas[$v['date']] = $totalDatas[$v['date']] ?? [];
//            $kpis = json_decode($v['kpi_values']);
//            $totalDatas[$v['date']]['installs']+=intval($kpis[1]);
            $period = json_decode($v['period_values']);
            foreach ($period as $k1 => $v1){
//                $totalDatas[$v['date']]['remain']+=intval($v1[0]);
                $TAdjustDataRet[$k]["period_{$k1}_kpis"] = json_encode($v1);
            }
        }

        $TAdjustData = [];
        $trackers_group_typeKey = implode(',', $trackers_group_type);
        foreach($TAdjustDataRet as $key => $row){
            $row["kpi_values"] = json_decode($row["kpi_values"],1);
            if(isset($TAdjustData[$row["date"]][$row["countries"]][$row["os_names"]][$row["trackers_channel_token"]])){
                foreach($row["kpi_values"] as $k => $vo){
                    $TAdjustData[$row["date"]][$row["countries"]][$row["os_names"]][$row["trackers_channel_token"]][$k] += $vo;
                }
            }else{
                $TAdjustData[$row["date"]][$row["countries"]][$row["os_names"]][$row["trackers_channel_token"]] = $row["kpi_values"];
            }
        }
        $TAdjustPeriodData = [];
        foreach ($TAdjustDataRet as $key => $row){
            $row["trackers_group_type"] = $trackers_group_typeKey;
            foreach($periodList as $time){
                $row["period_{$time}_kpis"] = json_decode($row["period_{$time}_kpis"],true);
            }
            if(isset($TAdjustPeriodData[$row["date"]][$row["countries"]][$row["os_names"]][$row["trackers_channel_token"]])){
                foreach($periodList as $time){
                    foreach($row["period_{$time}_kpis"] as $k => $vo){
                        $TAdjustPeriodData[$row["date"]][$row["countries"]][$row["os_names"]][$row["trackers_channel_token"]]["period_{$time}_kpis"][$k] += $vo;
                    }
                }
            }else{
                foreach($periodList as $time){
                    $TAdjustPeriodData[$row["date"]][$row["countries"]][$row["os_names"]][$row["trackers_channel_token"]]["period_{$time}_kpis"] = $row["period_{$time}_kpis"];
                }
            }
        }
        $list = [];

        foreach($TAdjustData as $date => $row){
            $extension = $extensionRemain = [];
            foreach($row as $countriesTemp => $rowTwo){
                $countriesTemp2 = $countriesTemp;
                if($address && $address == "all"){
                    $countriesTemp = "all";
                }else if($address && count($address) > 1){
                    $countriesTemp = implode(",",$address);
                }
                if($user_os && $user_os == "all") {
                    $extension[$countriesTemp2] = 0;//推广安装
                    $extensionRemain[$countriesTemp2] = 0;//推广留存人数
                }
                foreach($rowTwo as $os_namesTemp => $rowThree){
                    $os_namesTemp2 = $os_namesTemp;
                    if($user_os && $user_os == "all"){
                        $os_namesTemp = "all";
                    }else{
                        $extension[$countriesTemp2] = 0;//推广安装
                        $extensionRemain[$countriesTemp2] = 0;//推广留存人数
                    }
                    foreach($rowThree as $trackers_group_typeTemp => $vo){
                        if(in_array($trackers_group_typeTemp,$extensionList)){
                            //计算推广安装
                            $extension[$countriesTemp2] += $vo[1];
                            //计算推广留存人数
                            $extensionRemain[$countriesTemp2] += $TAdjustPeriodData[$date][$countriesTemp2][$os_namesTemp2][$trackers_group_typeTemp]["period_1_kpis"][0];
                        }
                    }
                    foreach($rowThree as $trackers_group_typeTemp => $vo){
                        $trackers_group_typeTemp2 = $trackers_group_typeTemp ;//= $trackers_group_typeKey;
                        if($trackers_group_type && $trackers_group_type == "all"){
                            $trackers_group_typeTemp = "all";
                        }

                        if(isset($list[$date][$countriesTemp][$os_namesTemp][$trackers_group_typeTemp])){
                            foreach($vo as $k => $num){
                                $list[$date][$countriesTemp][$os_namesTemp][$trackers_group_typeTemp]["kpi_values"][$k] += $num;
                            }

                            foreach($periodList as $time){
                                $temp = $TAdjustPeriodData[$date][$countriesTemp2][$os_namesTemp2][$trackers_group_typeTemp2]["period_{$time}_kpis"];
                                if(!empty($temp)){
                                    foreach($temp as $tempK => $tempV){
                                        $list[$date][$countriesTemp][$os_namesTemp][$trackers_group_typeTemp]["period_{$time}_kpis"][$tempK] += $tempV;
                                    }
                                }
                            }
                        }else{
                            $list[$date][$countriesTemp][$os_namesTemp][$trackers_group_typeTemp]["kpi_values"] = $vo;
                            foreach($periodList as $time){
                                $list[$date][$countriesTemp][$os_namesTemp][$trackers_group_typeTemp]["period_{$time}_kpis"] = $TAdjustPeriodData[$date][$countriesTemp2][$os_namesTemp2][$trackers_group_typeTemp2]["period_{$time}_kpis"];
                            }
                        }
                    }
                }
            }
        }
        $listNew = [];
        $trackTokenReserve = [];
        foreach ($this->trackTokens as $channel => $tokens){
//            if(in_array($channel, $trackers_group_type))$selectedTokens = array_merge($selectedTokens, (array)$tokens);
            foreach ($tokens as $token){
                $trackTokenReserve[$token] = $channel;
            }
        }
        $网盟CPI = 1;

        $cpiList = oo::commonOprDb('report')->getAll('select * from '.otable::wmcpi());
        $cpiList = array_column($cpiList, 'cpi', 'name');

        foreach ($list as $dateKey => $dateItems){
            foreach ($dateItems as $countryKey => $countryItems){
                foreach ($countryItems as $osKey => $osItems){
                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey] = [
                        'extension' => 0,
                        'extensionRemain' => 0,
                        'kpi_values' => [],
                    ];
                    foreach ($periodList as $i){
                        $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["period_{$i}_kpis"] = [];
                    }
                    foreach ($osItems as $trackToken => $items){
                        foreach ($items['kpi_values'] as $k => $v){
                            if(empty($listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]['kpi_values'][$k]))$listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]['kpi_values'][$k] = 0;
                            $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]['kpi_values'][$k] += $v;
                        }
                        foreach ($periodList as $i){
                            foreach ((array)$items["period_{$i}_kpis"] as $k => $v){
                                if(empty($listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["period_{$i}_kpis"][$k]))
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["period_{$i}_kpis"][$k] = 0;
                                $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["period_{$i}_kpis"][$k] += $v;
                            }
                        }
                        if(in_array($trackTokenReserve[$trackToken], $extensionList)){
                            $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]['extension'] += $items['kpi_values'][1];
                            $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]['extensionRemain'] += $items["period_1_kpis"][0];
                        }

                        if(empty($listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"])){
                            $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] = 0;

                            if(in_array("all", $trackers_group_type )){
                                //fb花费 + google花费 + IronSource花费 + Unity花费
                                $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] +=
                                    $this->getFbSpend($dateKey,$countryKey,$osKey)
                                    +$this->getGoogleSpend($dateKey,$countryKey,$osKey)
                                    +$this->getIronsourceSpend($dateKey,$countryKey,$osKey)
                                    +$this->getUnitySpend($dateKey,$countryKey,$osKey)
                                    +$this->getApplovinSpend($dateKey,$countryKey,$osKey)
                                    +$this->getChartboostSpend($dateKey,$countryKey,$osKey)
                                    +$this->getMintegralSpend($dateKey,$countryKey,$osKey)
                                    +$this->getTikTokSpend($dateKey,$countryKey,$osKey)
                                    +$this->getAppleSpend($dateKey,$countryKey,$osKey)
                                    +$this->getProdegeSpend($dateKey,$countryKey,$osKey)
                                    +$this->getAdactionSpend($dateKey,$countryKey,$osKey)
                                    +$this->getMistplaySpend($dateKey,$countryKey,$osKey)
                                ;

                            }
                            else{
                                if(in_array("Facebook", $trackers_group_type )){
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] += $this->getFbSpend($dateKey,$countryKey,$osKey);
                                }
                                if(in_array("Google_ads", $trackers_group_type )){
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] += $this->getGoogleSpend($dateKey,$countryKey,$osKey);
                                }
                                if(in_array("IronSource", $trackers_group_type )){
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] += $this->getIronsourceSpend($dateKey,$countryKey,$osKey);
                                }
                                if(in_array("Unity", $trackers_group_type )){
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] += $this->getUnitySpend($dateKey,$countryKey,$osKey);
                                }
                                if(in_array("Applovin", $trackers_group_type )){
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] += $this->getApplovinSpend($dateKey,$countryKey,$osKey);
                                }
                                if(in_array("Chartboost", $trackers_group_type )){
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] += $this->getChartboostSpend($dateKey,$countryKey,$osKey);
                                }
                                if(in_array("Mintegral", $trackers_group_type )){
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] += $this->getMintegralSpend($dateKey,$countryKey,$osKey);
                                }
                                if(in_array("TikTok", $trackers_group_type )){
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] += $this->getTikTokSpend($dateKey,$countryKey,$osKey);
                                }
                                if(in_array("苹果商店页搜索广告", $trackers_group_type )){
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] += $this->getAppleSpend($dateKey,$countryKey,$osKey);
                                }
                                if(in_array("Prodege", $trackers_group_type )){
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] += $this->getProdegeSpend($dateKey,$countryKey,$osKey);
                                }
                                if(in_array("AdAction", $trackers_group_type )){
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] += $this->getAdactionSpend($dateKey,$countryKey,$osKey);
                                }
                                if(in_array("Mistplay", $trackers_group_type )){
                                    $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] += $this->getMistplaySpend($dateKey,$countryKey,$osKey);
                                }
                            }
                        }

                        if(strpos($trackTokenReserve[$trackToken], '网盟')!== false){
                            $wmName = rtrim($trackTokenReserve[$trackToken], '网盟-');
                            $网盟CPI = $cpiList[$wmName] ?? 1;
                            $listNew[$dateKey][$countryKey][$osKey][$trackers_group_typeKey]["spend"] +=$items['kpi_values'][1]*$网盟CPI;
                        }

                    }
                }
            }
        }
        $list = $listNew;
        unset($listNew);

        $rows = [];
        $validSpend = 0;
        $typeText = '';
        switch ($type){
            case 'day':$typeText = '日';break;
            case 'month':$typeText = '月';break;
            case 'week':$typeText = '周';break;
            default: return [];
        }
        foreach($list as $date => $countryMap) {
            if($type == 'day') $date = date('Ymd', strtotime($date));
            $rows[$date] = [];
            foreach ($countryMap as $country => $osMap) {
                foreach ($osMap as $os => $channelMap) {
                    foreach ($channelMap as $channel => $row) {
                        $extensionRemain = $row["extensionRemain"];//推广
                        $extension = $row["extension"] ;
                        $naturalRemain = $row["period_1_kpis"][0] - $row["extensionRemain"];//自然
                        $natural = $row["kpi_values"][1] - $row["extension"];
                        $naturalRate = number_format(($natural / $row["kpi_values"][1]) * 100, 2);
                        $tmp = [
                            '日期' => $date,
                            '国家' => $country,
                            '版本' => $os,
                            '广告渠道' => $channel,
                            'DAU' => round($row["kpi_values"][0]) ?? 0,
                            '花费$' => number_format($row["spend"],2,".","") ?? 0,
                            '总安装' => $row["kpi_values"][1] ?? 0,
                            '推广安装' => $extension,
                            '自然量安装' => $natural,
                            '自然量占比' => $naturalRate . '%',
                            '买量CPI$' => empty($extension) ? '' : number_format($row["spend"] / $extension,2,".","") ?? "",
                            '均价CPI$' => empty($row["kpi_values"][1]) ? '' : number_format($row["spend"] / $row["kpi_values"][1],2,".","") ?? "",
//                            '推广次留' => empty($extension) ? '' : number_format($extensionRemain / $extension * 100,2,".","")."%" ?? '',
//                            '自然量次留' => empty($natural) ? '' : number_format($naturalRemain / $natural * 100,2,".","")."%" ?? '',
                        ];
                        $月留存7 = empty($row["kpi_values"][1]) ? 0 :$row["period_6_kpis"][0] / $row["kpi_values"][1];
                        $roi7 = empty($row["spend"]) ? 0 :$row["period_6_kpis"][2] * $this->fcce / $row["spend"];
                        foreach ($periodList as $time){
                            $key = empty($time) ? "首{$typeText}留存" : $time+1 ."{$typeText}留存";;
                            $tmp[$key] = empty($row["kpi_values"][1]) ? '' : number_format($row["period_{$time}_kpis"][0] / $row["kpi_values"][1] * 100,2,".","")."%" ?? '';

                            $key = empty($time) ? "首{$typeText}留存人数" : $time+1 ."{$typeText}留存人数";;
                            $tmp[$key] = intval($row["period_{$time}_kpis"][0]);
                        }
                        $tmp['付费人数'] = $row["period_0_kpis"][1] ?? 0;;
                        $tmp['付费率'] = empty($row["kpi_values"][1]) ? '' : number_format($row["period_0_kpis"][1] / $row["kpi_values"][1] * 100,2,".","")."%" ?? '';;
                        $tmp["当{$typeText}ARPU"] = empty($row["kpi_values"][1]) ? '' : number_format($row["period_0_kpis"][2] / $row["kpi_values"][1],2,".","") ?? '';;
                        $tmp["当{$typeText}ARPPU"] = empty($row["period_0_kpis"][1]) ? '' : number_format($row["period_0_kpis"][2] / $row["period_0_kpis"][1],2,".","") ?? '';;
                        foreach ($periodList as $time){
                            $key = empty($time) ? "首{$typeText}内购ROI" : $time+1 ."{$typeText}内购ROI";
                            $tmp[$key] = empty($row["spend"]) ? '' : number_format($row["period_{$time}_kpis"][2] * $this->fcce / $row["spend"] * 100,2,".","")."%" ?? '';

                            $key = empty($time) ? "首{$typeText}付费人数" : $time+1 ."{$typeText}付费人数";
                            $tmp[$key] = $row["period_{$time}_kpis"][3];
                        }
                        $tmp['内购收入'] =     number_format($row["kpi_values"][2],2,".","") ?? 0; ;
                        $tmp['分成后总收入'] = number_format($row["kpi_values"][2] * $this->fcce,2,".","") ?? 0;;
                        foreach ($periodList as $time){
                            $key = empty($time) ? "首{$typeText}内购收入" : $time+1 ."{$typeText}内购收入";
                            $tmp[$key] = number_format($row["period_{$time}_kpis"][2],2,".","") ?? 0;

//                            内购ltvX=第X天同期群付费金额/同期群安装人数
                            $key = empty($time) ? "首{$typeText}内购LTV" :  "{$time}{$typeText}内购LTV";
                            $tmp[$key] = empty($row["kpi_values"][1]) ? '' : number_format($row["period_{$time}_kpis"][2]/$row["kpi_values"][1],2,".","");

//                            内购付费LTVX=第X天同期群付费金额/第X天同期群付费人数
                            $key = empty($time) ? "首{$typeText}内购付费LTV" : $time+1 ."{$typeText}内购付费LTV";
                            $tmp[$key] = empty($row["period_{$time}_kpis"][3]) ? '' : number_format($row["period_{$time}_kpis"][2]/$row["period_{$time}_kpis"][3],2,".","");

                        }
//                        $tmp['推广次留用户数'] = $extensionRemain;
//                        $tmp['自然次留用户数'] = $naturalRemain;
                        $tmp['AE']  = $this->getAE($月留存7, $roi7);
                        $tmp['AEA'] = number_format($this->getAE($月留存7, $roi7) * $row["spend"], 2, '.', '');
                        if(in_array($trackers_group_type,['Tecdo','Inplayable'])){
                            $tmp['花费$'] = $tmp['总安装'] * 3;
                        }
                        $ce = $this->getCE($tmp['AE']);
                        $validSpend += $ce * $tmp['花费$'];
//                        echo json_encode($tmp);die;
//                        $tmp['有效投放金额(累计)'] = number_format($validSpend, 2, '.','');
//                        $tmp['合格系数'] = $ce;
                        $rows[$date][] = $tmp;
                    }
                }
            }
        }
        unset($list);
        if($rows){
            oo::commonOprRedis('Statistics')->setex($cacheKey,json_encode($rows),600);
        }
        return $rows;
    }

    //获取fb素材数据
    function getFbAdSourceData($stime,$etime,$address,$trackers_group_type,$user_os,$campaign_id,$adset_id,$ad_id,$periodList){
        $cacheKey = $stime."-".$etime."-".$address."-".$trackers_group_type."-".$user_os."-".$campaign_id."-".$adset_id."-".$ad_id;
        $cache = oo::commonOprRedis('Statistics')->get($cacheKey);
        if($cache){
//            return json_decode($cache,1);
        }
        //adjust数据
        $TAdjustPeriodView = otable::TAdjustPeriodView();
        $where = "";

        $where .= " AND trackers_group_type = 'Facebook'";
//        if($trackers_group_type && $trackers_group_type != "all"){
//            $trackers_group_type == "Facebook" && $where .= " AND trackers_group_type = 'Facebook'";
//        }
        /*
        //地区规则 因为fb跟adjust归因不同，所以要注释掉
        if($address && $address != "all"){
            if(is_array($address)){
                $addressTemp = "'".implode("','",$address)."'";
                $where .= " AND countries in($addressTemp)";
            }else{
                $where .= " AND countries = '{$address}'";
            }
        }
        */
        if($user_os && $user_os != "all"){
            $where .= " AND os_names = '{$user_os}'";
        }
        if($campaign_id && $campaign_id != "all"){
            $where .= " AND campaigns_id = '{$campaign_id}'";
        }
        if($adset_id && $adset_id != "all"){
            $where .= " AND adgroups_id = '{$adset_id}'";
        }
        if($ad_id && $ad_id != "all"){
            $where .= " AND creatives_id = '{$ad_id}'";
        }
        $sql = "SELECT * FROM {$TAdjustPeriodView} WHERE date >= '{$stime}' AND date <= '{$etime}' {$where}";
//        echo $sql.PHP_EOL;
        $ajustPeriodData = oo::commonOprDb('report')->getAll($sql,1);
        //计算出渠道 & 留存人数 跟 留存都是取这里的
        $adjustData = [];//0 date 1 ad_id
        foreach($ajustPeriodData as $row){
            foreach($periodList as $time){
                $row["period_{$time}_kpis"] = json_decode($row["period_{$time}_kpis"],true);
            }
            $row["kpi_values"] = json_decode($row["kpi_values"],true);
            $date = date("Ymd",strtotime($row["date"]));
//            if(isset($adjustData[$date][$row["creatives_id"]])){
//                //fb渠道相加
//                foreach($periodList as $time){
//                    foreach($row["period_{$time}_kpis"] as $key => $num){
//                        $adjustData[$date][$row["creatives_id"]]["period_{$time}_kpis"][$key] += $num;
//                    }
//                }
//            }else{
//                $adjustData[$date][$row["creatives_id"]] = $row;
//            }
            $adjustData[$date][$row["creatives_id"]][] = $row;
        }
        //广告成本数据（广告详情表）
        $facebookAdsTb = otable::facebookAds();
        $where = "";
        if($address && $address != "all"){
            if(is_array($address)){
                $addressTemp = [];
                foreach($address as $addr){
                    $addressTemp[] = strtoupper($addr);
                }
                $addressTemp = "'".implode("','",$addressTemp)."'";
                $where .= " AND country in($addressTemp)";
            }else{
                $addressTemp = strtoupper($address);
                $where .= " AND country = '{$addressTemp}'";
            }
        }

        if($user_os && $user_os != "all"){
            switch ($user_os){
                case 'android':
                    $where .= " AND campaign_name like '%and%'";
                    break;
                case 'ios':
                    $where .= " AND campaign_name like '%ios%'";
                    break;
            }

        }
        if($campaign_id && $campaign_id != "all"){
            $where .= " AND campaign_id = '{$campaign_id}'";
        }
        if($adset_id && $adset_id != "all"){
            $where .= " AND adset_id = '{$adset_id}'";
        }
        if($ad_id && $ad_id != "all"){
            $where .= " AND ad_id = '{$ad_id}'";
        }
        $sql = "SELECT * FROM {$facebookAdsTb} WHERE date_start >= '{$stime}' AND date_start <= '{$etime}' {$where}";
        $facebookAdsData = oo::commonOprDb('report')->getAll($sql,1);
        $ads = [];
        foreach($facebookAdsData as $row){
            $date = date("Ymd", strtotime($row['date_start']));
            $ad_id_temp = $row["ad_id"];
            $adset_id_temp = $row["adset_id"];
            $country = $row["country"];
            $row["user_os"] = "";

            //筛选出最大的地区值
//            $address_max = 0;
//            $percent = 0.1;
//            foreach($adjustData[$date][$ad_id_temp] as $vo){
//                if($user_os && $user_os != "all" && $vo["os_names"] != $user_os){
//                    continue;
//                }
//                if(strtolower($country) == strtolower($vo["countries"]) && $vo["campaigns_id"] == $row["campaign_id"] && $vo["adgroups_id"] == $row["adset_id"] && $vo["creatives_id"] == $row["ad_id"]){
//                    $address_max += $vo["kpi_values"][1] * $percent;
//                }
//            }
            foreach($adjustData[$date][$ad_id_temp] as $adk => $vo){
                if($user_os && $user_os != "all" && $vo["os_names"] != $user_os){
                    continue;
                }
//                $is_address = false;
//                if($vo["kpi_values"][1] && $vo["kpi_values"][1] <= $address_max){
//                    $is_address = true;
//                }
//                if(
//                    ($is_address || strtolower($country) == strtolower($vo["countries"]))
//                    && $vo["campaigns_id"] == $row["campaign_id"]
//                    && $vo["adgroups_id"] == $row["adset_id"]
//                    && $vo["creatives_id"] == $row["ad_id"]){
                if(
                    strtolower($country) == strtolower($vo["countries"])
                    && $vo["campaigns_id"] == $row["campaign_id"]
                    && $vo["adgroups_id"] == $row["adset_id"]
                    && $vo["creatives_id"] == $row["ad_id"]
                ) {
                    if (strtolower($country) == strtolower($vo["countries"])) {
                        foreach ([0, 1, 2, 6, 14, 29] as $time) {
                            if (isset($row["period_{$time}_kpis"])) {
                                foreach ($vo["period_{$time}_kpis"] as $k => $num) {
                                    $row["period_{$time}_kpis"][$k] += $num;
                                }
                            } else {
                                $row["period_{$time}_kpis"] = $vo["period_{$time}_kpis"] ?? [];
                            }
                        }
                        if (isset($row["kpi_values"])) {
                            foreach ($vo["kpi_values"] as $k => $num) {
                                $row["kpi_values"][$k] += $num;
                            }
                        } else {
                            $row["kpi_values"] = $vo["kpi_values"];
                        }

                        $row["user_os"] = $vo["os_names"];
                    }
                    unset($adjustData[$date][$ad_id_temp][$adk]);
                }
            }
            $row["ad_name"] = strtolower($row["ad_name"]);
            $row["adset_name"] = strtolower($row["adset_name"]);
            $row["campaign_name"] = strtolower($row["campaign_name"]);
            if(empty($row["user_os"])){
                if(strpos($row["campaign_name"],'and') !== false){
                    $row["user_os"] = "android";
                }else if(strpos($row["campaign_name"],'ios') !== false){
                    $row["user_os"] = "ios";
                }
            }
            $ads[$date][] = $row;
        }
//        $cnt = 0;
//        $install = 0;
//        echo json_encode($adjustData);
        foreach ($adjustData as $date => $dateItems){
            foreach ($dateItems as $adItems){
                foreach ($adItems as $row){
//                    $cnt++;
//                    $install += intval($row['kpi_values'][1]);
                    $row['campaign_id'] = $row['campaigns_id'];
                    $row['adset_id'] = $row['adgroups_id'];
                    $row['ad_id'] = $row['creatives_id'];

                    $row['campaign_name'] = $row['campaigns_name'];
                    $row['adset_name'] = $row['adgroups_name'];
                    $row['ad_name'] = $row['creatives_name'];
                    $row['user_os'] = $row['os_names'];
                    $row['attribution_setting'] = 'attribution_setting';
                    $ads[$date][] = $row;
                }
            }
        }
//        echo $cnt . '<br>';
//        echo $install . '<br>';
        //不同国家 同一系列、广告组、广告合并
        $list = [];
        is_array($address) ? $country = implode(",",$address) : $country = $address;
        foreach($ads as $date => $row){
            foreach($row as $vo){
                if(isset($list[$date][$country][$vo["campaign_id"]][$vo["adset_id"]][$vo["ad_id"]][$vo["user_os"]][$vo["attribution_setting"]])){
                    foreach(['clicks','impressions','inline_link_clicks','reach','spend','cpc','link_click','app_install','mobile_app_install','three_sec_video_view','video_play_actions',
                                'video_avg_time_watched_actions','video_p25_watched_actions','video_p50_watched_actions','video_p75_watched_actions',
                                'video_p95_watched_actions','video_p100_watched_actions','impression_device','video_15_sec_watched_actions'] as $name){
                        $list[$date][$country][$vo["campaign_id"]][$vo["adset_id"]][$vo["ad_id"]][$vo["user_os"]][$vo["attribution_setting"]][$name] += $vo[$name];
                    }
                    foreach($vo["kpi_values"] as $k => $num){
                        $list[$date][$country][$vo["campaign_id"]][$vo["adset_id"]][$vo["ad_id"]][$vo["user_os"]][$vo["attribution_setting"]]["kpi_values"][$k] += $num;
                    }
                    foreach([0,1,2,6,14,29] as $time){
                        foreach($vo["period_{$time}_kpis"] as $k => $num){
                            $list[$date][$country][$vo["campaign_id"]][$vo["adset_id"]][$vo["ad_id"]][$vo["user_os"]][$vo["attribution_setting"]]["period_{$time}_kpis"][$k] += $num;
                        }
                    }
                }else{
                    $list[$date][$country][$vo["campaign_id"]][$vo["adset_id"]][$vo["ad_id"]][$vo["user_os"]][$vo["attribution_setting"]] = $vo;
                }
            }
        }
        $ads = [];
        foreach($list as $date => $row){
            foreach($row as $country => $rowTwo){
                foreach($rowTwo as $campaign_id_temp => $rowThree){
                    foreach($rowThree as $adset_id_temp => $rowFour){
                        foreach($rowFour as $ad_id_temp => $rowFive){
                            foreach($rowFive as $user_os_temp => $rowSix){
                                foreach($rowSix as $attribution_setting_temp => $vo){
                                    //因为后面用到排序，所以country，user_os，campaign_name，adset_name，ad_name
                                    $temp = [
                                        '国家'=>$country,
                                        '版本'=>$vo["user_os"],
                                        '广告系列'=>$vo["campaign_name"],
                                        '广告组'=>$vo["adset_name"],
                                        '广告'=>$vo["ad_name"],
                                        '广告成本'=>number_format($vo["spend"],2,".",""),
                                        '广告平台安装'=>$vo["mobile_app_install"],
                                        '推广CPI'=>empty($vo["mobile_app_install"]) ? '0' : number_format(($vo["spend"] / $vo["mobile_app_install"]) ?? '',2,".",""),//推广CPI 推广CPI=广告成本/推广安装
                                        '推广次留CPI'=>empty($vo["mobile_app_install"]) || empty($vo["period_1_kpis"][0]) ? '' :number_format((($vo["spend"] / $vo["mobile_app_install"]) / ($vo["period_1_kpis"][0] / $vo["mobile_app_install"])) ?? '',2,".",""),//推广次留CPI 推广次留CPI=推广CPI/次日留存
                                        'Adjust安装'=>$vo["kpi_values"][1],
                                        'Adjust CPI'=>empty($vo["period_1_kpis"][0]) ? '0' : number_format(($vo["spend"] / $vo["kpi_values"][1]) ?? '',2,".",""),
                                        '次日留存'=>empty($vo["kpi_values"][1]) ? '0' : number_format($vo["period_1_kpis"][0] / $vo["kpi_values"][1] * 100 ?? '',2,".","")."%",
                                        '3日留存'=>empty($vo["kpi_values"][1]) ? '0' : number_format($vo["period_2_kpis"][0] / $vo["kpi_values"][1] * 100 ?? '',2,".","")."%",
                                        '7日留存'=>empty($vo["kpi_values"][1]) ? '0' : number_format($vo["period_6_kpis"][0] / $vo["kpi_values"][1] * 100 ?? '',2,".","")."%",
                                        '次日留存人数'=>empty($vo["period_1_kpis"][0]) ? 0 : $vo["period_1_kpis"][0],
                                        '3日留存人数'=>empty($vo["period_2_kpis"][0]) ? 0 : $vo["period_2_kpis"][0],
                                        '7日留存人数'=>empty($vo["period_6_kpis"][0]) ? 0 : $vo["period_6_kpis"][0],
                                        '点击率(CTR)'=>empty($vo["impressions"]) ? '0' : number_format($vo["link_click"] / $vo["impressions"] * 100 ?? '',2,".","")."%",//CTR=链接点击数/展示次数
                                        '转化率(CVR)'=>empty($vo["link_click"]) ? '0' : number_format($vo["mobile_app_install"] / $vo["link_click"] * 100 ?? '',2,".","")."%",//CVR=推广安装/链接点击数
                                        '成效率(RR)'=>empty($vo["impressions"]) ? '0' : number_format($vo["mobile_app_install"] / $vo["impressions"] * 100 ?? '',2,".","")."%",//RR=点击率x转化率，或 推广安装除以展示次数
                                        '每千次展示费用(CPM)'=>empty($vo["impressions"]) ? '0' : number_format($vo["spend"] / $vo["impressions"]*1000 ?? '',2,".",""),//CPM=广告成本/展示次数X1000
                                        '覆盖人数'=>empty($vo["reach"]) ? 0 : $vo["reach"],
                                        '展示次数'=>empty($vo["impressions"]) ? 0 : $vo["impressions"],
                                        '链接点击数'=>empty($vo["link_click"]) ? 0 : $vo["link_click"],
                                        '视频平均观看时长(s)'=>empty($vo["video_avg_time_watched_actions"]) ? 0 : $vo["video_avg_time_watched_actions"],
                                        '视频播放次数'=>empty($vo["video_play_actions"]) ? 0 : $vo["video_play_actions"],
                                        '视频前3秒播放次数'=>empty($vo["three_sec_video_view"]) ? 0 : $vo["three_sec_video_view"],
                                        '视频25%处播放次数'=>empty($vo["video_p25_watched_actions"]) ? 0 : $vo["video_p25_watched_actions"],
                                        '视频50%处播放次数'=>empty($vo["video_p50_watched_actions"]) ? 0 : $vo["video_p50_watched_actions"],
                                        '视频15s处播放次数'=>empty($vo["video_15_sec_watched_actions"]) ? 0 : $vo["video_15_sec_watched_actions"],
                                        '视频75%处播放次数'=>empty($vo["video_p75_watched_actions"]) ? 0 : $vo["video_p75_watched_actions"],
                                        '视频95%处播放次数'=>empty($vo["video_p95_watched_actions"]) ? 0 : $vo["video_p95_watched_actions"],
                                        '视频100%处播放次数'=>empty($vo["video_p100_watched_actions"]) ? 0 : $vo["video_p100_watched_actions"],
                                        '视频总观看时长(s)'=>$vo["video_avg_time_watched_actions"]*$vo["video_play_actions"],
                                        '首日内购ROI'=>empty($vo["spend"]) ? '0' : number_format($vo["period_0_kpis"][2] / $vo["spend"] * 100 ?? '',2,".","")."%",
                                        '3日内购ROI'=>empty($vo["spend"]) ? '0' : number_format($vo["period_2_kpis"][2] / $vo["spend"] * 100 ?? '',2,".","")."%",
                                        '7日内购ROI'=>empty($vo["spend"]) ? '0' : number_format($vo["period_6_kpis"][2] / $vo["spend"] * 100 ?? '',2,".","")."%",
                                        '15日内购ROI'=>empty($vo["spend"]) ? '0' : number_format($vo["period_14_kpis"][2] / $vo["spend"] * 100 ?? '',2,".","")."%",
                                        '30日内购ROI'=>empty($vo["spend"]) ? '0' : number_format($vo["period_29_kpis"][2] / $vo["spend"] * 100 ?? '',2,".","")."%",
                                        '首日内购收入'=>number_format($vo["period_0_kpis"][2],2,".",""),
                                        '3日内购收入'=>number_format($vo["period_2_kpis"][2],2,".",""),
                                        '7日内购收入'=>number_format($vo["period_6_kpis"][2],2,".",""),
                                        '15日内购收入'=>number_format($vo["period_14_kpis"][2],2,".",""),
                                        '30日内购收入'=>number_format($vo["period_29_kpis"][2],2,".",""),
                                        '账户ID'=> $vo['account_id'],
                                    ];
                                    $ads[$date][] = $temp;
                                }
                            }
                        }
                    }
                }
            }
        }
        if($ads){
            oo::commonOprRedis('Statistics')->setex($cacheKey,json_encode($ads),60);
        }
        return $ads;
    }

    //获取adjust日报明细数据
    function getDayReportViewData($stime,$etime,$address,$trackers_group_type,$user_os,$campaign_id,$adset_id,$ad_id,$sort){
        $cacheKey = "getDayReportViewData-".$stime."-".$etime."-".$address."-".$trackers_group_type."-".$user_os."-".$campaign_id."-".$adset_id."-".$ad_id."-".$sort;
        $cache = oo::commonOprRedis('Statistics')->get($cacheKey);
        if($cache){
            //return json_decode($cache,1);
        }
        $fbData = [];
        switch ($trackers_group_type){
            case 'all':
            case 'Facebook':
                $fbData = $this->getFbSpendData($stime,$etime,$address,$user_os,$campaign_id,$adset_id,$ad_id);
                break;
            case 'Google_ads':
            case 'IronSource':
            case 'Unity':
            case 'Applovin':
            case 'Chartboost':
            case 'Mintegral':
                $fbData = $this->getOtherSpendData($stime,$etime,$address,$user_os,$trackers_group_type,$campaign_id);
                break;
            case 'TikTok':
                $fbData = $this->getTikTokSpendData($stime,$etime,$address,$user_os,$campaign_id,$adset_id,$ad_id);
                break;
            case '苹果商店页搜索广告':
                $ad_id = 'all';
                $fbData = $this->getAppleSpendData($stime,$etime,$address,$user_os,$campaign_id,$adset_id,$ad_id);
                break;
        }
        $where = "";
        if($trackers_group_type && $trackers_group_type != "all"){
            $where .= " AND trackers_group_type = '{$trackers_group_type}'";
        }
        if($address && $address != "all"){
            if(is_array($address)){
                $addressTemp = "'".implode("','",$address)."'";
                $where .= " AND countries in($addressTemp)";
            }else{
                $where .= " AND countries = '{$address}'";
            }
        }
        if($user_os && $user_os != "all"){
            $where .= " AND os_names = '{$user_os}'";
        }
        if($campaign_id && $campaign_id != "all" && in_array($trackers_group_type,["Facebook","Google_ads","TikTok", '苹果商店页搜索广告'])){
            $where .= " AND campaigns_id = '{$campaign_id}'";
        }
        if($campaign_id && $campaign_id != "all" && in_array($trackers_group_type,["IronSource","Unity"])){
            $where .= " AND campaigns_name = '{$campaign_id}'";
        }
        if($adset_id && $adset_id != "all"){
            if(in_array($trackers_group_type, ['Google_ads', 'Mintegral'])){
                $where .= " AND adgroups_name = '{$adset_id}'";
            }else{
                $where .= " AND adgroups_id = '{$adset_id}'";
            }
        }
        if($ad_id && $ad_id != "all"){
            $where .= " AND creatives_id = '{$ad_id}'";
        }
        if($trackers_group_type == "Facebook"){
            $where .= " AND creatives_id <> ''";
        }
        $tb = otable::TAdjustPeriodView($trackers_group_type);
        $sql = "SELECT * FROM {$tb} WHERE date >= '{$stime}' AND date <= '{$etime}' {$where}";
        $ret = oo::commonOprDb('report')->getAll($sql,1);
        $periodList = [0,1,2,6,14,29,59,89,119];
        if(in_array($trackers_group_type, ['Google_ads','Mintegral','苹果商店页搜索广告'])){
            $formatData = [];
            foreach ($ret as $row){

                if($trackers_group_type == 'Google_ads')$row["countries"] = 'all';
                if($trackers_group_type == 'Mintegral'){
                    $row["campaigns_id"] = $row['campaigns_name'];
                    $row["adgroups_id"] = $row['adgroups_name'];
                }
                if(in_array($trackers_group_type , ['Google_ads','Mintegral','苹果商店页搜索广告']))$row["creatives_name"] = 'all';

                $key = $row['campaigns_id'] . '|' . $row['adgroups_name']. '|' . $row['date']. '|' . $row['os_names']. '|' . $row['countries'];
                $row["kpi_values"] = json_decode($row["kpi_values"],true);
                foreach($periodList as $time){
                    $row["period_{$time}_kpis"] = json_decode($row["period_{$time}_kpis"],true);
                }
                if(empty($formatData[$key])){
                    $formatData[$key] = $formatData[$key] ?? $row;
                }else{
                    foreach($periodList as $time){
                        foreach($row["period_{$time}_kpis"] as $k => $num){
                            $formatData[$key]["period_{$time}_kpis"][$k] += $num;
                        }
                    }
                    foreach ($row['kpi_values'] as $k => $num){
                        $formatData[$key]["kpi_values"][$k] += $num;
                    }
                }
            }
            $ret = array_values($formatData);
            unset($formatData);
        }
        $list = [];
        //合并数据
        $sumArr = [];
        foreach($ret as $row){
            $date = $row["date"];
            if(!is_array($row["kpi_values"]))$row["kpi_values"] = json_decode($row["kpi_values"],true);
            foreach($periodList as $time){
                if(!is_array($row["period_{$time}_kpis"]))$row["period_{$time}_kpis"] = json_decode($row["period_{$time}_kpis"],true);
            }
            if(isset($sumArr[$date][$row["os_names"]][$row["countries"]][$row["trackers_group_type"]][$row["campaigns_name"]][$row["adgroups_name"]][$row["creatives_name"]])){
                foreach($row["kpi_values"] as $k => $num){
                    $sumArr[$date][$row["os_names"]][$row["countries"]][$row["trackers_group_type"]][$row["campaigns_name"]][$row["adgroups_name"]][$row["creatives_name"]]["kpi_values"][$k] += $num;
                }
                foreach($periodList as $time){
                    foreach($row["period_{$time}_kpis"] as $k => $num){
                        $sumArr[$date][$row["os_names"]][$row["countries"]][$row["trackers_group_type"]][$row["campaigns_name"]][$row["adgroups_name"]][$row["creatives_name"]]["period_{$time}_kpis"][$k] += $num;
                    }
                }
            }else{
                $sumArr[$date][$row["os_names"]][$row["countries"]][$row["trackers_group_type"]][$row["campaigns_name"]][$row["adgroups_name"]][$row["creatives_name"]] = $row;
            }

        }
        $ret = [];
        foreach($sumArr as $date => $row){
            foreach($row as $os_namesTemp => $row2){
                foreach($row2 as $countriesTemp => $row3){
                    foreach($row3 as $trackers_group_typeTemp => $row4){
                        foreach($row4 as $campaigns_nameTemp => $row5){
                            foreach($row5 as $adgroups_nameTemp => $row6){
                                foreach($row6 as $creatives_nameTemp => $vo){
                                    $ret[] = $vo;
                                }
                            }
                        }
                    }
                }
            }
        }
        foreach($ret as $row){
            $date = $row["date"];
//            $row["kpi_values"] = json_decode($row["kpi_values"],true);
//            foreach($periodList as $time){
//                $row["period_{$time}_kpis"] = json_decode($row["period_{$time}_kpis"],true);
//            }
            $temp = [
                "版本"=>$row["os_names"],
                "国家"=>$row["countries"],
                "广告渠道"=>$row["trackers_group_type"],
                '广告系列'=>$row["campaigns_name"],
                '广告组'=>$row["adgroups_name"],
                '广告名'=>$row["creatives_name"],
                "广告成本"=>0,//广告成本
                "Adjust安装"=>$row["kpi_values"][1],//推广安装
            ];
            if($row["trackers_group_type"] == "Facebook"){
                foreach($fbData[$date][$row["creatives_id"]] as $vo){
                    if(
                        strtolower($row["countries"] == strtolower($vo["country"])) &&
                        $row["campaigns_id"] == $vo["campaign_id"] &&
                        $row["adgroups_id"] == $vo["adset_id"] &&
                        $row["creatives_id"] == $vo["ad_id"]
                    ){
                        $temp["广告成本"] = $vo["spend"];
                    }
                }
            }else if($row["trackers_group_type"] == "苹果商店页搜索广告"){
                foreach($fbData[$date][$row["adgroups_id"]] as $vo){
                    if(
                        strtolower($row["countries"] == strtolower($vo["country"])) &&
                        $row["campaigns_id"] == $vo["campain_id"] &&
                        $row["adgroups_id"] == $vo["adgroup_id"]
                    ){
                        $temp["广告成本"] = $vo["spend"];
                    }
                }
            }else if($row["trackers_group_type"] == "TikTok"){
                foreach($fbData[$date][$row["creatives_id"]] as $vo){
                    if(
                        strtolower($row["countries"] == strtolower($vo["country"])) &&
                        $row["campaigns_id"] == $vo["campain_id"] &&
                        $row["adgroups_id"] == $vo["adgroup_id"] &&
                        $row["creatives_id"] == $vo["ad_id"]
                    ){
                        $temp["广告成本"] = $vo["spend"];
                    }
                }
            }else if($row["trackers_group_type"] == "Google_ads"){
                foreach($fbData[$date][$row["campaigns_id"]] as $vo){
                    if(
                        $row["campaigns_id"] == $vo["campaign_id"]
                        && $row["os_names"] == $vo['user_os']
                        && ($row["adgroups_id"] == $vo['ad_group_id'] || $row["adgroups_name"] == $vo['ad_group_id'])
                    ){
                        $tmpAdGroupName = $vo['ad_group_name'];
                        $temp["广告成本"] += $vo["spend"];
                    }
                }
            }else if($row["trackers_group_type"] == "Mintegral"){
                foreach($fbData[$date][$row["campaigns_id"]] as $vo){
                    if(
                        $row["campaigns_id"] == $vo["id"]
                        && strtolower($row["countries"] == strtolower($vo["country"]))
                        && $row["os_names"] == $vo['user_os']
                        && $row["adgroups_name"] == $vo['ad_group_id']
                    ){
                        $tmpAdGroupName = $vo['ad_group_name'];
                        $temp["广告成本"] += $vo["spend"];
                    }
                }
            }else if($row["trackers_group_type"] == "Unity"){
                foreach($fbData[$date][$row["campaigns_name"]] as $vo){
                    if(strtolower($row["countries"] == strtolower($vo["country"])) && $row["campaigns_name"] == $vo["name"] && $row["os_names"] == $vo["user_os"]){
                        $temp["广告成本"] += $vo["spend"];
                    }
                }
            }else if($row["trackers_group_type"] == "IronSource"){
                $number = explode("_",$row["campaigns_name"]);
                $campaigns_id_temp = substr($row["campaigns_name"],0,strpos($row["campaigns_name"],'_'.end($number)));
                foreach($fbData[$date][$campaigns_id_temp] as $vo){
                    if(strtolower($row["countries"] == strtolower($vo["country"])) && strpos($row["campaigns_name"],$vo["name"]) !== false && strpos($row["campaigns_name"],$vo["id"]) !== false && $row["os_names"] == $vo["user_os"]){
                        $temp["广告成本"] += $vo["spend"];
                    }
                }
            }else if($row["trackers_group_type"] == "Applovin" ){
                list($campaigns_name,$campaigns_id) = explode(" ",$row["campaigns_name"]);
                foreach($fbData[$date][$campaigns_name] as $vo){
                    if(
                        strtolower($row["countries"] == strtolower($vo["country"]))
                        && strpos($row["campaigns_name"],$vo["name"]) !== false
                        && strpos($row["campaigns_name"],$vo["id"]) !== false
                        && $row["os_names"] == $vo["user_os"]
                    ){
                        $temp["广告成本"] += $vo["spend"];
                    }
                }
            }else if($row["trackers_group_type"] == "Chartboost" ){
//                list($campaigns_name,$campaigns_id) = explode(" ",$row["campaigns_name"]);
                foreach($fbData[$date][$row['campaigns_name']] as $vo){
                    if(
                        strtolower($row["countries"] == strtolower($vo["country"]))
                        && strpos($row["campaigns_name"],$vo["name"]) !== false
//                        && strpos($row["campaigns_name"],$vo["id"]) !== false
                        && $row["os_names"] == $vo["user_os"]
                    ){
                        $temp["广告成本"] += $vo["spend"];
                    }
                }
            }

            $temp['广告组'] = $tmpAdGroupName ?? $temp['广告组'];
            $temp["推广CPI"] = empty($temp["Adjust安装"]) ?  '' : number_format($temp["广告成本"]/$temp["Adjust安装"],2,".","");//推广CPI=广告成本/推广安装
            $second_stay = empty($temp["Adjust安装"]) ? "" : number_format($row["period_1_kpis"][0]/$temp["Adjust安装"]*100,2,".","");//次留=次日留存人数/安装
//            $temp["推广次留CPI"] = empty($second_stay) ? "" : number_format($temp["推广CPI"]/$second_stay,2,".","");//推广次留CPI=推广CPI/推广次留
            $temp["推广次留CPI"] = empty($row["period_1_kpis"][0]) ? "" : number_format($temp["广告成本"]/$row["period_1_kpis"][0],2,".","");//推广次留CPI=广告成本/次日留存人数
            $temp["次日留存"] = empty($second_stay) ? "" : $second_stay."%";//次留=次日留存人数/安装
            $temp["3日留存"] = empty($temp["Adjust安装"]) ? "" : number_format($row["period_2_kpis"][0]/$temp["Adjust安装"]*100,2,".","")."%";//3留=第3日留存人数/安装
            $temp["7日留存"] = empty($temp["Adjust安装"]) ? "" : number_format($row["period_6_kpis"][0]/$temp["Adjust安装"]*100,2,".","")."%";//7留=第7日留存人数/安装
            $temp["次留人数"] = empty($row["period_1_kpis"][0]) ? "" : number_format($row["period_1_kpis"][0],2,".","");
            $temp["3留人数"] = empty($row["period_2_kpis"][0]) ? "" : number_format($row["period_2_kpis"][0],2,".","");
            $temp["7留人数"] = empty($row["period_6_kpis"][0]) ? "" : number_format($row["period_6_kpis"][0],2,".","");
            $temp["当日注册付费人数"] = empty($row["period_1_kpis"][0]) ? "" : number_format($row["period_0_kpis"][1],2,".","");
            $temp["当日注册付费率"] = empty($temp["Adjust安装"]) ? "" : number_format($row["period_0_kpis"][1]/$temp["Adjust安装"],2,".","").'%';//当日注册付费率=当日新增付费人数/总安装
            $temp["当日注册ARPU"] = empty($row["period_0_kpis"][0]) ? "" : number_format($row["period_0_kpis"][2]/$row["period_0_kpis"][0],2,".","");//当日注册ARPU=当日注册用户的内购收入/当日注册的用户数
            $temp["当日注册ARPPU"] = empty($row["period_0_kpis"][1]) ? "" : number_format($row["period_0_kpis"][2]/$row["period_0_kpis"][1],2,".","");//当日注册ARPPU=当日注册用户的内购收入/当日注册的付费人数
            $roi_inner_1 = empty($temp["广告成本"]) ? "" : number_format($row["period_0_kpis"][2] / $temp["广告成本"] * 100,2,".","");//内购ROI=内购收入/广告成本
            $roi_inner_3 = empty($temp["广告成本"]) ? "" : number_format($row["period_2_kpis"][2] / $temp["广告成本"] * 100,2,".","");//内购ROI=内购收入/广告成本
            $roi_inner_7 = empty($temp["广告成本"]) ? "" : number_format($row["period_6_kpis"][2] / $temp["广告成本"] * 100,2,".","");//内购ROI=内购收入/广告成本
            $roi_inner_15 = empty($temp["广告成本"]) ? "" : number_format($row["period_14_kpis"][2] / $temp["广告成本"] * 100,2,".","");//内购ROI=内购收入/广告成本
            $roi_inner_30 = empty($temp["广告成本"]) ? "" : number_format($row["period_29_kpis"][2] / $temp["广告成本"] * 100,2,".","");//内购ROI=内购收入/广告成本

            $temp["首日总ROI"] = empty($roi_inner_1) ? "" : number_format($roi_inner_1 * $this->fcce,2,".","")."%";//总ROI=内购ROI*$this->fcce+广告ROI
            $temp["3日总ROI"] = empty($roi_inner_3) ? "" : number_format($roi_inner_3 * $this->fcce,2,".","")."%";//总ROI=内购ROI*$this->fcce+广告ROI
            $temp["7日总ROI"] = empty($roi_inner_7) ? "" : number_format($roi_inner_7 * $this->fcce,2,".","")."%";//总ROI=内购ROI*$this->fcce+广告ROI
            $temp["15日总ROI"] = empty($roi_inner_15) ? "" : number_format($roi_inner_15 * $this->fcce,2,".","")."%";//总ROI=内购ROI*$this->fcce+广告ROI
            $temp["30日总ROI"] = empty($roi_inner_30) ? "" : number_format($roi_inner_30 * $this->fcce,2,".","")."%";//总ROI=内购ROI*$this->fcce+广告ROI

            $temp["首日内购ROI"] = empty($roi_inner_1) ? "" : number_format($roi_inner_1,2,".","")."%";
            $temp["3日内购ROI"] = empty($roi_inner_3) ? "" : number_format($roi_inner_3,2,".","")."%";
            $temp["7日内购ROI"] = empty($roi_inner_7) ? "" : number_format($roi_inner_7,2,".","")."%";
            $temp["15日内购ROI"] = empty($roi_inner_15) ? "" : number_format($roi_inner_15,2,".","")."%";
            $temp["30日内购ROI"] = empty($roi_inner_30) ? "" : number_format($roi_inner_30,2,".","")."%";

//            $temp["首日广告ROI"] = '';
            $temp["3日广告ROI"] = '';
            $temp["7日广告ROI"] = '';
            $temp["15日广告ROI"] = '';
            $temp["30日广告ROI"] = '';

            $temp["首日内购收入"] = empty($row["period_0_kpis"][2]) ? "" : number_format($row["period_0_kpis"][2],2,".","");
            $temp["3日内购收入"] = empty($row["period_2_kpis"][2]) ? "" : number_format($row["period_2_kpis"][2],2,".","");
            $temp["7日内购收入"] = empty($row["period_6_kpis"][2]) ? "" : number_format($row["period_6_kpis"][2],2,".","");
            $temp["15日内购收入"] = empty($row["period_14_kpis"][2]) ? "" : number_format($row["period_14_kpis"][2],2,".","");
            $temp["30日内购收入"] = empty($row["period_29_kpis"][2]) ? "" : number_format($row["period_29_kpis"][2],2,".","");

//            $temp["首日广告收入"] = '';
            $temp["3日广告收入"] = '';
            $temp["7日广告收入"] = '';
            $temp["15日广告收入"] = '';
            $temp["30日广告收入"] = '';
            if(in_array($row["trackers_group_type"],['Tecdo','Inplayable'])){
                $temp['广告成本'] = $temp['Adjust安装'] * 3;
            }
            $temp["广告成本"] = number_format($temp["广告成本"], 2, '.', '');
            $list[$date][] = $temp;
        }
        $out = [];
        foreach($list as $date => $row){
            $out[date("Ymd",strtotime($date))] = $row;
        }
        $list = $out;
        if($sort == "DESC"){
            krsort($list,true);
        }else{
            ksort($list,true);
        }

        foreach($list as $date => $arr){
            array_multisort(array_column($list[$date],"user_os"), SORT_ASC, array_column($list[$date],"country"), SORT_ASC, array_column($list[$date],"trackers_group_type"), SORT_ASC,array_column($list[$date],"campaign_name"), SORT_ASC,array_column($list[$date],"adset_name"), SORT_ASC,array_column($list[$date],"adset_name"), SORT_ASC, $list[$date]);
        }
        if($list){
            oo::commonOprRedis('Statistics')->setex($cacheKey,json_encode($list),60);
        }
        return $list;
    }

    // 投放日报明细
    function getDayReportDetailData($reportType,$stime, $etime, $address, $trackers_group_type, $user_os, $users, $periodList, $sort = 'ASC'){
//        return [];
        switch ($reportType){
            case 'week':
                $weekIdx = date('w', strtotime($stime));
                $weekIdx = empty($weekIdx) ? 7 : $weekIdx;
                $weekBeginTime = strtotime($stime) - ($weekIdx-1)*86400;
                $stime = date('Y-m-d', $weekBeginTime);

                $weekIdx = date('w', strtotime($etime));
                $weekIdx = empty($weekIdx) ? 7 : $weekIdx;
                $weekEndTime = strtotime($etime) + (7 - $weekIdx) * 86400;
                $etime = date('Y-m-d', $weekEndTime);
                break;
            case 'month':
                $monthIdx = date('d', strtotime($stime));
                $monthBeginTime = strtotime($stime) - ($monthIdx-1)*86400;
                $stime = date('Y-m-d', $monthBeginTime);

                $monthIdx = date('d', strtotime($etime));
                $monthBeginTime = strtotime($etime) - ($monthIdx-1)*86400;
                $monthEndTime = strtotime('+1 month', $monthBeginTime) - 86400;
                $etime = date('Y-m-d', $monthEndTime);
                break;
        }
        $cacheKey = $stime."-".$etime."-".$address."-".$trackers_group_type."-".$user_os;
        $cache = oo::commonOprRedis('Statistics')->get($cacheKey);
        if($cache){
//            return json_decode($cache,1);
        }
        $where = "";

        if(!is_array($address))$address = strtolower($address);
        if(!is_array($address))$address = explode(',', $address);
        if(!in_array('all', $address)){
            if(!empty($address)){
                $whereCountryStr = '"'.implode('","', $address).'"';
                $where .= " AND countries in ({$whereCountryStr})";
            }
        }else{
            $address = ['all'];
        }

        if(!is_array($trackers_group_type))$trackers_group_type = explode(',', $trackers_group_type);

        if(in_array('all', $trackers_group_type)){
            $trackers_group_type = ['all'];
            $selectedChannels = $this->paymentChannels;
        }else{
            $selectedChannels = $trackers_group_type;
        }

        if(!is_array($users))$users = explode(',', $users);
        if(!empty($users) && !in_array('all', $users)){
            $whereUsers = $users;
        }else{
            $whereUsers = $this->adUsers;
            $users = ['all'];
        }

        $where .= ' and ( 0 ';
        foreach ($whereUsers as $user){
            $where .= " or `campaigns_name` like '%_{$user}_%' ";
        }
        $where .= ' ) ';

        if($user_os && $user_os != "all"){
            $where .= " AND os_names = '{$user_os}'";
        }
        $where .= " AND date >= '{$stime}' AND date <= '{$etime}'";

        $trackers_group_typeKey = implode(',', $trackers_group_type);
        $usersKey = implode(',', $users);
        $addressKey = implode(',', $address);
        if( in_array('all', $users))$users = $this->adUsers;
        $TAdjustPeriodDataRet = [];

        foreach ($selectedChannels as $channel){
            if(empty($this->trackTokens[$channel]))continue;
            $whereTokens = array_unique($this->trackTokens[$channel]);
            $whereTokensStr = '';
            if(!empty($whereTokens)){
                $whereTokensStr = '"'.implode('","', $whereTokens).'"';
                $whereTokensStr = " AND trackers_channel_token in ({$whereTokensStr})";
            }else{
                continue;
            }

            $TAdjustPeriod = otable::TAdjustPeriodView($channel);
            $sql = "SELECT * FROM {$TAdjustPeriod} WHERE 1=1 {$where} {$whereTokensStr}";
            $tmpRes = (array)oo::commonOprDb('report')->getAll($sql,1);
            $TAdjustPeriodDataRet = array_merge($TAdjustPeriodDataRet, $tmpRes);
        }
//        return [];
//        $TAdjustPeriod = otable::TAdjustPeriodView('All');
//        $sql = "SELECT * FROM {$TAdjustPeriod} WHERE 1=1 {$where}";
//        $TAdjustPeriodDataRet = (array)oo::commonOprDb('report')->getAll($sql,1);
        $TAdjustPeriodData = [];
        $periodDateMap = [];
        foreach ($TAdjustPeriodDataRet as $key => $row){
            $row["date"] = $this->getDateKey($row["date"], $reportType);
            $periodDateMap[$row["date"]] = $periodDateMap[$row["date"]] ?? [];
            $kpis = json_decode($row['kpi_values'], true);
            $row["trackers_group_type"] = $trackers_group_typeKey;
            $usersKey = 'default';
            foreach ($this->adUsers as $adUser){
                if(strpos(strtolower($row['campaigns_name']), strtolower($adUser)) !== false){
                    $usersKey = $adUser;
                    break;
                }
            }
            if($usersKey == 'default'){
                continue;
            }
            $row["users"] = $usersKey;
            $row["os_names"] = $user_os;
            $row["countries"] = $addressKey;
            $TAdjustPeriodData[$row["date"]][$row["countries"]][$row["os_names"]][$row["trackers_group_type"]][$row["users"]] = $TAdjustPeriodData[$row["date"]][$row["countries"]][$row["os_names"]][$row["trackers_group_type"]][$row["users"]] ?? [];
            foreach($periodList as $time){
                $row["period_{$time}_kpis"] = @json_decode($row["period_{$time}_kpis"],true) ?? [];

                $periodDateMap[$row["date"]][$time] = $periodDateMap[$row["date"]][$time] ?? [];
                $periodDateMap[$row["date"]][$time][] = $row["period_{$time}_kpis"];
            }
            foreach ($kpis as $k => $v){
                $TAdjustPeriodData[$row["date"]][$row["countries"]][$row["os_names"]][$row["trackers_group_type"]][$row["users"]]['kpi_values'][$k] = $TAdjustPeriodData[$row["date"]][$row["countries"]][$row["os_names"]][$row["trackers_group_type"]][$row["users"]]['kpi_values'][$k] ?? 0;
                $TAdjustPeriodData[$row["date"]][$row["countries"]][$row["os_names"]][$row["trackers_group_type"]][$row["users"]]['kpi_values'][$k] += $v;
            }
            $lastPeriods = [0,0,0];
            foreach($periodList as $time){
                if(empty($row["period_{$time}_kpis"]))$row["period_{$time}_kpis"] = [0,0,0]; // 不存在时 默认 0 保证数据结构一致
                foreach($row["period_{$time}_kpis"] as $k => $vo){
                    if($k == 2){
                        if(empty($vo))
                            $vo = $lastPeriods[$k];
                        else
                            $lastPeriods[$k] = $vo;
                    }

                    $TAdjustPeriodData[$row["date"]][$row["countries"]][$row["os_names"]][$row["trackers_group_type"]][$row["users"]]["period_{$time}_kpis"][$k] = $TAdjustPeriodData[$row["date"]][$row["countries"]][$row["os_names"]][$row["trackers_group_type"]][$row["users"]]["period_{$time}_kpis"][$k] ?? 0;
                    $TAdjustPeriodData[$row["date"]][$row["countries"]][$row["os_names"]][$row["trackers_group_type"]][$row["users"]]["period_{$time}_kpis"][$k] += $vo;
                }
            }
        }
        $list = [];
        $spendTotal = [];
        $valideSpend = [];
        ksort($TAdjustPeriodData);
        foreach ($TAdjustPeriodData as $dateKey => $dateItem){
            foreach ($dateItem as $countryKey => $countryItem){
                foreach ($countryItem as $osKey => $osItem){
                    foreach ($osItem as $channelKey => $channelItem){
                        foreach ($channelItem as $adUsersKey => $adUsersItem){
                            $users = [$adUsersKey];
                            $spend = 0;

                            # 计算花费
                            if(
                                in_array("all", $trackers_group_type )
                                ||in_array("All", $trackers_group_type )
                                ||in_array("ALL", $trackers_group_type )
                            ){
                                $spend += $spendTotal[$dateKey]['fb'] = $this->getFbSpend($dateKey,$countryKey,$osKey, $users) * $this->spendCeList['fb'];
                                $spend += $spendTotal[$dateKey]['Google'] = $this->getGoogleSpend($dateKey,$countryKey,$osKey, $users);
                                $spend += $spendTotal[$dateKey]['Apple'] = $this->getAppleSpend($dateKey,$countryKey,$osKey, $users);
                                $spend += $spendTotal[$dateKey]['Unity'] = $this->getUnitySpend($dateKey,$countryKey,$osKey, $users);
                                $spend += $spendTotal[$dateKey]['Applovin'] = $this->getApplovinSpend($dateKey,$countryKey,$osKey, $users);
                                $spend += $spendTotal[$dateKey]['Ironsource'] = $this->getIronsourceSpend($dateKey,$countryKey,$osKey, $users);
                                $spend += $spendTotal[$dateKey]['Chartboost'] = $this->getChartboostSpend($dateKey,$countryKey,$osKey, $users);
                                $spend += $spendTotal[$dateKey]['Mintegral'] = $this->getMintegralSpend($dateKey,$countryKey,$osKey, $users);
                                $spend += $spendTotal[$dateKey]['TikTok'] = $this->getTikTokSpend($dateKey,$countryKey,$osKey, $users) * $this->spendCeList['tt'];
                            }
                            else{
                                if(in_array("Facebook", $trackers_group_type )){
                                    $spend += $this->getFbSpend($dateKey,$countryKey,$osKey, $users) * $this->spendCeList['fb'];
                                }
                                if(in_array("Google_ads", $trackers_group_type )){
                                    $spend += $this->getGoogleSpend($dateKey,$countryKey,$osKey, $users);
                                }
                                if(in_array("苹果商店页搜索广告", $trackers_group_type )){
                                    $spend += $this->getAppleSpend($dateKey,$countryKey,$osKey, $users);
                                }
                                if(in_array("Unity", $trackers_group_type )){
                                    $spend += $this->getUnitySpend($dateKey,$countryKey,$osKey, $users);
                                }
                                if(in_array("Applovin", $trackers_group_type )){
                                    $spend += $this->getApplovinSpend($dateKey,$countryKey,$osKey, $users);
                                }
                                if(in_array("IronSource", $trackers_group_type )){
                                    $spend += $this->getIronsourceSpend($dateKey,$countryKey,$osKey, $users);
                                }
                                if(in_array("Chartboost", $trackers_group_type )){
                                    $spend += $this->getChartboostSpend($dateKey,$countryKey,$osKey, $users);
                                }
                                if(in_array("Mintegral", $trackers_group_type )){
                                    $spend += $this->getMintegralSpend($dateKey,$countryKey,$osKey, $users);
                                }
                                if(in_array("TikTok", $trackers_group_type )){
                                    $spend += $this->getTikTokSpend($dateKey,$countryKey,$osKey, $users) * $this->spendCeList['tt'];
                                }
                                if(in_array("Vungle", $trackers_group_type )){
                                    $spend += 0;
                                }
                            }

                            $TAdjustPeriodData[$dateKey][$countryKey][$osKey][$channelKey][$adUsersKey]["spend"] = $spend ;

                            $roi_inner_1 = empty($spend) ? 0.00 : number_format($adUsersItem["period_0_kpis"][2] / $spend * 100,2,".","");//内购ROI=内购收入/广告成本
                            $roi_inner_3 = empty($spend) ? 0.00 : number_format($adUsersItem["period_2_kpis"][2] / $spend * 100,2,".","");//内购ROI=内购收入/广告成本
                            $roi_inner_7 = empty($spend) ? 0.00 : number_format($adUsersItem["period_6_kpis"][2] / $spend * 100,2,".","");//内购ROI=内购收入/广告成本
                            $roi_inner_15 = empty($spend) ? 0.00 : number_format($adUsersItem["period_14_kpis"][2] / $spend * 100,2,".","");//内购ROI=内购收入/广告成本
                            $roi_inner_30 = empty($spend) ? 0.00 : number_format($adUsersItem["period_29_kpis"][2] / $spend * 100,2,".","");//内购ROI=内购收入/广告成本
                            $roi_inner_60 = empty($spend) ? 0.00 : number_format($adUsersItem["period_59_kpis"][2] / $spend * 100,2,".","");//内购ROI=内购收入/广告成本
                            $roi_inner_120 = empty($spend) ? 0.00 : number_format($adUsersItem["period_119_kpis"][2] / $spend * 100,2,".","");//内购ROI=内购收入/广告成本

                            $日留存7 = empty($adUsersItem["kpi_values"][1]) ? 0.00 : $adUsersItem["period_6_kpis"][0]/$adUsersItem["kpi_values"][1];
                            $ae = $this->getAE($日留存7, $roi_inner_7 * $this->fcce * 0.01);
                            $ce = $this->getCE($ae);
                            $valideSpend[$adUsersKey] = $valideSpend[$adUsersKey] ?? 0;
                            $valideSpend[$adUsersKey] += $ce*$spend;
                            $list[$dateKey][$adUsersKey] = [
                                'kpi_values' => $adUsersItem["kpi_values"],
                                '日期' => $dateKey,
                                '版本' => $osKey,
                                '国家' => $countryKey,
                                '广告渠道' => $channelKey,
                                '投放人' => $adUsersKey,
                                '广告成本' => number_format($spend, 2,'.', ''),
                                'spend' => $spend,
                                'Adjust安装' => $adUsersItem["kpi_values"][1],
                                '推广CPI' => empty($adUsersItem["kpi_values"][1]) ? '' : number_format($spend/$adUsersItem["kpi_values"][1], 2, '.', ''),
                                '推广次留CPI' =>  empty($adUsersItem["period_1_kpis"][0]) ? "" : number_format($spend/$adUsersItem["period_1_kpis"][0],2,".",""),//推广次留CPI=广告成本/次日留存人数,

                                "当日注册付费人数" => empty($adUsersItem["period_1_kpis"][0]) ? "" : number_format($adUsersItem["period_0_kpis"][1],2,".",""),
                                "当日注册付费率" => empty($adUsersItem["kpi_values"][1]) ? "" : number_format($adUsersItem["period_0_kpis"][1]/$adUsersItem["kpi_values"][1],2,".","").'%',//当日注册付费率=当日新增付费人数/总安装
                                "当日注册ARPU" => empty($adUsersItem["period_0_kpis"][0]) ? "" : number_format($adUsersItem["period_0_kpis"][2]/$adUsersItem["period_0_kpis"][0],2,".",""),//当日注册ARPU=当日注册用户的内购收入/当日注册的用户数
                                "当日注册ARPPU" => empty($adUsersItem["period_0_kpis"][1]) ? "" : number_format($adUsersItem["period_0_kpis"][2]/$adUsersItem["period_0_kpis"][1],2,".",""),//当日注册ARPPU=当日注册用户的内购收入/当日注册的付费人数


                                '次日留存' =>   empty($adUsersItem["kpi_values"][1]) ? "" : number_format($adUsersItem["period_1_kpis"][0]/$adUsersItem["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,
                                '3日留存' =>   empty($adUsersItem["kpi_values"][1]) ? "" : number_format($adUsersItem["period_2_kpis"][0]/$adUsersItem["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,
                                '7日留存' =>   empty($adUsersItem["kpi_values"][1]) ? "" : number_format($adUsersItem["period_6_kpis"][0]/$adUsersItem["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,
                                '15日留存' =>   empty($adUsersItem["kpi_values"][1]) ? "" : number_format($adUsersItem["period_14_kpis"][0]/$adUsersItem["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,
                                '30日留存' =>   empty($adUsersItem["kpi_values"][1]) ? "" : number_format($adUsersItem["period_29_kpis"][0]/$adUsersItem["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,
                                '60日留存' =>   empty($adUsersItem["kpi_values"][1]) ? "" : number_format($adUsersItem["period_59_kpis"][0]/$adUsersItem["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,
                                '120日留存' =>   empty($adUsersItem["kpi_values"][1]) ? "" : number_format($adUsersItem["period_119_kpis"][0]/$adUsersItem["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,

                                '次留人数' =>   $adUsersItem["period_1_kpis"][0],//empty($adUsersItem["kpi_values"][1]) ? "" : number_format(/$adUsersItem["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,
                                '3留人数' =>   $adUsersItem["period_2_kpis"][0],//empty($adUsersItem["kpi_values"][1]) ? "" : number_format(/$adUsersItem["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,
                                '7留人数' =>   $adUsersItem["period_6_kpis"][0],//empty($adUsersItem["kpi_values"][1]) ? "" : number_format(/$adUsersItem["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,
                                '15留人数' =>   $adUsersItem["period_14_kpis"][0],//empty($adUsersItem["kpi_values"][1]) ? "" : number_format(/$adUsersItem["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,
                                '30留人数' =>   $adUsersItem["period_29_kpis"][0],//empty($adUsersItem["kpi_values"][1]) ? "" : number_format(/$adUsersItem["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,
                                '60留人数' =>   $adUsersItem["period_59_kpis"][0],//empty($adUsersItem["kpi_values"][1]) ? "" : number_format(/$adUsersItem["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,
                                '120留人数' =>   $adUsersItem["period_119_kpis"][0],//empty($adUsersItem["kpi_values"][1]) ? "" : number_format(/$adUsersItem["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,

                                "首日总ROI" => empty($roi_inner_1) ? "" : number_format($roi_inner_1,2,".","")."%",//总ROI=内购ROI*$this->fcce+广告ROI
                                "3日总ROI" => empty($roi_inner_3) ? "" : number_format($roi_inner_3,2,".","")."%",//总ROI=内购ROI*$this->fcce+广告ROI
                                "7日总ROI" => empty($roi_inner_7) ? "" : number_format($roi_inner_7,2,".","")."%",//总ROI=内购ROI*$this->fcce+广告ROI
                                "15日总ROI" => empty($roi_inner_15) ? "" : number_format($roi_inner_15,2,".","")."%",//总ROI=内购ROI*$this->fcce+广告ROI
                                "30日总ROI" => empty($roi_inner_30) ? "" : number_format($roi_inner_30,2,".","")."%",//总ROI=内购ROI*$this->fcce+广告ROI
                                "60日总ROI" => empty($roi_inner_60) ? "" : number_format($roi_inner_60,2,".","")."%",//总ROI=内购ROI*$this->fcce+广告ROI
                                "120日总ROI" => empty($roi_inner_120) ? "" : number_format($roi_inner_120,2,".","")."%",//总ROI=内购ROI*$this->fcce+广告ROI

                                "首日内购ROI" => empty($roi_inner_1) ? "" : number_format($roi_inner_1 * $this->fcce,2,".","")."%",
                                "3日内购ROI" => empty($roi_inner_3) ? "" : number_format($roi_inner_3 * $this->fcce,2,".","")."%",
                                "7日内购ROI" => empty($roi_inner_7) ? "" : number_format($roi_inner_7 * $this->fcce,2,".","")."%",
                                "15日内购ROI" => empty($roi_inner_15) ? "" : number_format($roi_inner_15 * $this->fcce,2,".","")."%",
                                "30日内购ROI" => empty($roi_inner_30) ? "" : number_format($roi_inner_30 * $this->fcce,2,".","")."%",
                                "60日内购ROI" => empty($roi_inner_60) ? "" : number_format($roi_inner_60 * $this->fcce,2,".","")."%",
                                "120日内购ROI" => empty($roi_inner_120) ? "" : number_format($roi_inner_120 * $this->fcce,2,".","")."%",

                                "3日广告ROI" => '',
                                "7日广告ROI" => '',
                                "15日广告ROI" => '',
                                "30日广告ROI" => '',

                                'AE'  => $ae , // 7日留存 * 7 分成roi * 100
                                '合格系数'  => $ce , //
                                '有效投放金额(累计)'  => number_format($valideSpend[$adUsersKey], 2, '.', '') , //
                                'AEA' => number_format($ae * $spend, 2,'.', ''), // 7日留存 * 7 分成roi * 100

                                "首日内购收入" => empty($adUsersItem["period_0_kpis"][2]) ? "" : number_format($adUsersItem["period_0_kpis"][2],2,".",""),
                                "3日内购收入" => empty($adUsersItem["period_2_kpis"][2]) ? "" : number_format($adUsersItem["period_2_kpis"][2],2,".",""),
                                "7日内购收入" => empty($adUsersItem["period_6_kpis"][2]) ? "" : number_format($adUsersItem["period_6_kpis"][2],2,".",""),
                                "15日内购收入" => empty($adUsersItem["period_14_kpis"][2]) ? "" : number_format($adUsersItem["period_14_kpis"][2],2,".",""),
                                "30日内购收入" => empty($adUsersItem["period_29_kpis"][2]) ? "" : number_format($adUsersItem["period_29_kpis"][2],2,".",""),
                                "60日内购收入" => empty($adUsersItem["period_59_kpis"][2]) ? "" : number_format($adUsersItem["period_59_kpis"][2],2,".",""),
                                "120日内购收入" => empty($adUsersItem["period_119_kpis"][2]) ? "" : number_format($adUsersItem["period_119_kpis"][2],2,".",""),

                            ];
                            foreach ($periodList as $day){
                                $list[$dateKey][$adUsersKey]["period_{$day}_kpis"] = $adUsersItem["period_{$day}_kpis"];
                            }
                        }
                    }
                }
            }
        }

        # 选中的投放人大于一个是 才算汇总项
        if(count($whereUsers) > 1){
            $valideSpend = 0;
            foreach ($list as $dateKey => $item){
                $spend = 0;
                $period = [];
                foreach ($item as $userKey => $adUsersItem){
                    $spend += $adUsersItem['spend'];
                    foreach ($periodList as $day){
                        $period["period_{$day}_kpis"] = $period["period_{$day}_kpis"] ?? [0,0,0];
                        foreach ($adUsersItem["period_{$day}_kpis"] as $k => $v){
                            $period["period_{$day}_kpis"][$k] += $v;
                        }
                    }
                    $period["kpi_values"] = $period["kpi_values"] ?? [0,0,0];
                    foreach ($adUsersItem["kpi_values"] as $k => $v){
                        $period["kpi_values"][$k] += $v;
                    }
                }

                $roi_inner_1 = empty($spend) ? "" : number_format($period["period_0_kpis"][2] / $spend * 100,2,".","");//内购ROI=内购收入/广告成本
                $roi_inner_3 = empty($spend) ? "" : number_format($period["period_2_kpis"][2] / $spend * 100,2,".","");//内购ROI=内购收入/广告成本
                $roi_inner_7 = empty($spend) ? "" : number_format($period["period_6_kpis"][2] / $spend * 100,2,".","");//内购ROI=内购收入/广告成本
                $roi_inner_15 = empty($spend) ? "" : number_format($period["period_14_kpis"][2] / $spend * 100,2,".","");//内购ROI=内购收入/广告成本
                $roi_inner_30 = empty($spend) ? "" : number_format($period["period_29_kpis"][2] / $spend * 100,2,".","");//内购ROI=内购收入/广告成本
                $roi_inner_60 = empty($spend) ? "" : number_format($period["period_59_kpis"][2] / $spend * 100,2,".","");//内购ROI=内购收入/广告成本
                $roi_inner_120 = empty($spend) ? "" : number_format($period["period_119_kpis"][2] / $spend * 100,2,".","");//内购ROI=内购收入/广告成本
                $日留存7 = empty($period["kpi_values"][1]) ? 0 :$period["period_6_kpis"][0]/$period["kpi_values"][1];
                $ae = $this->getAE($日留存7, $roi_inner_7 * $this->fcce * 0.01);
                $ce = $this->getCE($ae);
                $valideSpend += $ce*$spend;
                $list[$dateKey]['all'] = [
                    '日期' => $dateKey,
                    '版本' => $osKey,
                    '国家' => $countryKey,
                    '广告渠道' => $channelKey,
                    '投放人' => 'all',
                    '广告成本' => number_format($spend, 2,'.', ''),
                    'Adjust安装' => $period["kpi_values"][1],
                    '推广CPI' => empty($period["kpi_values"][1]) ? '' : number_format($spend/$period["kpi_values"][1], 2, '.', ''),
                    '推广次留CPI' =>  empty($period["period_1_kpis"][0]) ? "" : number_format($spend/$period["period_1_kpis"][0],2,".",""),//推广次留CPI=广告成本/次日留存人数,

                    'AE'  => $ae, // 7日留存 * 7 分成roi * 1000
                    '合格系数'  => $ce, //
                    '有效投放金额(累计)'  => number_format($valideSpend , 2, '.', ''), //
                    'AEA' => number_format($ae*$spend , 2,'.', ''), // 7日留存 * 7 分成roi * 1000

                    "当日注册付费人数" => empty($period["period_1_kpis"][0]) ? "" : number_format($period["period_0_kpis"][1],2,".",""),
                    "当日注册付费率" => empty($period["kpi_values"][1]) ? "" : number_format($period["period_0_kpis"][1]/$period["kpi_values"][1],2,".","").'%',//当日注册付费率=当日新增付费人数/总安装
                    "当日注册ARPU" => empty($period["period_0_kpis"][0]) ? "" : number_format($period["period_0_kpis"][2]/$period["period_0_kpis"][0],2,".",""),//当日注册ARPU=当日注册用户的内购收入/当日注册的用户数
                    "当日注册ARPPU" => empty($period["period_0_kpis"][1]) ? "" : number_format($period["period_0_kpis"][2]/$period["period_0_kpis"][1],2,".",""),//当日注册ARPPU=当日注册用户的内购收入/当日注册的付费人数


                    '次日留存' =>   empty($period["kpi_values"][1]) ? "" : number_format($period["period_1_kpis"][0]/$period["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,
                    '3日留存' =>   empty($period["kpi_values"][1]) ? "" : number_format($period["period_2_kpis"][0]/$period["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,
                    '7日留存' =>   empty($period["kpi_values"][1]) ? "" : number_format($period["period_6_kpis"][0]/$period["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,
                    '15日留存' =>   empty($period["kpi_values"][1]) ? "" : number_format($period["period_14_kpis"][0]/$period["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,
                    '30日留存' =>   empty($period["kpi_values"][1]) ? "" : number_format($period["period_29_kpis"][0]/$period["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,
                    '60日留存' =>   empty($period["kpi_values"][1]) ? "" : number_format($period["period_59_kpis"][0]/$period["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,
                    '120日留存' =>   empty($period["kpi_values"][1]) ? "" : number_format($period["period_119_kpis"][0]/$period["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,

                    '次留人数' =>   $period["period_1_kpis"][0],//empty($period["kpi_values"][1]) ? "" : number_format(/$period["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,
                    '3留人数' =>   $period["period_2_kpis"][0],//empty($period["kpi_values"][1]) ? "" : number_format(/$period["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,
                    '7留人数' =>   $period["period_6_kpis"][0],//empty($period["kpi_values"][1]) ? "" : number_format(/$period["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,
                    '15留人数' =>   $period["period_14_kpis"][0],//empty($period["kpi_values"][1]) ? "" : number_format(/$period["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,
                    '30留人数' =>   $period["period_29_kpis"][0],//empty($period["kpi_values"][1]) ? "" : number_format(/$period["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,
                    '60留人数' =>   $period["period_59_kpis"][0],//empty($period["kpi_values"][1]) ? "" : number_format(/$period["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,
                    '120留人数' =>   $period["period_119_kpis"][0],//empty($period["kpi_values"][1]) ? "" : number_format(/$period["kpi_values"][1]*100,2,".","").'%',//推广次留CPI=广告成本/次日留存人数,



                    "首日总ROI" => empty($roi_inner_1) ? "" : number_format($roi_inner_1,2,".","")."%",//总ROI=内购ROI*$this->fcce+广告ROI
                    "3日总ROI" => empty($roi_inner_3) ? "" : number_format($roi_inner_3,2,".","")."%",//总ROI=内购ROI*$this->fcce+广告ROI
                    "7日总ROI" => empty($roi_inner_7) ? "" : number_format($roi_inner_7,2,".","")."%",//总ROI=内购ROI*$this->fcce+广告ROI
                    "15日总ROI" => empty($roi_inner_15) ? "" : number_format($roi_inner_15,2,".","")."%",//总ROI=内购ROI*$this->fcce+广告ROI
                    "30日总ROI" => empty($roi_inner_30) ? "" : number_format($roi_inner_30,2,".","")."%",//总ROI=内购ROI*$this->fcce+广告ROI
                    "60日总ROI" => empty($roi_inner_60) ? "" : number_format($roi_inner_60,2,".","")."%",//总ROI=内购ROI*$this->fcce+广告ROI
                    "120日总ROI" => empty($roi_inner_120) ? "" : number_format($roi_inner_120,2,".","")."%",//总ROI=内购ROI*$this->fcce+广告ROI

                    "首日内购ROI" => empty($roi_inner_1) ? "" : number_format($roi_inner_1 * $this->fcce,2,".","")."%",
                    "3日内购ROI" => empty($roi_inner_3) ? "" : number_format($roi_inner_3 * $this->fcce,2,".","")."%",
                    "7日内购ROI" => empty($roi_inner_7) ? "" : number_format($roi_inner_7 * $this->fcce,2,".","")."%",
                    "15日内购ROI" => empty($roi_inner_15) ? "" : number_format($roi_inner_15 * $this->fcce,2,".","")."%",
                    "30日内购ROI" => empty($roi_inner_30) ? "" : number_format($roi_inner_30 * $this->fcce,2,".","")."%",
                    "60日内购ROI" => empty($roi_inner_60) ? "" : number_format($roi_inner_60 * $this->fcce,2,".","")."%",
                    "120日内购ROI" => empty($roi_inner_120) ? "" : number_format($roi_inner_120 * $this->fcce,2,".","")."%",

                    "3日广告ROI" => '',
                    "7日广告ROI" => '',
                    "15日广告ROI" => '',
                    "30日广告ROI" => '',

                    "首日内购收入" => empty($period["period_0_kpis"][2]) ? "" : number_format($period["period_0_kpis"][2],2,".",""),
                    "3日内购收入" => empty($period["period_2_kpis"][2]) ? "" : number_format($period["period_2_kpis"][2],2,".",""),
                    "7日内购收入" => empty($period["period_6_kpis"][2]) ? "" : number_format($period["period_6_kpis"][2],2,".",""),
                    "15日内购收入" => empty($period["period_14_kpis"][2]) ? "" : number_format($period["period_14_kpis"][2],2,".",""),
                    "30日内购收入" => empty($period["period_29_kpis"][2]) ? "" : number_format($period["period_29_kpis"][2],2,".",""),
                    "60日内购收入" => empty($period["period_59_kpis"][2]) ? "" : number_format($period["period_59_kpis"][2],2,".",""),
                    "120日内购收入" => empty($period["period_119_kpis"][2]) ? "" : number_format($period["period_119_kpis"][2],2,".",""),

                ];
            }
        }
        if($sort == 'ASC')
            ksort($list);
        else
            krsort($list);
        if($list){
            oo::commonOprRedis('Statistics')->setex($cacheKey,json_encode($list),600);
        }
        return $list;
    }
    private function getDateKey($date, $type){
        switch ($type){
            case 'day':return $date;
            case 'week':
                $weekIdx = date('w', strtotime($date));
                $weekIdx = empty($weekIdx) ? 7 : $weekIdx;
                $weekBeginTime = strtotime($date) - ($weekIdx-1)*86400;
                $weekBeginDate = date('Ymd', $weekBeginTime);
                $weekEndDate = date('Ymd', $weekBeginTime + 86400 * 6);
                return "{$weekBeginDate}~{$weekEndDate}";
            case 'month':
                $monthIdx = date('d', strtotime($date));
                $monthBeginTime = strtotime($date) - ($monthIdx-1)*86400;
                $monthEndTime = strtotime('+1 month', $monthBeginTime) - 86400;
                $monthBeginDate = date('Ymd', $monthBeginTime);
                $monthEndDate = date('Ymd', $monthEndTime);
                return "{$monthBeginDate}~{$monthEndDate}";
        }
    }

    private function getCE($ae){
// 2023-07-11 更新AE系数
//- 10＞AE，合格系数=-1
//- 12＞AE≥10，合格系数=0
//- 13＞AE≥12，合格系数=1
//- 14＞AE≥13，合格系数=1.1
//- 15＞AE≥14，合格系数=1.2
//- 16＞AE≥15，合格系数=1.3
//- 17＞AE≥16，合格系数=1.4
//- 18＞AE≥17，合格系数=1.5
//- 19＞AE≥18，合格系数=1.6
//- 20＞AE≥19，合格系数=1.7
//- 21＞AE≥20，合格系数=1.8
//- 22＞AE≥21，合格系数=1.9
//- AE≥22，合格系数=2.0

        $ceArray = [
            10 => 0,
            12 => 1,
            13 => 1.1,
            14 => 1.2,
            15 => 1.3,
            16 => 1.4,
            17 => 1.5,
            18 => 1.6,
            19 => 1.7,
            20 => 1.8,
            21 => 1.9,
            22 => 2.0,
        ];
        krsort($ceArray);
        foreach ($ceArray as $k => $value){
            if ($ae >= $k)return $value;
        }
        return -1;
    }
    private function getAE($日留存7, $roi7){
        if(empty($日留存7) || empty($roi7))return 0.00;
        return number_format(200 * $roi7 * log($日留存7 * 50, 10), 2, '.',  '');
//        return number_format($日留存7 * $roi7 * 1000 , 2,'.', '');
    }
    //获取FbAdSource标题
    function getFbAdSourceThead(){
        $headerTable = ['国家','版本','广告系列','广告组','广告','广告成本','广告平台安装','推广CPI','推广次留CPI','Adjust安装','Adjust CPI',
            '次日留存','3日留存','7日留存','次日留存人数','3日留存人数','7日留存人数','点击率(CTR)','转化率(CVR)','成效率(RR)','每千次展示费用(CPM)',
            '覆盖人数','展示次数','链接点击数','视频平均观看时长(s)','视频播放次数','视频前3秒播放次数','视频25%处播放次数','视频50%处播放次数',
            '视频15s处播放次数','视频75%处播放次数','视频95%处播放次数','视频100%处播放次数','视频总观看时长(s)','首日内购ROI','3日内购ROI','7日内购ROI','15日内购ROI',
            '30日内购ROI','首日内购收入','3日内购收入','7日内购收入','15日内购收入','30日内购收入','账户ID'];

        return $headerTable;
    }

    //获取adjust标题
    function getAdjustThead($type = "day"){
        $headerTable = ['日期','国家','版本','广告渠道','DAU','花费$','总安装','推广安装','自然量安装','自然量占比','买量CPI$','均价CPI$',
            'AE','合格系数','有效投放金额(累计)',
            '推广次留','自然量次留','次留','3日留存','7日留存','15日留存','30日留存'    ];
        if($type == "week"){
            $headerTable[] = "60日留存";
            $headerTable[] = "90日留存";
            $headerTable[] = "120日留存";
        }else if($type == "month"){
            $headerTable[] = "60日留存";
            $headerTable[] = "90日留存";
            $headerTable[] = "120日留存";

            #月报展示留存人数
            $headerTable[] = "次留人数";
            $headerTable[] = '3日留存人数';
            $headerTable[] = '7日留存人数';
            $headerTable[] = '15日留存人数';
            $headerTable[] = '30日留存人数';
            $headerTable[] = "60日留存人数";
            $headerTable[] = "90日留存人数";
            $headerTable[] = "120日留存人数";
        }
        $headerTable = array_merge($headerTable,['付费人数','付费率','当日ARPU','当日ARPPU','首日内购ROI','3日内购ROI','7日内购ROI','15日内购ROI','30日内购ROI']);
        if($type == "week"){
            $headerTable[] = "60日内购ROI";
            $headerTable[] = "90日内购ROI";
            $headerTable[] = "120日内购ROI";
        }else if($type == "month"){
            $headerTable[] = "60日内购ROI";
            $headerTable[] = "90日内购ROI";
            $headerTable[] = "120日内购ROI";
        }
        $headerTable = array_merge($headerTable,['内购收入','分成后总收入','首日内购收入','3日内购收入','7日内购收入','15日内购收入','30日内购收入']);
        if($type == "week"){
            $headerTable[] = "60日内购收入";
            $headerTable[] = "90日内购收入";
            $headerTable[] = "120日内购收入";
        }else if($type == "month"){
            $headerTable[] = "60日内购收入";
            $headerTable[] = "90日内购收入";
            $headerTable[] = "120日内购收入";
        }
        $headerTable = array_merge($headerTable,['推广次留用户数','自然次留用户数']);
        return $headerTable;
    }
    function getAdjustReportThead($type, $showList){
        $headerTable = ['日期','国家','版本','广告渠道','DAU','花费$','总安装','推广安装','自然量安装','自然量占比','买量CPI$','均价CPI$',
//            'AE','合格系数','有效投放金额(累计)',
//            '推广次留','自然量次留'
        ];
        switch ($type){
            case 'day':$dateType = '日';break;
            case 'week':$dateType = '周';break;
            case 'month':$dateType = '月';break;
            default:return [];
        }
        foreach ($showList as $showIdx){
//            if (empty($showIdx))continue;
            $headerTable[] = empty($showIdx) ? "首{$dateType}留存" : ++$showIdx."{$dateType}留存";
        }
        foreach ($showList as $showIdx){
//            if (empty($showIdx))continue;
            $headerTable[] = empty($showIdx) ? "首{$dateType}留存人数" : ++$showIdx."{$dateType}留存人数";
        }

        $headerTable = array_merge($headerTable,['付费人数','付费率']);
        foreach ($showList as $showIdx){
            $headerTable[] = empty($showIdx) ? "首{$dateType}内购ROI" : ++$showIdx."{$dateType}内购ROI";
        }
        $headerTable = array_merge($headerTable,['内购收入','分成后总收入']);
        foreach ($showList as $showIdx){
            $headerTable[] = empty($showIdx) ? "首{$dateType}内购收入" : ++$showIdx."{$dateType}内购收入";
        }
        return $headerTable;
    }

    //获取adjust日报明细标题
    function getDayReportViewThead($type = "Facebook"){
        $headerTable = ['版本','国家','广告渠道','广告系列'];
        if(in_array($type ,  ['Facebook','Google_ads','Mintegral', 'TikTok', '苹果商店页搜索广告'])) {
            $headerTable = array_merge($headerTable,['广告组']);
            if(!in_array($type,  ['苹果商店页搜索广告'])){
                $headerTable = array_merge($headerTable,['广告名']);
            }
        }

        $headerTable = array_merge($headerTable,['广告成本','Adjust安装','推广CPI','推广次留CPI',
            '次日留存','3日留存','7日留存','次留人数','3留人数','7留人数','当日注册付费人数','当日注册付费率','当日注册ARPU', '当日注册ARPPU',
            '首日总ROI', '3日总ROI','7日总ROI','15日总ROI','30日总ROI',
            '首日内购ROI', '3日内购ROI','7日内购ROI','15日内购ROI','30日内购ROI',
            '3日广告ROI','7日广告ROI','15日广告ROI','30日广告ROI',
            '首日内购收入','3日内购收入','7日内购收入','15日内购收入','30日内购收入',
            '3日广告收入','7日广告收入','15日广告收入','30日广告收入'
        ]);
        return $headerTable;
    }
    function getDayReportDetailThead(){
        $headerTable = ['日期','版本','国家','广告渠道','投放人'];

        $headerTable = array_merge($headerTable,['广告成本','Adjust安装','推广CPI','AE','合格系数','有效投放金额(累计)',
//        '推广次留CPI','当日注册付费人数','当日注册付费率','当日注册ARPU', '当日注册ARPPU',
            '首日内购ROI', '3日内购ROI','7日内购ROI','15日内购ROI','30日内购ROI','60日内购ROI','120日内购ROI',
            '次日留存','3日留存','7日留存','15日留存','30日留存','60日留存','120日留存',
            '首日内购收入','3日内购收入','7日内购收入','15日内购收入','30日内购收入','60日内购收入','120日内购收入',
            '次留人数','3留人数','7留人数','15留人数','30留人数','60留人数','120留人数',
//            '首日总ROI', '3日总ROI','7日总ROI','15日总ROI','30日总ROI',
        ]);
        return $headerTable;
    }

    //获取表头字母
    function headerTableChar($k){
        $char = 'A';
        $prefix  = '';
        for($i = 0;$i < $k; $i++){
            if($char == 'Z') {
                $char = 'AA';
                $prefix = 'A';
            }else if($char == 'AZ'){
                $char = 'BA';
                $prefix = 'B';
            }else if($char == 'BZ'){
                $char = 'CA';
                $prefix = 'C';
            }else {
                if(strlen($char) == 2){
                    $char = $prefix.chr(ord(substr($char,1,1)) + 1);
                }else{
                    $char = $prefix.chr(ord($char) + 1);
                }
            }
        }
        return $char;
    }

    //导出FbAdSource数据
    public function expprtFbAdSourceData($stime,$etime,$address,$trackers_group_type,$user_os,$campaign_id,$adset_id,$ad_id){
        $headerTable = array_merge(['日期'],$this->getFbAdSourceThead());
        $periodList = [0,1,2,6,14,29,59,89,119];
        $bodyTable = $this->getFbAdSourceData($stime,$etime,$address,$trackers_group_type,$user_os,$campaign_id,$adset_id,$ad_id,$periodList);
        $objPHPExcel = new PHPExcel();
        //处理表头
        foreach ($headerTable as $k => $v) {
            $strTemp = strval($this->headerTableChar($k).'1');
            $objPHPExcel->getActiveSheet()->setCellValue($strTemp, $v);
        }

        krsort($bodyTable,true);

        foreach($bodyTable as $date => $arr){
            array_multisort(array_column($bodyTable[$date],"country"), SORT_ASC, array_column($bodyTable[$date],"user_os"), SORT_ASC,array_column($bodyTable[$date],"campaign_name"), SORT_ASC,array_column($bodyTable[$date],"adset_name"), SORT_ASC,array_column($bodyTable[$date],"ad_name"), SORT_ASC, $bodyTable[$date]);
        }
        //处理数据
        $i = 2;
        foreach($bodyTable as $date => $vos) {
            foreach($vos as $vo){
                $j = 0;
                $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, $date);
                foreach($vo as $row){
                    $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, $row);
                }
                $i++;
            }
        }
        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $outPutFileName = 'fbAdSource数据_'.date('Y-m-d');
        $this->base($objPHPExcel,$outPutFileName);
    }

    //导出adjust数据
    public function exportAdjustData($stime,$etime,$type,$address,$trackers_group_type,$user_os){

        if($type != 'day')return $this->exportAdjustReport($stime,$etime,$type,$address,$trackers_group_type,$user_os);
        $trackers_group_type = strtr($trackers_group_type, ['___' => ',']);
        $address = strtr($address, ['___' => ',']);
        $trackers_group_type = urldecode($trackers_group_type);
        $address = urldecode($address);
        $headerTable = $this->getAdjustThead($type);
        $extensionList = $this->extensionList;//推广渠道
        $periodList = [0,1,2,6,14,29,59,89,119];
        $bodyTable = $this->getAdjustData($stime,$etime,$type,$address,$trackers_group_type,$user_os,$extensionList,$periodList);
        $objPHPExcel = new PHPExcel();
        //处理表头
        foreach ($headerTable as $k => $v) {
            $strTemp = strval($this->headerTableChar($k).'1');
            $objPHPExcel->getActiveSheet()->setCellValue($strTemp, $v);
        }
        $showList = [0,2,6,14,29];
        if($type == "week"){
            $showList = array_merge($showList,[59,89,119]);
        }else if($type == "month"){
            $showList = array_merge($showList,[59,89,119]);
        }

        //处理数据
        $i = 2;
        if($type == "day"){
            $out = [];
            foreach($bodyTable as $date => $row){
                $out[date("Ymd",strtotime($date))] = $row;
            }
            $bodyTable = $out;
        }
        ksort($bodyTable,true);
        $validSpend = 0;
        foreach($bodyTable as $date => $vos) {
            foreach ($vos as $countriesTemp => $vo) {
                foreach ($vo as $os_namesTemp => $v) {
                    $j = 0;
                    foreach ($v as $trackers_group_typeTemp => $row) {
                        $trackers_group_type == "all" && $row["spend"] += $row["spendGoogle"];

                        $Organic_all = 0;
                        if($trackers_group_typeTemp == "all"){
                            $Organic_all = number_format(($row["kpi_values"][1] - $row["extension"]) / $row["kpi_values"][1] * 100,2,".","") ?? 0;
                        }else if(!in_array($trackers_group_typeTemp,$extensionList)){
                            $Organic_all = "100";
                        }

                        $extensionRemain = $row["extensionRemain"];//推广
                        $extension = $row["extension"] ;
                        $naturalRemain = $row["period_1_kpis"][0] - $row["extensionRemain"];//自然
                        $natural = $row["kpi_values"][1] - $row["extension"];

                        $naturalRate = number_format(($natural / $row["kpi_values"][1]) * 100, 2);
                        switch (strtolower($trackers_group_type)){
                            case 'share':$channel = 'Share';break;
                            case 'organic':$channel = 'Organic';break;
                            default:$channel = $trackers_group_typeTemp;break;
                        }

                        $roi7 = empty($row["spend"]) ? 0 :$row["period_6_kpis"][2] * $this->fcce / $row["spend"];
                        $日留存7 =  empty($row["kpi_values"][1]) ? 0 :$row["period_6_kpis"][0] / $row["kpi_values"][1];
                        $ae = $this->getAE($日留存7, $roi7);
                        $ce = $this->getCE($ae);
                        $validSpend += $ce * $row["spend"];
                        #日期
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, $date);
                        #国家
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, $countriesTemp);
                        #设备
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, $os_namesTemp);
                        #渠道
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, $channel);
                        #dau
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, $row["kpi_values"][0] ?? 0);
                        #话费
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, number_format($row["spend"],2,".","") ?? 0);
                        #安装
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, $row["kpi_values"][1] ?? 0);
                        #推广安装
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, $extension);
                        #自然安装
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, $natural);
                        #自然量占比
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, $naturalRate."%");
                        #推广CPI
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, (empty($extension) ? '' : number_format($row["spend"] / $extension,2,".","") ?? ""));
                        #全量CPI
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, (empty($row["kpi_values"][1]) ? '' : number_format($row["spend"] / $row["kpi_values"][1],2,".","") ?? ""));
                        //AE
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, $ae );
                        // CE
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, $ce );
                        // 有效投放金额(累计)
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, $validSpend );
                        //AEA
//                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, number_format($ae  * $row["spend"],2,".","") );
                        #推广次留
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, (empty($extension) ? '' : number_format($extensionRemain / $extension * 100,2,".","")."%" ?? ''));
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, (empty($natural) ? '' : number_format($naturalRemain / $natural * 100,2,".","")."%" ?? ''));
                        foreach($showList as $time){
                            if($time == 0){
                                $time = 1;
                            }
                            $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, (empty($row["kpi_values"][1]) ? '' : number_format($row["period_{$time}_kpis"][0] / $row["kpi_values"][1] * 100,2,".","")."%" ?? ''));
                        }
                        if($type == 'month'){
                            foreach($showList as $time){
                                if($time == 0){
                                    $time = 1;
                                }
                                $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, intval($row["period_{$time}_kpis"][0]) );
                            }
                        }
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, ($row["period_0_kpis"][1] ?? 0));
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, (empty($row["kpi_values"][1]) ? '' : number_format($row["period_0_kpis"][1] / $row["kpi_values"][1] * 100,2,".","")."%" ?? ''));
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, (empty($row["kpi_values"][1]) ? '' : number_format($row["period_0_kpis"][2] / $row["kpi_values"][1],2,".","") ?? ''));
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, (empty($row["period_0_kpis"][1]) ? '' : number_format($row["period_0_kpis"][2] / $row["period_0_kpis"][1],2,".","") ?? ''));
                        foreach($showList as $time){
                            $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, (empty($row["spend"]) ? '' : number_format($row["period_{$time}_kpis"][2] / $row["spend"] * $this->fcce * 100,2,".","")."%" ?? ''));
                        }
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, (number_format($row["kpi_values"][2],2,".","") ?? 0));
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, (number_format($row["kpi_values"][2] * $this->fcce,2,".","") ?? 0));
                        foreach($showList as $time){
                            $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, (number_format($row["period_{$time}_kpis"][2],2,".","") ?? 0));
                        }
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, ($extensionRemain));
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, ($naturalRemain));
                        $i++;
                    }
                }
            }
        }

        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $outPutFileName = 'adjust数据_'.date('Y-m-d');
        $this->base($objPHPExcel,$outPutFileName);
    }

    public function exportAdjustReport($stime,$etime,$type,$address,$trackers_group_type,$user_os){
        $trackers_group_type = strtr($trackers_group_type, ['___' => ',']);
        $address = strtr($address, ['___' => ',']);
        $trackers_group_type = urldecode($trackers_group_type);
        $address = urldecode($address);
        $periodList = $this->getPeriodTimes($type);
        $headerTable = $this->getAdjustReportThead($type, $periodList);
        $extensionList = $this->extensionList;//推广渠道
        $bodyTable = $this->getAdjustReportData($stime,$etime,$type,$address,$trackers_group_type,$user_os,$extensionList);
        $objPHPExcel = new PHPExcel();
        //处理表头
        $char = 'A';
        $i = 1;
        foreach ($headerTable as $k => $v) {
            $objPHPExcel->getActiveSheet()->setCellValue($char++.$i, $v);
        }
        $i++;
        ksort($bodyTable,true);
        foreach($bodyTable as $date => $rows) {
            #日期
            $char = 'A';
            foreach ($rows as $row){
                foreach ($headerTable as $headerText){
                    $objPHPExcel->getActiveSheet()->setCellValue($char++.$i, $row[$headerText] ?? '-');
                }
                $i++;
            }
        }

        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $typeText = $type == 'month' ? "月报" : "周报" ;
        $outPutFileName = 'adjust'.$typeText.date('Y-m-d');
        $this->base($objPHPExcel,$outPutFileName);
    }
    public function exportAdjustLtvReport($stime,$etime,$type,$address,$trackers_group_type,$user_os){
        $trackers_group_type = strtr($trackers_group_type, ['___' => ',']);
        $address = strtr($address, ['___' => ',']);
        $trackers_group_type = urldecode($trackers_group_type);
        $address = urldecode($address);
        $periodList = $this->getPeriodTimes($type);
        $headerTable = $this->getLtvThead2($periodList, $type );
        $extensionList = $this->extensionList;//推广渠道
        $bodyTable = $this->getAdjustReportData($stime,$etime,$type,$address,$trackers_group_type,$user_os,$extensionList);
        $objPHPExcel = new PHPExcel();
        //处理表头
        $char = 'A';
        $i = 1;
        foreach ($headerTable as $k => $v) {
            $objPHPExcel->getActiveSheet()->setCellValue($char++.$i, $v);
        }
        $i++;
        ksort($bodyTable,true);
        foreach($bodyTable as $date => $rows) {
            #日期
            $char = 'A';
            foreach ($rows as $row){
                foreach ($headerTable as $headerText){
                    $objPHPExcel->getActiveSheet()->setCellValue($char++.$i, $row[$headerText] ?? '-');
                }
                $i++;
            }
        }

        $typeText = $type == 'month' ? "月" : "周" ;
        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $outPutFileName = 'adjust'.$typeText.'报_ltv'.date('Y-m-d');
        $this->base($objPHPExcel,$outPutFileName);
    }

    # 导出投放明细
    public function exportAdjustDataDetail($reportType, $stime,$etime,$user_os,$address,$trackers_group_type,$users){
        $periodList = [0,1,2,6,14,29,59,89,119];
        $trackers_group_type = strtr($trackers_group_type, ['___' => ',']);
        $trackers_group_type = urldecode($trackers_group_type);

        $users = strtr($users, ['___' => ',']);
        $users = urldecode($users);

        $address = strtr($address, ['___' => ',']);
        $address = urldecode($address);
        $headerTable = $this->getDayReportDetailThead();
        $bodyTable = $this->getDayReportDetailData($reportType, $stime,$etime,$address,$trackers_group_type,$user_os,$users,$periodList, 'DESC');
        $objPHPExcel = new PHPExcel();
        //处理表头
        $charBegin = 'A';
        foreach ($headerTable as $k => $v) {
            $strTemp = strval($charBegin.'1');
            $objPHPExcel->getActiveSheet()->setCellValue($strTemp, $v);
            $charBegin++;
        }

        //处理数据
        $i = 1;
        foreach($bodyTable as $date => $rows) {
            foreach($rows as $user => $row) {
                $i++;
                $charBegin = 'A';
                foreach ($headerTable as $k => $v){
                    $objPHPExcel->getActiveSheet()->setCellValue("{$charBegin}{$i}", $row[$v]);
                    $charBegin++;
                }
            }
        }
        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $outPutFileName = '投放明细'.date('Y-m-d');
        $this->base($objPHPExcel,$outPutFileName);
    }

    //导出adjust日报明细数据
    function exportAdjustViewData($stime,$etime,$address,$trackers_group_type,$user_os,$campaign_id,$adset_id,$ad_id,$sort){
        $headerTable = array_merge(['日期'], $this->getDayReportViewThead($trackers_group_type));
        $bodyTable = $this->getDayReportViewData($stime,$etime,$address,$trackers_group_type,$user_os,$campaign_id,$adset_id,$ad_id,$sort);
        $objPHPExcel = new PHPExcel();
        //处理表头
        foreach ($headerTable as $k => $v) {
            $strTemp = strval($this->headerTableChar($k).'1');
            $objPHPExcel->getActiveSheet()->setCellValue($strTemp, $v);
        }
        //处理数据
        $i = 2;
        foreach($bodyTable as $date => $vos) {
            foreach($vos as $vo){
                $j = 0;
                foreach ($headerTable as $key ){
                    if($key == '日期')
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, $date);
                    else
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, $vo[$key]);
                }
                $i++;
            }
        }
        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $outPutFileName = 'adjust日报明细数据_'.date('Y-m-d');
        $this->base($objPHPExcel,$outPutFileName);
    }

    //获取unity花费
    function getUnitySpend($date,$country,$os_names, $users = []){
        $where = '';
        if($country && $country != "all"){
            if(strpos($country,",") !== false){
                $countryTemp = explode(",",$country);
                $countryTemp = "'".implode("','",$countryTemp)."'";
                $where .= " AND country in ({$countryTemp})";
            }else{
                $where .= " AND country = '{$country}'";
            }
        }
        if($os_names && $os_names != "all"){
            $where .= " AND user_os = '{$os_names}'";
        }
        if(strpos($date,"~") !== false){
            $dateTemp = explode("~",$date);
            $stime = date("Y-m-d",strtotime($dateTemp[0]));
            $etime = date("Y-m-d",strtotime($dateTemp[1]));
            $where .= " AND data_start >= '{$stime}' AND data_start <= '{$etime}'";
        }else{
            $where .= " AND data_start = '{$date}'";
        }
        if(!empty($users)){
            $where .= ' and ( 0 ';
            foreach ($users as $user){
                $where .= " or name like '%{$user}%' ";
            }
            $where .= ')';
        }
        $tb = otable::TUnityCampain();
        $sql = "SELECT SUM(spend) AS total FROM {$tb} WHERE 1=1 {$where}";
        $ret = oo::commonOprDb('report')->getOne($sql,1);
        return $ret['total'] ?? 0;
    }
    function getApplovinSpend($date,$country,$os_names, $users = []){
        $where = '';
        if($country && $country != "all"){
            if(strpos($country,",") !== false){
                $countryTemp = explode(",",$country);
                $countryTemp = "'".implode("','",$countryTemp)."'";
                $where .= " AND country in ({$countryTemp})";
            }else{
                $where .= " AND country = '{$country}'";
            }
        }
        if($os_names && $os_names != "all"){
            $where .= " AND user_os = '{$os_names}'";
        }
        if(strpos($date,"~") !== false){
            $dateTemp = explode("~",$date);
            $stime = date("Y-m-d",strtotime($dateTemp[0]));
            $etime = date("Y-m-d",strtotime($dateTemp[1]));
            $where .= " AND data_start >= '{$stime}' AND data_start <= '{$etime}'";
        }else{
            $where .= " AND data_start = '{$date}'";
        }
        if(!empty($users)){
            $where .= ' and ( 0 ';
            foreach ($users as $user){
                $where .= " or name like '%{$user}%' ";
            }
            $where .= ')';
        }
        $tb = otable::TTypeCampain('Applovin');
        $sql = "SELECT SUM(spend) AS total FROM {$tb} WHERE 1=1 {$where}";
        $ret = oo::commonOprDb('report')->getOne($sql,1);
        return $ret['total'] ?? 0;
    }
    function getChartboostSpend($date,$country,$os_names, $users = []){
        $where = '';
        if($country && $country != "all"){
            if(strpos($country,",") !== false){
                $countryTemp = explode(",",$country);
                $countryTemp = "'".implode("','",$countryTemp)."'";
                $where .= " AND country in ({$countryTemp})";
            }else{
                $where .= " AND country = '{$country}'";
            }
        }
        if($os_names && $os_names != "all"){
            $where .= " AND user_os = '{$os_names}'";
        }
        if(strpos($date,"~") !== false){
            $dateTemp = explode("~",$date);
            $stime = date("Y-m-d",strtotime($dateTemp[0]));
            $etime = date("Y-m-d",strtotime($dateTemp[1]));
            $where .= " AND data_start >= '{$stime}' AND data_start <= '{$etime}'";
        }else{
            $where .= " AND data_start = '{$date}'";
        }
        if(!empty($users)){
            $where .= ' and ( 0 ';
            foreach ($users as $user){
                $where .= " or name like '%{$user}%' ";
            }
            $where .= ')';
        }
        $tb = otable::TTypeCampain('Chartboost');
        $sql = "SELECT SUM(spend) AS total FROM {$tb} WHERE 1=1 {$where}";
        $ret = oo::commonOprDb('report')->getOne($sql,1);
        return $ret['total'] ?? 0;
    }
    function getMintegralSpend($date,$country,$os_names, $users = []){
        $where = '';
        if($country && $country != "all"){
            if(strpos($country,",") !== false){
                $countryTemp = explode(",",$country);
                $countryTemp = "'".implode("','",$countryTemp)."'";
                $where .= " AND country in ({$countryTemp})";
            }else{
                $where .= " AND country = '{$country}'";
            }
        }
        if($os_names && $os_names != "all"){
            $where .= " AND user_os = '{$os_names}'";
        }
        if(strpos($date,"~") !== false){
            $dateTemp = explode("~",$date);
            $stime = date("Y-m-d",strtotime($dateTemp[0]));
            $etime = date("Y-m-d",strtotime($dateTemp[1]));
            $where .= " AND data_start >= '{$stime}' AND data_start <= '{$etime}'";
        }else{
            $where .= " AND data_start = '{$date}'";
        }
        if(!empty($users)){
            $where .= ' and ( 0 ';
            foreach ($users as $user){
                $where .= " or name like '%{$user}%' ";
            }
            $where .= ')';
        }
        $tb = otable::TTypeCampain('Mintegral');
        $sql = "SELECT SUM(spend) AS total FROM {$tb} WHERE 1=1 {$where}";
        $ret = oo::commonOprDb('report')->getOne($sql,1);
        return $ret['total'] ?? 0;
    }
    function getTikTokSpend($date,$country,$os_names, $users = []){
        $where = '';
        if($country && $country != "all"){
            if(strpos($country,",") !== false){
                $countryTemp = explode(",",$country);
                $countryTemp = "'".implode("','",$countryTemp)."'";
                $where .= " AND country in ({$countryTemp})";
            }else{
                $where .= " AND country = '{$country}'";
            }
        }

        if($os_names == 'ios')$os_names = 'iphone';
        if($os_names && $os_names != "all"){
            $where .= " AND user_os = '{$os_names}'";
        }
        if(strpos($date,"~") !== false){
            $dateTemp = explode("~",$date);
            $stime = date("Y-m-d",strtotime($dateTemp[0]));
            $etime = date("Y-m-d",strtotime($dateTemp[1]));
            $where .= " AND data_start >= '{$stime}' AND data_start <= '{$etime}'";
        }else{
            $where .= " AND data_start = '{$date}'";
        }
        if(!empty($users)){
            $where .= ' and ( 0 ';
            foreach ($users as $user){
                $where .= " or campain_name like '%{$user}%' ";
            }
            $where .= ')';
        }
        $tb = otable::TTypeCampain('TikTok');
        $sql = "SELECT SUM(spend) AS total FROM {$tb} WHERE 1=1 {$where}";
        $ret = oo::commonOprDb('report')->getOne($sql,1);
        return $ret['total'] ?? 0;
    }
    function getAppleSpend($date,$country,$os_names, $users = []){
        $where = '';
        if($country && $country != "all"){
            if(strpos($country,",") !== false){
                $countryTemp = explode(",",$country);
                $countryTemp = "'".implode("','",$countryTemp)."'";
                $where .= " AND country in ({$countryTemp})";
            }else{
                $where .= " AND country = '{$country}'";
            }
        }

        if($os_names && $os_names != "all"){
            $where .= " AND user_os = '{$os_names}'";
        }
        if(strpos($date,"~") !== false){
            $dateTemp = explode("~",$date);
            $stime = date("Y-m-d",strtotime($dateTemp[0]));
            $etime = date("Y-m-d",strtotime($dateTemp[1]));
            $where .= " AND data_start >= '{$stime}' AND data_start <= '{$etime}'";
        }else{
            $where .= " AND data_start = '{$date}'";
        }
        if(!empty($users)){
            $where .= ' and ( 0 ';
            foreach ($users as $user){
                $where .= " or campain_name like '%{$user}%' ";
            }
            $where .= ')';
        }
        $tb = otable::TTypeCampain('apple');
        $sql = "SELECT SUM(spend) AS total FROM {$tb} WHERE 1=1 {$where}";
        $ret = oo::commonOprDb('report')->getOne($sql,1);
        return $ret['total'] ?? 0;
    }
    function getProdegeSpend($date,$country,$os_names, $users = []){
        $where = '';
        if(strpos($date,"~") !== false){
            $dateTemp = explode("~",$date);
            $stime = date("Y-m-d",strtotime($dateTemp[0]));
            $etime = date("Y-m-d",strtotime($dateTemp[1]));
            $where .= " AND date >= '{$stime}' AND date <= '{$etime}'";
        }else{
            $where .= " AND date = '{$date}'";
        }

        $tb = otable::prodegeSpends();
        $sql = "SELECT SUM(spends) AS total FROM {$tb} WHERE 1=1 {$where}";
        $ret = oo::commonOprDb('report')->getOne($sql,1);
        return $ret['total'] ?? 0;
    }
    function getAdactionSpend($date,$country,$os_names, $users = []){
        $where = '';
        if(strpos($date,"~") !== false){
            $dateTemp = explode("~",$date);
            $stime = date("Y-m-d",strtotime($dateTemp[0]));
            $etime = date("Y-m-d",strtotime($dateTemp[1]));
            $where .= " AND date >= '{$stime}' AND date <= '{$etime}'";
        }else{
            $where .= " AND date = '{$date}'";
        }

        $tb = otable::adactionSpends();
        $sql = "SELECT SUM(spends) AS total FROM {$tb} WHERE 1=1 {$where}";
        $ret = oo::commonOprDb('report')->getOne($sql,1);
        return $ret['total'] ?? 0;
    }
    function getMistplaySpend($date,$country,$os_names, $users = []){
        $where = '';
        if(strpos($date,"~") !== false){
            $dateTemp = explode("~",$date);
            $stime = date("Y-m-d",strtotime($dateTemp[0]));
            $etime = date("Y-m-d",strtotime($dateTemp[1]));
            $where .= " AND date >= '{$stime}' AND date <= '{$etime}'";
        }else{
            $where .= " AND date = '{$date}'";
        }

        $tb = otable::mistplaySpends();
        $sql = "SELECT SUM(spends) AS total FROM {$tb} WHERE 1=1 {$where}";
        $ret = oo::commonOprDb('report')->getOne($sql,1);
        return $ret['total'] ?? 0;
    }

    //LTV日报
    public function ltvReport($type = "day",$sort = "DESC"){
        if($type != 'day')return $this->ltvReport2($type, $sort);
        $stime = get_cookie('stime') ?? date("Y-m-d",strtotime("-7 days 0:0:0"));
        $etime = get_cookie('etime') ?? date("Y-m-d",strtotime("-1 days 0:0:0"));
        $address = get_cookie('address') ?? 'all';//国家
        if(strpos($address,',') !== false && strpos($address,'all') === false){
            $address = explode(",",$address);
        }else if(strpos($address,',') !== false && strpos($address,'all') !== false){
            $address = "all";
        }

        $trackers_group_type = get_cookie('trackers_group_type') ?? 'all';//广告渠道
        $user_os = get_cookie('user_os') ?? 'all';//版本

        $extensionList = $this->extensionList;
        $periodList = [0,1,2,6,14,29,59,89,119];

        $showList = [0,1,2,6,14,29,59,89,119];

        $list = $this->getAdjustData($stime,$etime,$type,$address,$trackers_group_type,$user_os,$extensionList,$periodList);

        if($type == "day"){
            $out = [];
            foreach($list as $date => $row){
                $out[date("Ymd",strtotime($date))] = $row;
            }
            $list = $out;
        }
        if($sort == "DESC"){
            krsort($list,true);
        }else{
            ksort($list,true);
        }

        $formatData = [];
        foreach($list as $date => $vos) {
            foreach ($vos as $countriesTemp => $vo) {
                foreach ($vo as $os_namesTemp => $v) {
                    foreach ($v as $channel => $row) {
                        $extensionRemain = $row["extensionRemain"];//推广
//                        if ($channel == "all") {
//                            $extensionRemain = $row["extensionRemain"] ?? 0;
//                        } else if (in_array($channel, $extensionList)) {
//                            $extensionRemain = $row["period_1_kpis"][0] ?? 0;
//                        }

                        $extension = $row["extension"] ;
//                        if ($channel == "all") {
//                            $extension = $row["extension"] ?? 0;
//                        } else if (in_array($channel, $extensionList)) {
//                            $extension = $row["kpi_values"][1] ?? 0;
//                        }

                        $naturalRemain = $row["period_1_kpis"][0] - $row["extensionRemain"];//自然
//                        if ($channel == "all") {
//                            $naturalRemain = $row["period_1_kpis"][0] - $row["extensionRemain"] ?? 0;
//                        } else if (!in_array($channel, $extensionList)) {
//                            $naturalRemain = $row["period_1_kpis"][0] ?? 0;
//                        }
                        $natural = $row["kpi_values"][1] - $row["extension"];
//                        if($channel == "all"){
//                            $natural = $row["kpi_values"][1] - $row["extension"] ?? 0;
//                        }else if(!in_array($channel,$extensionList)){
//                            $natural = $row["kpi_values"][1] ?? 0;
//                        }else{
//                            $natural = 0;
//                        }

                        $naturalRate = number_format(($natural / $row["kpi_values"][1]) * 100, 2);

//                        $Organic_all = 0;
//                        if($trackers_group_typeTemp == "all"){
//                            $Organic_all = number_format(($row["kpi_values"][1] - $row["extension"]) / $row["kpi_values"][1] * 100,2,".","") ?? 0;
//                        }else if(!in_array($trackers_group_typeTemp,$extensionList)){
//                            $Organic_all = 100;
//                        }
                        $Organic_all = $naturalRate;

//                        $extension = 0;
//                        if($trackers_group_typeTemp == "all"){
//                            $extension = $row["extension"] ?? 0;
//                        }else if(in_array($trackers_group_typeTemp,$extensionList)){
//                            $extension = $row["kpi_values"][1] ?? 0;
//                        }

//                        $natural = 0;
//                        if($trackers_group_typeTemp == "all"){
//                            $natural = $row["kpi_values"][1] - $row["extension"] ?? 0;
//                        }else if(!in_array($trackers_group_typeTemp,$extensionList)){
//                            $natural = $row["kpi_values"][1] ?? 0;
//                        }
                        $temp = [
                            '日期' => $date,
                            '国家' => $countriesTemp,
                            '版本' => $os_namesTemp,
                            '广告渠道' => $channel,//(strtolower($trackers_group_type) == 'share') ? 'Share' : $trackers_group_typeTemp,
                            'DAU' => round($row["kpi_values"][0]) ?? 0,
                            '广告成本' => number_format($row["spend"],2,".","") ?? 0,
                            '总安装' => $row["kpi_values"][1] ?? 0,
                            '推广安装' => $extension,
                            '自然量安装' => $natural,
                            '自然量占比' => $Organic_all . '%',
                            'CPI' => empty($row["kpi_values"][1]) ? '' : number_format($row["spend"] / $row["kpi_values"][1],2,".","") ?? "",
                            '推广CPI' => empty($extension) ? '' : number_format($row["spend"] / $extension,2,".","") ?? "",
                            '推广次留CPI' => empty($extensionRemain) ? '' : number_format($row["spend"] / $extensionRemain,2,".","") ?? "",
                            '推广安装次留' => empty($extension) ? '' : number_format($extensionRemain / $extension * 100,2,".","")."%" ?? "",
                            '自然量安装次留' => empty($natural) ? '' : number_format($naturalRemain / $natural * 100,2,".","")."%" ?? "",
                            '次日留存' => empty($row["kpi_values"][1]) ? '' : number_format($row["period_1_kpis"][0] / $row["kpi_values"][1] * 100,2,".","")."%" ?? '',
                        ];
                        foreach($showList as $time){
                            if($time == 1){
                                continue;
                            }
                            if($time != 0 && $time != 1){
                                $temp[intval($time+1).'日留存'] = empty($row["kpi_values"][1]) ? '' : number_format($row["period_{$time}_kpis"][0] / $row["kpi_values"][1] * 100,2,".","")."%" ?? '';
                            }
                        }

                        //ltv左右两边增加付费率（左）和付费人数（右）
                        $temp['当日LTV'] =  empty($row["kpi_values"][0]) ? '' : number_format($row["kpi_values"][2] / $row["kpi_values"][0],2,".","") ?? '';
                        $temp['当日总收入'] =   empty($row["kpi_values"][2]) ? '' : number_format($row["kpi_values"][2],2,".","") ?? '';
                        $ltvDays   = [];
                        $ltvValues = [];
                        foreach($showList as $time2){
                            if($time2 == 1){
                                continue;
                            }
                            $temp['内购LTV' . intval($time2 + 1)] =   empty($row["period_0_kpis"][0]) ? '' : number_format($row["period_{$time2}_kpis"][2] / $row["period_0_kpis"][0],2,".","") ?? '';
                            $day = intval($time2 + 1);
//                            if(!empty($temp['内购LTV' . $day])){
//                                $ltvDays[] = $day;
//                                $ltvValues[] = floatval($temp['内购LTV' . $day]);
//                            }
                        }

                        foreach($showList as $time2){
                            if($time2 == 1){
                                continue;
                            }
                            $temp['内购付费LTV'. intval($time2 + 1)] = empty($row["period_0_kpis"][3]) ? '' : number_format($row["period_{$time2}_kpis"][2] / $row["period_0_kpis"][3],2,".","") ?? '';
                        }
                        $temp['付费用户群'] = empty($row["period_0_kpis"][3]) ? '' : round($row["period_0_kpis"][3]) ?? '';

                        foreach($showList as $time){
                            if($time == 1){
                                continue;
                            }
                            $temp['内购收入'. intval($time + 1)] = number_format($row["period_{$time}_kpis"][2],2,".","") ?? 0;
                        }
                        $ltvDays = $ltvValues = [];
                        foreach($showList as $time){
                            if($time == 1){
                                continue;
                            }
                            $temp[intval($time + 1).'日留存人数'] = round($row["period_{$time}_kpis"][0]) ?? 0;
//                            $ltvDays[] = intval($time + 1);
//                            $ltvValues[] = $temp[intval($time + 1).'日留存人数'];
                        }
                        $formatData[] = $temp;
                    }
                }
            }
        }
        $list = $formatData;
        unset($formatData);
        $data["title"] = "ltv日报";
        if($type == "week"){
            $data["title"] = "ltv周报";
        }else if($type == "month"){
            $data["title"] = "ltv月报";
        }
        $data['list'] = $list;
        $data['address'] = $address;
        $data['stime'] = $stime;
        $data['etime'] = $etime;
        $data['trackers_group_type'] =  is_array($trackers_group_type) ? $trackers_group_type : explode(',', $trackers_group_type);//$trackers_group_type;
        $data['user_os'] = $user_os;
        $data["extensionList"] = $extensionList;
        $data["sort"] = $sort;
        $data["type"] = $type;
        $data["showList"] = $showList;
        $data["headerTable"] = $this->getLtvThead($showList,$type);
        $data["addressList"] = $this->getCountryList();
        $data["getTrackersGroupType"] = $this->getTrackersGroupType();
        $data["trackTokens"] = $this->trackTokens;

        $this->load->view('report/ltvReport', $data);
    }
    public function ltvReport2($type = "day",$sort = "DESC"){
        $stime = get_cookie('stime') ?? date("Y-m-d",strtotime("-7 days 0:0:0"));
        $etime = get_cookie('etime') ?? date("Y-m-d",strtotime("-1 days 0:0:0"));
        $address = get_cookie('address') ?? 'all';//国家
        if(strpos($address,',') !== false && strpos($address,'all') === false){
            $address = explode(",",$address);
        }else if(strpos($address,',') !== false && strpos($address,'all') !== false){
            $address = "all";
        }

        $trackers_group_type = get_cookie('trackers_group_type') ?? 'all';//广告渠道
        $user_os = get_cookie('user_os') ?? 'all';//版本

        $extensionList = $this->extensionList;
        $periodList = $showList = $this->getPeriodTimes($type);

        $list = $this->getAdjustReportData($stime,$etime,$type,$address,$trackers_group_type,$user_os,$extensionList);

        if($sort == "DESC"){
            krsort($list,true);
        }else{
            ksort($list,true);
        }
        $data["title"] = "ltv日报";
        if($type == "week"){
            $data["title"] = "ltv周报";
        }else if($type == "month"){
            $data["title"] = "ltv月报";
        }
        $data['list'] = $list;
        $data['address'] = $address;
        $data['stime'] = $stime;
        $data['etime'] = $etime;
        $data['trackers_group_type'] =  is_array($trackers_group_type) ? $trackers_group_type : explode(',', $trackers_group_type);//$trackers_group_type;
        $data['user_os'] = $user_os;
        $data["extensionList"] = $extensionList;
        $data["sort"] = $sort;
        $data["type"] = $type;
        $data["showList"] = $showList;
        $data["headerTable"] = $this->getLtvThead($showList,$type);
        $data["headerTable"] = $this->getLtvThead2($showList,$type);
        $data["addressList"] = $this->getCountryList();
        $data["getTrackersGroupType"] = $this->getTrackersGroupType();
        $data["trackTokens"] = $this->trackTokens;

        $this->load->view('report/ltvReport2', $data);
    }

    //广告渠道
    function getTrackersGroupType(){
        $config = [];
        $config[""] = "all";
        $config["Facebook"] = "Facebook";
        $config["Google_ads"] = "Google_ads";
        $config["IronSource"] = "IronSource";
        $config["Organic_all"] = "Organic_all";
        $config["Unity"] = "Unity";
        $config["Virgrilmedia"] = "Virgrilmedia";
        $config["Linkme"] = "Linkme";
        $config["Applovin"] = "Applovin";
        $config["Vungle"] = "Vungle";
        return $config;
    }

    //ltv表格标题
    function getLtvThead($showList,$type){
        $headerTable = ['日期','国家','版本','广告渠道','DAU','广告成本','总安装','推广安装','自然量安装','自然量占比','CPI','推广CPI','推广次留CPI','推广安装次留','自然量安装次留'];
        foreach($showList as $num){
            if($num == 0){
                continue;
            }
            if($num == 1){
                $num = "次";
            }
            if($num >= 2){
                $num = $num + 1;
            }
            $headerTable[] = $num."日留存";
            if($num == '次'){
                //ltv左右两边增加付费率（左）和付费人数（右）
//                $headerTable[] = "付费率";
                if($type == "month"){
                    $headerTable[] = "当月LTV";
                }else if($type == "week"){
                    $headerTable[] = "当周LTV";
                }else{
                    $headerTable[] = "当日LTV";
                }

                $headerTable[] = "当日总收入";
                foreach($showList as $num2){
                    if($num2 == 0){
                        continue;
                    }
                    if($num2 >= 2){
                        $num2 = $num2 + 1;
                    }
                    $headerTable[] = "内购LTV".$num2;
                }
                foreach($showList as $num2){
                    if($num2 == 0){
                        continue;
                    }
                    if($num2 >= 2){
                        $num2 = $num2 + 1;
                    }
                    $headerTable[] = "内购付费LTV".$num2;
                }
//                $headerTable[] = "付费人数";
                $headerTable[] = "付费用户群";
            }
        }

        foreach($showList as $num){
            if($num == 0){
                continue;
            }
            if($num >= 2){
                $num = $num + 1;
            }
            $headerTable[] = "内购收入".$num;
        }

        foreach($showList as $num){
            if($num == 0){
                continue;
            }
            if($num >= 2){
                $num = $num + 1;
            }
            $headerTable[] = $num."日留存人数";
        }
        return $headerTable;
    }
    function getLtvThead2($showList,$type){
        $headerTable = ['日期','国家','版本','广告渠道','DAU','花费$','总安装','推广安装','自然量安装','自然量占比','买量CPI$','均价CPI$',
//            'AE','合格系数','有效投放金额(累计)',
//            '推广次留','自然量次留'
        ];
        switch ($type){
            case 'week':$dateType = '周';break;
            case 'month':$dateType = '月';break;
            default:return [];
        }
        foreach ($showList as $showIdx){
            if (empty($showIdx))continue;
            $headerTable[] = empty($showIdx) ? "首{$dateType}留存" : ++$showIdx."{$dateType}留存";
            $headerTable[] = empty($showIdx) ? "首{$dateType}留存人数" : ++$showIdx."{$dateType}留存人数";
        }

        $headerTable = array_merge($headerTable,['付费人数','付费率']);
        foreach ($showList as $showIdx){
            $headerTable[] = empty($showIdx) ? "首{$dateType}内购收入" : ++$showIdx."{$dateType}内购收入";
            $headerTable[] = empty($showIdx) ? "首{$dateType}付费人数" : ++$showIdx."{$dateType}付费人数";
            $headerTable[] = empty($showIdx) ? "首{$dateType}内购LTV" : ++$showIdx."{$dateType}内购LTV";
            $headerTable[] = empty($showIdx) ? "首{$dateType}内购付费LTV" : ++$showIdx."{$dateType}内购付费LTV";
        }
        return $headerTable;
    }

    //导出ltv数据
    public function exportLtvData($stime,$etime,$address,$trackers_group_type,$user_os,$type){
        $showList = [0,1,2,6,14,29,59,89,119];
        $headerTable = $this->getLtvThead($showList,$type);
        $extensionList = $this->extensionList;//推广渠道
        $periodList = [0,1,2,6,14,29,59,89,119];
        $bodyTable = $this->getAdjustData($stime,$etime,$type,$address,$trackers_group_type,$user_os,$extensionList,$periodList);

        $objPHPExcel = new PHPExcel();
        //处理表头
        foreach ($headerTable as $k => $v) {
            $strTemp = strval($this->headerTableChar($k)."1");
            $objPHPExcel->getActiveSheet()->setCellValue($strTemp, $v);
        }
        //处理数据
        $i = 2;
        if($type == "day"){
            $out = [];
            foreach($bodyTable as $date => $row){
                $out[date("Ymd",strtotime($date))] = $row;
            }
            $bodyTable = $out;
        }
        krsort($bodyTable,true);

        foreach($bodyTable as $date => $vos) {
            foreach ($vos as $countriesTemp => $vo) {
                foreach ($vo as $os_namesTemp => $v) {
                    $j = 0;
                    foreach ($v as $trackers_group_typeTemp => $row) {
                        $trackers_group_type == "all" && $row["spend"] += $row["spendGoogle"];
                        $extensionRemain = 0;//推广
                        if ($trackers_group_typeTemp == "all") {
                            $extensionRemain = $row["extensionRemain"] ?? 0;
                        } else if (in_array($trackers_group_typeTemp, $extensionList)) {
                            $extensionRemain = $row["period_1_kpis"][0] ?? 0;
                        }

                        $naturalRemain = 0;//自然
                        if($trackers_group_typeTemp == "all"){
                            $naturalRemain = $row["period_1_kpis"][0] - $row["extensionRemain"] ?? 0;
                        }else if(!in_array($trackers_group_typeTemp,$extensionList)){
                            $naturalRemain = $row["period_1_kpis"][0] ?? 0;
                        }
                        $extension = 0;
                        if($trackers_group_typeTemp == "all"){
                            $extension = $row["extension"] ?? 0;
                        }else if(in_array($trackers_group_typeTemp,$extensionList)){
                            $extension = $row["kpi_values"][1] ?? 0;
                        }
                        $natural = 0;
                        if($trackers_group_typeTemp == "all"){
                            $natural = $row["kpi_values"][1] - $row["extension"] ?? 0;
                        }else if(!in_array($trackers_group_typeTemp,$extensionList)){
                            $natural = $row["kpi_values"][1] ?? 0;
                        }
                        $Organic_all = 0;
                        if($trackers_group_typeTemp == "all"){
                            $Organic_all = number_format(($row["kpi_values"][1] - $row["extension"]) / $row["kpi_values"][1] * 100,2,".","") ?? 0;
                        }else if(!in_array($trackers_group_typeTemp,$extensionList)){
                            $Organic_all = "100";
                        }
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, $date);
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, $countriesTemp);
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, $os_namesTemp);
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, (strtolower($trackers_group_type) == 'share') ? 'Share' : $trackers_group_typeTemp);
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, $row["kpi_values"][0] ?? 0);
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, number_format($row["spend"],2,".","") ?? 0);
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, $row["kpi_values"][1] ?? 0);
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, $extension);
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, $natural);
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, $Organic_all."%");
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, empty($row["kpi_values"][1]) ? '' : number_format($row["spend"] / $row["kpi_values"][1],2,".","") ?? "");
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, empty($extension) ? '' : number_format($row["spend"] / $extension,2,".","") ?? "");
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, empty($extensionRemain) ? '' : number_format($row["spend"] / $extensionRemain,2,".","") ?? "");
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, empty($extension) ? '' : number_format($extensionRemain / $extension * 100,2,".","")."%" ?? "");
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, empty($natural) ? '' : number_format($naturalRemain / $natural * 100,2,".","")."%" ?? "");
                        //次日留存
                        $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, empty($row["kpi_values"][1]) ? '' : number_format($row["period_1_kpis"][0] / $row["kpi_values"][1] * 100,2,".","")."%" ?? '');
                        foreach($showList as $time){
                            if($time == 1){
                                continue;
                            }
                            if($time != 0 && $time != 1){
                                $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, empty($row["kpi_values"][1]) ? '' : number_format($row["period_{$time}_kpis"][0] / $row["kpi_values"][1] * 100,2,".","")."%" ?? '');
                            }
                            if($time == 0){
                                //ltv左右两边增加付费率（左）和付费人数（右）
                                $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, empty($row["kpi_values"][0]) ? '' : number_format($row["kpi_values"][2] / $row["kpi_values"][0],2,".","") ?? '');
                                $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, empty($row["kpi_values"][2]) ? '' : number_format($row["kpi_values"][2],2,".","") ?? '');
                                foreach($showList as $time2){
                                    if($time2 == 1){
                                        continue;
                                    }
                                    $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, empty($row["period_0_kpis"][0]) ? '' : number_format($row["period_{$time2}_kpis"][2] / $row["period_0_kpis"][0],2,".","") ?? '');
                                }
                                foreach($showList as $time2){
                                    if($time2 == 1){
                                        continue;
                                    }
                                    $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, empty($row["period_0_kpis"][3]) ? '' : number_format($row["period_{$time2}_kpis"][2] / $row["period_0_kpis"][3],2,".","") ?? '');
                                }
                                $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, empty($row["period_0_kpis"][3]) ? '' : round($row["period_0_kpis"][3]) ?? '');
                            }
                        }
                        //内购收入
                        foreach($showList as $time){
                            if($time == 0){
                                continue;
                            }
                            $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, number_format($row["period_{$time}_kpis"][2],2,".","") ?? 0);
                        }
                        //留存人数
                        foreach($showList as $time){
                            if($time == 0){
                                continue;
                            }
                            $objPHPExcel->getActiveSheet()->setCellValue($this->headerTableChar($j++).$i, round($row["period_{$time}_kpis"][0]) ?? 0);
                        }

                        $i++;
                    }
                }
            }
        }

        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $outPutFileName = 'ltv数据_'.date('Y-m-d');
        $this->base($objPHPExcel,$outPutFileName);


    }


    public function exportLoginRegReturned( ){
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        date_default_timezone_set("UTC");
        $sdate = $this->input->get('stime') ?? date("Y-m-d",strtotime("-100 days 0:0:0"));
        $edate = $this->input->get('etime') ?? date("Y-m-d",strtotime("-1 days 0:0:0"));
        $stime = strtotime($sdate);
        $etime = strtotime($edate);
        if(($etime - $stime) > 15 * 86400){
            $etime = $stime + 15 * 86400;
            $edate = date('Y-m-d', $etime);
        }
        $days = [
            1,3,4,5,6,7,8,15,30,60,90,120
        ];
        $os      = $this->input->get('user_os')  ?? 0;//版本
        $address = $this->input->get('country') ?? 'ALL';//国家
        $country = explode(',',$address) ?? ['ALL'];//国家
        $country = array_map(function($v){return strtoupper($v);}, $country);
        $uidMaps = [];
        $results = [];
        switch ($os){
            case 0:$osTitle = 'All';break;
            case 1:$osTitle = 'Android';break;
            case 2:$osTitle = 'IOS';break;
            default:
                $os = 0;
                $osTitle = 'All';
                break;
        }
        for ($i = $stime; $i<= $etime; $i+=86400){
            $date = date('Ymd', $i);
            if(empty($uidMaps[$date])){
                $uidMaps[$date]['regUids'] = $this->getRegUidsByDate($date, $os, $country);
                $loginUids = $this->getLoginUidsByDateOs($date, $os, $country);
                $loginUids = array_diff($loginUids, $uidMaps[$date]['regUids']);    #从登录uid中剔除注册uid
                $uidMaps[$date]['loginUids'] = array_values($loginUids);
            }
            $dauids = array_merge($uidMaps[$date]['regUids'], $uidMaps[$date]['loginUids']);
            $dauids = array_unique(array_filter($dauids));
            $tempLine = [
                'date' => $date,
                'os' => $osTitle,
                'country' => $address,
                'regCnt' => count($uidMaps[$date]['regUids']),
                'loginCnt' => count($uidMaps[$date]['loginUids']),
                'dau' => count($dauids),
            ];
            foreach ($days as $j){
                $dateJ = date('Ymd', strtotime("+{$j} days 0:0:0", $i));
                if(empty($uidMaps[$dateJ])){
                    $uidMaps[$dateJ]['regUids'] = $this->getRegUidsByDate($dateJ, $os, $country);
                    $loginUids = $this->getLoginUidsByDateOs($dateJ, $os, $country);
                    $loginUids = array_diff($loginUids, $uidMaps[$dateJ]['regUids']);    #从登录uid中剔除注册uid
                    $uidMaps[$dateJ]['loginUids'] = array_values($loginUids);
                }
                $tempLine['regReturn'.$j] = count(array_intersect($uidMaps[$date]['regUids'],$uidMaps[$dateJ]['loginUids']));
                $tempLine['regReturnRate'.$j] = empty($uidMaps[$date]['regUids']) ?
                    '0%':
                    number_format($tempLine['regReturn'.$j] / count($uidMaps[$date]['regUids'] )* 100, 4) . '%';

                $tempLine['loginReturn'.$j] = count(array_intersect($uidMaps[$date]['loginUids'],$uidMaps[$dateJ]['loginUids']));
                $tempLine['loginReturnRate'.$j] = empty($uidMaps[$date]['loginUids']) ?
                    '0%':
                    number_format($tempLine['loginReturn'.$j] / count($uidMaps[$date]['loginUids'] )* 100, 4) . '%';
            }
            $results[$date] = $tempLine;
        }
//        if($sort == "DESC"){
//            krsort($results,true);
//        }else{
//            ksort($results,true);
//        }
        $headers = [
            'date' => '日期',
            'os' => '版本',
            'country' => '国家',
            'dau' => 'DAU规模',
            'regCnt' => '注册人数',
            'loginCnt' => '登录人数',
        ];
        foreach ($days as $j){
            if($j == 1){
                $headers['regReturnRate'.$j] = '注册次日回头率';
            }else{
                $headers['regReturnRate'.$j] = '注册' . $j . '日回头率';
            }
        }
        foreach ($days as $j){
            if($j == 1){
                $headers['loginReturnRate'.$j] = '活跃次日回头率';
            }else{
                $headers['loginReturnRate'.$j] = '活跃' . $j . '日回头率';
            }
        }
        $file_name = '登录注册回头率-'.date('YmdHis') . '.csv';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename='.$file_name );
        header('Cache-Control: max-age=0');
        $f = fopen('php://output',"a");
        fputcsv($f, array_values($headers));
        foreach ($results as $date => $result){
            $line = [];
            foreach ($headers as $k => $v){
                $line[] = $result[$k] ?? '-';
            }

            fputcsv($f, $line);
        }
        fclose($f);
//        $data['list'] = $results;
//        $data['stime'] = $sdate;
//        $data['etime'] = $edate;
//        $data['user_os'] = $os;
//        $data["sort"] = $sort;
//        $data["days"] = $days;
//        $data["maxDays"] = $maxDays;
//        $data["headerTable"] = $headers;
//        $data["country"] = $country;
//        $data["address"] = $address;
//
//        $data["addressList"] = $this->getCountryList();
//
//        $this->load->view('report/loginRegReturned', $data);
    }
    public function loginRegReturned($sort = "DESC"){
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        date_default_timezone_set("UTC");
        $sdate = get_cookie('stime') ?? date("Y-m-d",strtotime("-16 days 0:0:0"));
        $edate = get_cookie('etime') ?? date("Y-m-d",strtotime("-1 days 0:0:0"));
        $maxDays = 120;
        $days = get_cookie('days') ?? $maxDays;
        $days = min($days, $maxDays);
        $stime = strtotime($sdate);
        $etime = strtotime($edate);
        if(($etime - $stime) > 15 * 86400){
            $etime = $stime + 15 * 86400;
            $edate = date('Y-m-d', $etime);
        }
        $days = [
            1,3,4,5,6,7,8,15,30,60,90,120
        ];
        $os = get_cookie('user_os') ?? 0;//版本
        $address = get_cookie('address') ?? 'ALL';//国家
        $country = explode(',',$address) ?? ['ALL'];//国家
        $country = array_map(function($v){return strtoupper($v);}, $country);
        $uidMaps = [];
        $results = [];
        switch ($os){
            case 0:$osTitle = 'All';break;
            case 1:$osTitle = 'Android';break;
            case 2:$osTitle = 'IOS';break;
            default:
                $os = 0;
                $osTitle = 'All';
                break;
        }
        for ($i = $stime; $i<= $etime; $i+=86400){
            $date = date('Ymd', $i);
            if(empty($uidMaps[$date])){
                $uidMaps[$date]['regUids'] = $this->getRegUidsByDate($date, $os, $country);
                $loginUids = $this->getLoginUidsByDateOs($date, $os, $country);
                $loginUids = array_diff($loginUids, $uidMaps[$date]['regUids']);    #从登录uid中剔除注册uid
                $uidMaps[$date]['loginUids'] = array_values($loginUids);
            }
            $dauids = array_merge($uidMaps[$date]['regUids'], $uidMaps[$date]['loginUids']);
            $dauids = array_unique(array_filter($dauids));
            $tempLine = [
                'date' => $date,
                'os' => $osTitle,
                'country' => $address,
                'regCnt' => count($uidMaps[$date]['regUids']),
                'loginCnt' => count($uidMaps[$date]['loginUids']),
                'dau' => count($dauids),
            ];
            foreach ($days as $j){
                $dateJ = date('Ymd', strtotime("+{$j} days 0:0:0", $i));
                if(empty($uidMaps[$dateJ])){
                    $uidMaps[$dateJ]['regUids'] = $this->getRegUidsByDate($dateJ, $os, $country);
                    $loginUids = $this->getLoginUidsByDateOs($dateJ, $os, $country);
                    $loginUids = array_diff($loginUids, $uidMaps[$dateJ]['regUids']);    #从登录uid中剔除注册uid
                    $uidMaps[$dateJ]['loginUids'] = array_values($loginUids);
                }
                $tempLine['regReturn'.$j] = count(array_intersect($uidMaps[$date]['regUids'],$uidMaps[$dateJ]['loginUids']));
                $tempLine['regReturnRate'.$j] = empty($uidMaps[$date]['regUids']) ?
                    '0%':
                    number_format($tempLine['regReturn'.$j] / count($uidMaps[$date]['regUids'] )* 100, 2) . '%';

                $tempLine['loginReturn'.$j] = count(array_intersect($uidMaps[$date]['loginUids'],$uidMaps[$dateJ]['loginUids']));
                $tempLine['loginReturnRate'.$j] = empty($uidMaps[$date]['loginUids']) ?
                    '0%':
                    number_format($tempLine['loginReturn'.$j] / count($uidMaps[$date]['loginUids'] )* 100, 2) . '%';
            }
            $results[$date] = $tempLine;
        }
        if($sort == "DESC"){
            krsort($results,true);
        }else{
            ksort($results,true);
        }
        $headers = [
            'date' => '日期',
            'os' => '版本',
            'country' => '国家',
            'dau' => 'DAU规模',
            'regCnt' => '注册人数',
            'loginCnt' => '登录人数',
        ];
        foreach ($days as $j){
            if($j == 1){
                $headers['regReturnRate'.$j] = '注册次日回头率';
            }else{
                $headers['regReturnRate'.$j] = '注册' . $j . '日回头率';
            }
        }
        foreach ($days as $j){
            if($j == 1){
                $headers['loginReturnRate'.$j] = '活跃次日回头率';
            }else{
                $headers['loginReturnRate'.$j] = '活跃' . $j . '日回头率';
            }
        }
        $data['list'] = $results;
        $data['stime'] = $sdate;
        $data['etime'] = $edate;
        $data['user_os'] = $os;
        $data["sort"] = $sort;
        $data["days"] = $days;
        $data["maxDays"] = $maxDays;
        $data["headerTable"] = $headers;
        $data["country"] = $country;
        $data["address"] = $address;

        $data["addressList"] = $this->getCountryList();

        $this->load->view('report/loginRegReturned', $data);
    }
    private function getRegUidsByDate($date, $os = 0, $country = ['DE']){
        if($date >= date('Ymd'))return [];
        if(in_array('ALL', $country))$country = ['ALL'];
        $cacheKey = 'REGUIDS'.$date."-".$os."-".implode($country);
        $cache = oo::commonOprRedis('Statistics')->get($cacheKey);
        if($cache){
//            return json_decode($cache,1);
        }
        $userTbl = otable::registerLog();
        $whereCountry = '';
        if(!empty($country) && !in_array('ALL', $country)){
            $countryStr = implode("','",$country);
            $whereCountry = " and tu.country in ('{$countryStr}')";
        }
        $sql = "select * from {$userTbl} tu where  `date`='{$date}' {$whereCountry}";
        if(!empty($os)){
            $loginTbl = otable::newloginLog($date);
            $sql = "select tu.uid,tl.sid from {$userTbl} tu left join {$loginTbl} tl on tu.uid=tl.uid  where  tu.`date`='{$date}' {$whereCountry} and tl.sid=".$os;
        }
        $results = oo::commonOprDb('report')->getAll($sql, 1);
        $uids = empty($results) ? [] : array_map(function($v){return $v['uid'];}, $results);
        $uids = array_filter(array_unique($uids));
        oo::commonOprRedis('Statistics')->setex($cacheKey,json_encode($uids),3600);
        return $uids;

    }
    private function getLoginUidsByDateOs($date, $os = 0, $country = []){
        if(in_array('ALL', $country))$country = ['ALL'];
        $cacheKey = 'DAUUIDS'.$date."-".$os."-".implode($country);
        $cache = oo::commonOprRedis('Statistics')->get($cacheKey);
        if($cache ){
            return json_decode($cache,1);
        }

        $loginTbl = otable::newloginLog($date);
        $where = ' where 1 ';
        if(!empty($os) && in_array($os, [1,2])){
            $where .= ' and sid='.$os;
        }
        if(!empty($country) && !in_array('ALL', $country)){
            $countryStr = implode("','",$country);
            $where .= " and country in ('{$countryStr}')";
        }

        $sql = "select uid from {$loginTbl}  {$where} group by uid";
        $results = oo::commonOprDb('report')->getAll($sql, 1);
        $uids = empty($results) ? [] : array_map(function($v){return $v['uid'];}, $results);
        $uids = array_filter(array_unique($uids));

        oo::commonOprRedis('Statistics')->setex($cacheKey,json_encode($uids),3600);
        return $uids;
    }



    public function iosDayReport($sort = "DESC"){
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        date_default_timezone_set("UTC");
        $sdate = get_cookie('stime') ?? date("Y-m-d",strtotime("-2 days 0:0:0"));
        $edate = get_cookie('etime') ?? date("Y-m-d",strtotime("-1 days 0:0:0"));
        $stime = strtotime($sdate);
        $etime = strtotime($edate);
        if(($etime - $stime) > 30 * 86400){
            $etime = $stime + 30 * 86400;
            $edate = date('Y-m-d', $etime);
        }
        $maxDays = 120;
        $os = 2;//get_cookie('user_os') ?? 0;//版本
        $address = get_cookie('address') ?? 'ALL';//国家
        $country = explode(',',$address) ?? ['ALL'];//国家
        $country = array_map(function($v){return strtoupper($v);}, $country);

        $days = [
            0,1,3,7,15,30
        ];

        $results = $this->getIosDayReportData($days, $sdate, $edate, $address, $sort);
        $headers = $this->getIosDayReportHeader($days);
        $data['list'] = $results;
        $data['stime'] = $sdate;
        $data['etime'] = $edate;
        $data['user_os'] = $os;
        $data["sort"] = $sort;
        $data["days"] = $days;
        $data["maxDays"] = $maxDays;
        $data["headerTable"] = $headers;
        $data["country"] = $country;
        $data["address"] = $address;

        $data["addressList"] = $this->getCountryList();

        $this->load->view('report/iosDayReport', $data);
    }
    public function exportIosDayReport(){
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        date_default_timezone_set("UTC");
        $days = [
            0,1,3,7,15,30
        ];

        $sdate = $this->input->get('stime') ?? date("Y-m-d",strtotime("-100 days 0:0:0"));
        $edate = $this->input->get('etime') ?? date("Y-m-d",strtotime("-1 days 0:0:0"));

        $address = $this->input->get('country') ?? 'ALL';//国家
        $sort = 'ASC';
        $results = $this->getIosDayReportData($days, $sdate, $edate, $address, $sort);
        $headers = $this->getIosDayReportHeader($days);
        $file_name = 'IOS日报-'.date('YmdHis') . '.csv';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename='.$file_name );
        header('Cache-Control: max-age=0');
        $f = fopen('php://output',"a");
        fputcsv($f, array_values($headers));
        foreach ($results as $date => $result){
            $line = [];
            foreach ($headers as $k => $v){
                $line[] = $result[$k] ?? '-';
            }
            fputcsv($f, $line);
        }
        fclose($f);
    }
    private function getIosDayReportData($days, $sdate,$edate,$address,$sort = 'DESC'){
        $country = explode(',',$address) ?? ['ALL'];//国家
        $country = array_map(function($v){return strtoupper($v);}, $country);
        $stime = strtotime($sdate);
        $etime = strtotime($edate);
        $uidMaps = [];
        $results = [];
        $os = 2;
        switch ($os){
            case 0:$osTitle = 'All';break;
            case 1:$osTitle = 'Android';break;
            case 2:$osTitle = 'IOS';break;
            default:
                $os = 0;
                $osTitle = 'All';
                break;
        }
        $validSpend = 0;
        for ($i = $stime; $i<= $etime; $i+=86400){
            $date = date('Ymd', $i);
            if(empty($uidMaps[$date])){
                $uidMaps[$date]['regUids'] = $this->getRegUidsByDate($date, $os, $country);
                $loginUids = $this->getLoginUidsByDateOs($date, $os, $country);
                $uidMaps[$date]['loginUidsAll'] = array_values($loginUids);
                $loginUids = array_diff($loginUids, $uidMaps[$date]['regUids']);    #从登录uid中剔除注册uid
                $uidMaps[$date]['loginUids'] = array_values($loginUids);
            }
            $dauids = $uidMaps[$date]['loginUidsAll'];
//            $dauids = array_unique(array_filter($dauids));
            $spend = $this->getFbSpend(date('Y-m-d', strtotime($date)),strtolower(implode(',', $country)),strtolower($osTitle))
                + $this->getGoogleSpend(date('Y-m-d', strtotime($date)),strtolower(implode(',', $country)),strtolower($osTitle))
                + $this->getIronsourceSpend(date('Y-m-d', strtotime($date)),strtolower(implode(',', $country)),strtolower($osTitle))
                + $this->getUnitySpend(date('Y-m-d', strtotime($date)),strtolower(implode(',', $country)),strtolower($osTitle))
                + $this->getApplovinSpend(date('Y-m-d', strtotime($date)),strtolower(implode(',', $country)),strtolower($osTitle))
                + $this->getChartboostSpend(date('Y-m-d', strtotime($date)),strtolower(implode(',', $country)),strtolower($osTitle))
                + $this->getMintegralSpend(date('Y-m-d', strtotime($date)),strtolower(implode(',', $country)),strtolower($osTitle))
                + $this->getAppleSpend(date('Y-m-d', strtotime($date)),strtolower(implode(',', $country)),strtolower($osTitle))
                + $this->getTikTokSpend(date('Y-m-d', strtotime($date)),strtolower(implode(',', $country)),strtolower($osTitle));
            $regPayedUsers = $this->getPayedUsers($date, $date, $uidMaps[$date]['regUids']);
            $allPayedUsers = $this->getPayedUsers($date, $date, $dauids);
            $allPayedSum = array_sum($allPayedUsers);
            $regCnt = count($uidMaps[$date]['regUids']);
            $payCnt = count($regPayedUsers);
            $paySum = array_sum($regPayedUsers);
            $tempLine = [
                'date' => $date,
                'os' => $osTitle,
                'country' => $address,
                'regCnt' => $regCnt,
                'loginCnt' => count($uidMaps[$date]['loginUids']),
                'dau' => count($dauids),
                'spend' => number_format($spend, 2),
                'cpi' => empty($regCnt) ? 0.00 : number_format($spend/$regCnt, 2),
                'payCnt' => $payCnt,
                'paySum' => $paySum,
                'payRate' => empty($regCnt) ? '0.00%' : number_format($payCnt/$regCnt*100, 2) . '%',
                '1arpu' => empty($regCnt) ? '0.00' : number_format($paySum/$regCnt, 2) ,
                '1arppu' => empty($payCnt) ? '0.00' : number_format($paySum/$payCnt, 2) ,
                'allPayed' => number_format($allPayedSum , 2),
                'fcPayed' => number_format($allPayedSum * $this->fcce, 2),
            ];
            foreach ($days as $j){
                $dateJ = date('Ymd', strtotime("+{$j} days 0:0:0", $i));
                if(empty($uidMaps[$dateJ])){
                    $uidMaps[$dateJ]['regUids'] = $this->getRegUidsByDate($dateJ, $os, $country);
                    $loginUids = $this->getLoginUidsByDateOs($dateJ, $os, $country);
                    $uidMaps[$dateJ]['loginUidsAll'] = array_values($loginUids);
                    $loginUids = array_diff($loginUids, $uidMaps[$dateJ]['regUids']);    #从登录uid中剔除注册uid
                    $uidMaps[$dateJ]['loginUids'] = array_values($loginUids);
                }
                $regReturnUids = array_intersect($uidMaps[$date]['regUids'],$uidMaps[$dateJ]['loginUidsAll']);
                $tempLine['regReturn'.$j] = count($regReturnUids);
                $tempLine['regReturnRate'.$j] = empty($uidMaps[$date]['regUids']) ? 0 : $tempLine['regReturn'.$j] / count($uidMaps[$date]['regUids'] ) ;
                $tmpPayedUsers = $this->getPayedUsers($date, $dateJ, $uidMaps[$date]['regUids']);
                $incomeMoney = array_sum($tmpPayedUsers);
                $tempLine['income'.$j] = number_format($incomeMoney, 2);
                $tempLine['roi'.$j] = empty($spend) ? 0 : (($incomeMoney * $this->fcce)/$spend);
                if($j == 7){
                    $tempLine['ae'] = $this->getAE($tempLine['regReturnRate'.$j], $tempLine['roi'.$j]);
                    $tempLine['ce'] = $this->getCE($tempLine['ae']);
                    $validSpend += $tempLine['ce'] * $spend;
                    $tempLine['validSpend'] = number_format($validSpend, 2);
                }
                $tempLine['roi'.$j] = number_format($tempLine['roi'.$j]*100, 2).'%';
                $tempLine['regReturnRate'.$j] = number_format($tempLine['regReturnRate'.$j]*100, 2).'%';
            }
            $results[$date] = $tempLine;
        }
        if($sort == "DESC"){
            krsort($results,true);
        }else{
            ksort($results,true);
        }
        return $results;
    }
    private function getIosDayReportHeader($days){
        $headers = [
            'date' => '日期',
            'os' => '版本',
            'country' => '国家',
            'dau' => 'DAU规模',
            'spend' => '广告花费',
            'ae' => 'AE',
            'ce' => '合格系数',
            'validSpend' => '有效投放金额(累计)',
            'regCnt' => '注册人数',
            'cpi' => 'cpi',
            'payCnt' => '首日付费人数',
            'payRate' => '首日付费率',
            '1arpu' => '首日ARPU',
            '1arppu' => '首日ARPPU',
            'allPayed' => '内购收入' ,
            'fcPayed' =>'分成后内购收入',
//            'paySum' => '首日付费金额',
//            'loginCnt' => '登录人数',
        ];
        foreach ($days as $j){
            if($j == 0){
                $headers['regReturnRate'.$j] = '首日留存';
            }elseif($j == 1){
                $headers['regReturnRate'.$j] = '次日留存';
            }else{
                $headers['regReturnRate'.$j] =  $j . '日留存';
            }
        }
        foreach ($days as $j){
            if($j == 0){
                $headers['income'.$j] = '首日内购收入';
            }elseif($j == 1){
                $headers['income'.$j] = '次日内购收入';
            }else{
                $headers['income'.$j] =  $j . '日内购收入';
            }
        }
        foreach ($days as $j){
            if($j == 0){
                $headers['roi'.$j] = '首日ROI';
            }elseif($j == 1){
                $headers['roi'.$j] = '次日ROI';
            }else{
                $headers['roi'.$j] =  $j . '日ROI';
            }
        }
        return $headers;
    }
    private function getPayedUsers($sdate, $edate, $uids = false){
        $stime = strtotime($sdate);
        $etime = strtotime($edate) + 86400;
        if($uids !== false){
            if(empty($uids))return [];
            $uidStr = implode(',', $uids);
            $whereUids = " and sl_uid in ({$uidStr})";
            $whereOrderUids = " and uid in ({$uidStr})";
        }
        $payInfo = [];
        $tbl = otable::summarylist();
        $sql = "select sl_uid,sl_pusd from {$tbl} where sl_pay_time >={$stime} and sl_pay_time <={$etime} and sl_status=2 {$whereUids}";
        $payRecords = oo::commonOprDb('gameslave')->getAll($sql, 1);

        $minYear = 2022;
        $sYear = max(date('Y', $stime), $minYear);
        $eYear = max(date('Y', $etime), $minYear);
        $sdate = date('Y-m-d 00:00:00', $stime);
        $edate = date('Y-m-d 00:00:00', $etime);
        for($tmpYeay = $sYear;$tmpYeay<= $eYear; $tmpYeay++){
            $tbl = otable::order($tmpYeay);
            $sql = "select uid as sl_uid,price as sl_pusd from {$tbl} where created_at >='{$sdate}' and created_at <='{$edate}' and status=4 {$whereOrderUids}";
            $payRecords = array_merge($payRecords, (array)oo::commonOprDb('gameslave')->getAll($sql, 1));
            break;
        }

        $tbl = otable::gameOrder();
        $sql = "select uid as sl_uid,price as sl_pusd from {$tbl} where created_at >='{$sdate}' and created_at <='{$edate}' and status=4 {$whereOrderUids}";
        $payRecords = array_merge($payRecords, (array)oo::commonOprDb('gameslave')->getAll($sql, 1));

        foreach ($payRecords as $record){
            $payInfo[$record['sl_uid']] += $record['sl_pusd'];
        }
        $payInfo = array_filter($payInfo);
        return $payInfo;
    }

    public function cpis(){
        $cpiList = oo::commonOprDb('report')->getAll('select * from '.otable::wmcpi());
        $cpiList = array_column($cpiList, 'cpi', 'name');
        $columns = [];
        foreach ($cpiList as $name => $cpi){
            $columns[$name] = $this->inputField("config[{$name}]", $name, 'text', $cpi);
        }
        $data = [
            'title' => '网盟CPI编辑',
            'columns' => $columns,
            'saveUrl' => '/adjuststa/cpisSave',
        ];
        $this->load->view('common/commonForm', $data);
    }
    public function cpisSave(){
        $input = $this->input->post();
        $tbl = otable::wmcpi();
        $res = [];
        foreach ($input['config'] as $name => $cpi){
            $res[$name] = oo::commonOprDb('report')->query("update {$tbl} set `cpi`='{$cpi}' where `name`='{$name}'");
        }
        $this->response(1, '保存成功', $res);
    }
}