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

/**
*	广告商广告效果统计相关
*/
class Advertiser extends MY_Controller{

	public $data = array('referer' =>'', 'refresh' => false, 'state' => 'error', 'message' => '');

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

	public $adPlatform = array(1 => 'Android', 2 => 'IOS');//广告投放平台

	protected $page = 20;//分页

	protected $pageConfig = array(
					'first_tag_open' => '<li>',
					'first_tag_close' => '</li>',
					'last_tag_open' => '<li>',
					'last_tag_close' => '</li>',
					'next_tag_open' => '<li>',
					'next_tag_close' => '</li>',
					'prev_tag_open' => '<li>',
					'prev_tag_close' => '</li>',
					'cur_tag_open' => "<li class='active'><a hef='#'>",
					'cur_tag_close' => "</a></li>",
					'num_tag_open' => "<li>",
					'num_tag_close' => "</li>",
				);

	public function __construct()
	{
		parent::__construct();
		$this->load->helper('url');
		$this->load->helper('cookie');
		$this->load->library('curl');
		$this->load->library('pagination');
		$this->load->database();

		//请求地址
		$this->env = get_cookie($this->_wenenv);
		$this->_url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
	}


	/**
	*	广告商效果
	*/
	public function index()
	{
		$data = array();

		//时间查询
		$dateArr = array();
		if( $stime = get_cookie('ad_start_time') ){
			$data['stime'] = $stime;
			//$dateArr['stime'] = strtotime($stime.'1:0:0');
			$sqlStime = strtotime($stime.'1:0:0') - 14*86400;//由于需要算7日ROI, 所以开始时间要拿到前7天的值
			$showStime = strtotime($stime.'1:0:0');
		}else{
			$sqlStime = strtotime('-14 days 1:0:0') ;//默认开始时间
			$showStime = strtotime('-7 days 1:0:0') ;
			$data['stime'] = date('Y-m-d', strtotime('-7 days 1:0:0'));
		}

		if( $etime = get_cookie('ad_end_time') ){
			$data['etime'] = $etime;
			$dateArr['etime'] = strtotime($etime.'23:59:59');
		}else{
			$dateArr['etime'] = strtotime('-1 days 23:59:59');//默认结束时间
			$data['etime'] = date('Y-m-d', $dateArr['etime']);
		}

		//获取新增数据
		$postData = array_merge($dateArr, array('stime' => $showStime), $this->postdata);
		$postData['mod'] = 'Statistics';
		$postData['act'] = 'newplayer';
		$this->env == 2 && $postData['demo'] = 1;
		$res = $this->curl->req($this->_url, $postData);
		$retData = json_decode($res, TRUE);//每日新增数据
		$newplayerList = array();
		if (is_array($retData)) {
			foreach ($retData as $day => $value) {
				$d = date('Ymd', strtotime($day));
				$newplayerList[$d] = $value[0]['total'];
			}
		}

		

		//获取广告商
		$data['click_adList'] = array();
		$click_adList = get_cookie('adname');
		$where = '';
		if (!empty($click_adList)) {
			$click_adList = json_decode($click_adList,1);
			if (is_array($click_adList)) {
				$data['click_adList'] = $click_adList;
				$adListStr = implode(',', $click_adList);
				$where .= " AND ad_id IN ({$adListStr}) ";
			}
		}

		//获取广告商名称
		$adQuery = $this->db->get_where('advertiser', array('ad_status' => 1));
		$adRes = $adQuery->result_array();

		//获取广告商数据
		$sql = "SELECT info.*, ad.ad_name FROM ad_inf AS info LEFT JOIN advertiser AS ad ON info.ad_id = ad.id WHERE info.ad_time >= {$sqlStime} AND info.ad_time <= {$dateArr['etime']} {$where} ORDER BY info.ad_time DESC";
		$query = $this->db->query($sql);
		$adInfoList = $query->result_array();
		$date = array();
		foreach ($adInfoList as $k => $val) {
			
			//计算7日ROI
			$roi7dayList = $this->compute7Roi($val['ad_time'], $val['ad_id'], $adInfoList);
			$adInfoList[$k]['roi7day'] = $roi7dayList['roi'];
			$adInfoList[$k]['income7day'] = $roi7dayList['income'];
			$adInfoList[$k]['cost7day'] = $roi7dayList['cost'];
		}

		/*
		*	过滤多余的数据, 因为计算7日ROI,所以多计算了7天的数据
		*	按照天数来筛选记录
		*/
		$adInstall = $adMoney = 0;//广告安装, 广告花费
		$dailyReport = array();
		foreach ($adInfoList as $tempKey => $tempVal) {
			if ($tempVal['ad_time'] < $showStime) {
				unset($adInfoList[$tempKey]);
				continue;
			}
			$tempDay = date('Ymd',$tempVal['ad_time']);
			$dailyReport[$tempDay][] = $tempVal;
			$adInstall += $tempVal['ad_num'];
			$adMoney += $tempVal['ad_money'];
		}

		$data['totalAdInstall'] = $adInstall;
		$data['totalAdMoney'] = $adMoney;
		$data['adList'] = $adRes;
		$data['newplayerList'] = $newplayerList;
		$data['dailyReport'] = $dailyReport;
		$data['platform'] = $this->adPlatform;
		$this->load->view('advertiser/index2', $data);
	}

	/**
	*	添加广告商
	*/
	public function addadver()
	{
		$name = $this->input->post('adname');
		$data = array(
			'ad_name' => $name,
			'ad_status' => 1,
			'ad_time'	=> time(),
		);
		$this->db->insert('advertiser', $data);
		$this->data['state'] = 'success';
		die(json_encode($this->data));
	}

	/**
	*	渠道商列表
	*/
	public function adverList($p = 0)
	{
		$data = array();

		$query = $this->db->get('advertiser', $this->page, $p);
		$list = $query->result_array();
		$data['list'] = $list;
		//分页
		$pageConfig = $this->pageConfig;				
		$pageConfig['base_url'] = base_url('#advertiser/adverList');
		$data['total'] = $pageConfig['total_rows'] = $this->db->count_all('advertiser');
		$pageConfig['per_page'] = $this->page;
		$this->pagination->initialize($pageConfig);
		$pageurl = $this->pagination->create_links();
		$data['pageurl'] = $pageurl;
		$this->load->view('advertiser/adverlist', $data);
	}

	/**
	*	添加广告商打广告的数据
	*/
	public function addInfo()
	{
		$ad_id = $this->input->post('ad_id');
		$ad_num = $this->input->post('ad_num');
		$ad_money = $this->input->post('ad_money');
		$ad_platform = $this->input->post('ad_platform');
		$ad_install_lc = $this->input->post('ad_install_lc');//安装留存
		//$ad_zr_lc = $this->input->post('ad_zr_lc');//自然留存
		$ad_time = $this->input->post('ad_time');//录入时间


		//获取留存数据
		$postData = $this->postdata;
		$postData['stime'] = strtotime($ad_time.' 0:1:1');
		$postData['etime'] = strtotime($ad_time.' 23:59:59');
		$postData['mod'] = 'Remain';
        $postData['act'] = 'index';
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($this->_url, $postData);
        $retData = json_decode($res, 1);
        $day1remain = 0;//自然留存
        if (is_array($retData)) {
        	$day1remain = $retData['day1Remain'][0];
        }

        //获取当天的收入
        $postData['mod'] = 'Payment';
        $postData['act'] = 'getDailyIncome';
        $this->env == 2 && $postData['demo'] = 1;
        $res = $this->curl->req($this->_url, $postData);
        $retData_payment = json_decode($res, 1);
        $income = $retData_payment['money'];

		$data = array(
			'ad_id' => $ad_id,
			'ad_num' => $ad_num,
			'ad_money' => $ad_money,
			'ad_platform' => $ad_platform,
			'ad_install_lc' => $ad_install_lc,
			'ad_zr_lc' => $day1remain,
			'ad_time'	=> strtotime($ad_time.' 9:0:0'),
            'ad_income' => $income,
		);
		$this->db->insert('ad_inf', $data);
		$this->data['state'] = 'success';
		$this->data['refresh'] = true;
		die(json_encode($this->data));
	}

	/**
	*	编辑
	*/
	public function ajaxEdit()
	{
		$adId = $this->input->post('adid');
		$colname = $this->input->post('colname');
		$val = $this->input->post('val');
		
		$data = array(
		    $colname => $val,
		);
		$this->db->where('id', $adId);
		$this->db->update('ad_inf', $data);
	}

	/**
	*	编辑广告
	*/
	public function editad($id = 0)
	{
		$data = array();
		//广告商列表
		$query = $this->db->get('advertiser');
		$data['adList'] = $query->result_array();
		$query = $this->db->get_where('ad_inf', array('id' => $id));
		$row = $query->row_array();
		$data['info'] = $row;
		$data['adPlatform'] = $this->adPlatform;
		$this->load->view('advertiser/editad', $data);
	}

    /**
     * 编辑广告数据
     */
	public function actionedit(){

        $id = $this->input->post('id');
        $ad_id = $this->input->post('ad_id');
        $ad_num = $this->input->post('ad_num');
        $ad_money = $this->input->post('ad_money');
        $ad_platform = $this->input->post('ad_platform');
        $ad_install_lc = $this->input->post('ad_install_lc');
        $ad_zr_lc = $this->input->post('ad_zr_lc');
        $ad_time = $this->input->post('ad_time');
        $ad_income = $this->input->post('ad_income');

        $sql_data = array(
            'id' => $id,
            'ad_id'  => $ad_id,
            'ad_num'  => $ad_num,
            'ad_money'  => $ad_money,
            'ad_platform'  => $ad_platform,
            'ad_install_lc'  => $ad_install_lc,
            'ad_zr_lc'  => $ad_zr_lc,
            'ad_time'  => strtotime($ad_time." 10:0:0"),
            'ad_income'  => $ad_income,
        );

        $this->db->replace('ad_inf', $sql_data);

        $this->data['state'] = 'success';
        $this->data['message'] = '更新成功';
        die(json_encode($this->data));
    }

	/**
	*	删除广告
	*/
	public function delAd()
	{
		$adId = $this->input->post('adid');
		$this->db->delete('ad_inf', array('id' => $adId));
	}

	/**
	*	删除广告商
	*/
	public function delAdver()
	{
		$adId = $this->input->post('adid');
		$this->db->delete('advertiser', array('id' => $adId));
	}

	/**
	*	添加adyes数据
	*/
	public function addAdYesInfo()
	{
		$stime = '20180123';
		$etime = '20180226';
		$postData = array_merge(array('stime' => $stime, 'etime' => $etime, 'length' => 100, 'start' => 0), $this->postdata);
		$postData['mod'] = 'Statistics';
		$postData['act'] = 'report';
		$this->env == 2 && $postData['demo'] = 1;
		$res = $this->curl->req($this->_url, $postData);
		$retData = json_decode($res, 1);

		if (is_array($retData)) {
			// foreach ($retData['list'] as $v) {
			// 	$data = array(
			// 	    'ad_id' => 7,
			// 	    'ad_num' => $v['install'],
			// 	    'ad_money' => $v['expend'],
			// 	    'ad_platform' => 1,
			// 	    'ad_install_lc' => 0,
			// 	    'ad_zr_lc' => 0,
			// 	    'ad_time' => strtotime($v['date']) + 5*3600,
			// 	    'ad_income' => 0,
			// 	);
			// 	$this->db->insert('ad_inf', $data);
			// }
		}
	}


	/**
	*	计算7日ROI
	*/
	public function compute7Roi($time, $aid, $list)
	{
		$data = array('income' => 0, 'cost' => 0, 'roi' => 0);
		$day = 7;
		$allIncome = $allCost = 0; //总收入和总花费
		for ($i=1; $i <= $day; $i++) {
			$tempTime = date('Ymd',$time - $i*86400);
			foreach ($list as $val) {
				if (date('Ymd',$val['ad_time']) == $tempTime && $val['ad_id'] == $aid) {
					$allIncome += $val['ad_income'];
					$allCost += $val['ad_money'];
				}
			}
		}
		if ($allCost == 0) {
			return $data;
		}
		$data['income'] = $allIncome;
		$data['cost'] = $allCost;
		$data['roi'] = round(($allIncome - $allCost)/$allCost, 4);;
		return $data;
	}

}