<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Created by liqx.
 * User: Administrator
 * Date: 2018/1/31
 * Time: 11:35
 */
class Advertisement extends MY_Controller
{
    public $postData = array('frombg' => 1, 'mod' => '', 'act' => '', 'lid' => 1, 'sid' => 1);
    public $channel = ['firebase','facebook'];

    public function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->library('curl');
        $this->_url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
    }


    public function index(){
        //获取数据
        $postData = $this->postData;
        $postData['mod'] = 'Advertisement';
        $postData['act'] = 'listFunction';
        $res = $this->curl->req($this->_url, $postData);
        $res = json_decode($res, TRUE);
        foreach ($res as $key=>$row){
            $res[$key]['trueId']     = json_decode($row['trueId'],true);
            $res[$key]['trueId_ios'] = json_decode($row['trueId_ios'],true);
            $res[$key]['weights']    = json_decode($row['weights'],true);
        }
        $postData['mod'] = 'Advertisement';
        $postData['act'] = 'getCache';
        $cache = $this->curl->req($this->_url, $postData);
        $cache = json_decode($cache, TRUE);

        $channel = [];
        foreach ($this->channel as $row){
            $channel[$row] = $cache[$row]??0;
        }

        $this->load->view('advertisement/index', ['list'=>$res,'channel'=>$channel]);
    }


    /**
     * 加载编辑活动页面
     */
    public function edit($id)
    {
        $postData = $this->postData;
        $postData['id'] = $id;
        $postData['mod'] = 'Advertisement';
        $postData['act'] = 'listFunction';
        $res = $this->curl->req($this->_url, $postData);
        $info = json_decode($res, TRUE);
        $info['reward']     = json_decode($info['reward'],true);
        $info['trueId']     = json_decode($info['trueId'],true);
        $info['trueId_ios'] = json_decode($info['trueId_ios'],true);
        $info['weights']    = json_decode($info['weights'],true);
        $info['channel']    = $this->channel;
        $this->load->view('advertisement/edit', ['info'=>$info]);
    }


    public function editAction(){
        $input = $this->input->post();
        if(array_sum($input['weights']) != 10){
            die(json_encode(['referer' =>'', 'refresh' => 'false', 'state' => 'error', 'message' => '权重和不为10']));
        }
        $data  = [
            'id'  => $input['id'],
            'data'=> [
                'trueId'    =>$input['trueId'],
                'trueId_ios'=>$input['trueId_ios'],
                'weights'   =>$input['weights'],
                'defChannel'=>$input['defChannel'],
                'name'      =>$input['name'],
                'max'       =>$input['max'],
                'status'    =>$input['status'],
            ],
        ];
        $json = [];
        if(isset($input['money']) && isset($input['spins'])){
            $json = [
                'specialReward'=>0,
                'reward'=>[
                    'money'=>$input['money'],
                    'spins'=>$input['spins'],
                ]
            ];
        }else if(isset($input['money'])){
            $json = [
                'specialReward'=>0,
                'reward'=>[
                    'money'=>$input['money'],
                ]
            ];
        }else if(isset($input['spins'])){
            $json = [
                'specialReward'=>0,
                'reward'=>[
                    'spins'=>$input['spins'],
                ]
            ];
        }

        if(!empty($json)){
            $data['data']['reward'] = json_encode($json,JSON_NUMERIC_CHECK);
        }


        $postData = $this->postData;
        $postData['mod'] = 'Advertisement';
        $postData['act'] = 'save';
        $postData['data'] = json_encode($data);
        $res = $this->curl->req($this->_url, $postData);
        if($res == 0){
            die(json_encode(['referer' =>'', 'refresh' => 'false', 'state' => 'error', 'message' => '']));
        }else{
            die(json_encode(['state' =>'success', 'message'=>'成功', 'refresh' => true,]));
        }
    }

    public function cacheAction(){
        $input = $this->input->post();
        $postData = $this->postData;
        $postData['mod'] = 'Advertisement';
        $postData['act'] = 'saveCache';
        $postData['data'] = json_encode($input);
        $this->curl->req($this->_url, $postData);
    }

    /**
     * 统计
     */
    public function sta($type = 1)
    {
    	
        $url = $this->config->item('officialUrl');
        if($sdate = get_cookie('detail_stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        if($edate = get_cookie('detail_etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }
    	
        $date     = [];
        $dateTemp = [];
        $stime = $data['stime'];
        for($i=1;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']) + 1;$i++){
            $date[] = date('Ymd', strtotime("$stime + $i days"));
            $j = $i -1;
            $dateTemp[] = date('Ymd', strtotime("$stime + $j days"));
        }

        $date = implode(',',$date);

        $postData = $this->postData;
        $postData['mod'] = 'Advertisement';
        $postData['act'] = 'getSta';
        $postData['date']= $date;
        $res = $this->curl->req($this->_url, $postData);
        $res = json_decode($res,true);
        $postData['mod'] = 'Advertisement';
        $postData['act'] = 'listFunction';
        $retData = $this->curl->req($url, $postData);
        $ret = json_decode($retData, TRUE);

        $data['date'] = implode(',',$dateTemp);
        $success = ['android'=>[], 'ios'=>[]];
        $play    = ['android'=>[], 'ios'=>[]];
        $click   = ['android'=>[], 'ios'=>[]];
        foreach ($res as $row){
            $temp = json_decode($row['success'],true);
            $success['android'][] = array_sum($temp['android']);
            $success['ios'][] = array_sum($temp['ios']);

            $temp = json_decode($row['play'],true);
            //兼容旧数据
			if(isset($temp['android']) && isset($temp['ios'])){
				$play['android'][] = array_sum($temp['android']);
            	$play['ios'][] = array_sum($temp['ios']);
			}else{
				$play['android'][] = array_sum($temp);
            	$play['ios'][] = array_sum($temp);
			}
            
            $temp = json_decode($row['click'],true);
            //兼容旧数据
            if(isset($temp['android']) && isset($temp['ios'])){
            	$click['android'][] = array_sum($temp['android']);
            	$click['ios'][] = array_sum($temp['ios']);
            }else{
            	$click['android'][] = array_sum($temp);
            	$click['ios'][] = array_sum($temp);
            }
        }

        $data['success'] = $success;
        $data['play']    = $play;
        $data['click']   = $click;

        $android = [];
        foreach ($ret as $row){
            $temp['name'] = $row['name'];
            $temp['success'] = [];
            $temp['play'] = [];
            $temp['click'] = [];
            foreach ($res as $day){
                $tempDay = json_decode($day['success'],true);
                $temp['success'][] = $tempDay['android'][$row['id']]??0;

                $tempDay = json_decode($day['play'],true);
                //兼容旧数据
                if(isset($tempDay['android'])){
                	$temp['play'][] = $tempDay['android'][$row['id']]??0;
                }else{
                	$temp['play'][] = $tempDay[$row['id']]??0;
                }
                
                $tempDay = json_decode($day['click'],true);
                //兼容旧数据
                if(isset($tempDay['android'])){
                	$temp['click'][] = $tempDay['android'][$row['id']]??0;
                }else{
                	$temp['click'][] = $tempDay[$row['id']]??0;
                }
                
            }
            $android[] = $temp;
        }
        $data['android'] = $android;

        $ios = [];
        foreach ($ret as $row){
            $temp['name'] = $row['name'];
            $temp['success'] = [];
            $temp['play'] = [];
            $temp['click'] = [];
            foreach ($res as $day){
                $tempDay = json_decode($day['success'],true);
                $temp['success'][] = $tempDay['ios'][$row['id']]??0;

                $tempDay = json_decode($day['play'],true);
                //兼容旧数据
                if(isset($tempDay['ios'])){
                	$temp['play'][] = $tempDay['ios'][$row['id']]??0;
                }else{
                	$temp['play'][] = $tempDay[$row['id']]??0;
                }
                
                $tempDay = json_decode($day['click'],true);
                //兼容旧数据
                if(isset($tempDay['ios'])){
                	$temp['click'][] = $tempDay['ios'][$row['id']]??0;
                }else{
                	$temp['click'][] = $tempDay[$row['id']]??0;
                }
                
            }
            $ios[] = $temp;
        }
        $data['ios'] = $ios;
		
		if($type == 1){
			$this->load->view('advertisement/sta', $data);
		}else{
			$this->load->view('advertisement/sta2', $data);
		}
    }
	
	public function diffBetweenTwoDays ($day1, $day2){
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);

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