<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: huajie <banhuajie@163.com>
// +----------------------------------------------------------------------

namespace Admin\Model;
use Think\Model;

/**
 * 投放平台数据模型
 * @author 鹿文学
 */
class LaunchDataModel extends Model{

    

    /* 自动验证规则 */
    protected $_validate = array(
        
    );

    /* 自动完成规则 */
    protected $_auto = array(
       
    );

    /**
     * 构造函数
     * @param string $name 模型名称
     * @param string $tablePrefix 表前缀
     * @param mixed $connection 数据库连接信息
     */
    public function __construct($name = '', $tablePrefix = '', $connection = '') {
        /* 设置默认的表前缀 */
        $this->tablePrefix ='tab_';
        /* 执行构造方法 */
        parent::__construct($name, $tablePrefix, $connection);
    }

		
		/**
		 * 投放数据列表(截止到昨天)
		 * @param 	integer  	$p  		页码
     * @param 	array  		$map  	条件数组
     * @param 	array  		$time  	时间数组
     * @return 	array    	结果数据集
     * @author 	鹿文学 
     */
		public function lists($p=1,$map=array(),$time=array()) {
			
			$page = intval($p);
      $page = $page ? $page : 1;
			
			
			if(isset($_REQUEST['row'])) {$row = $_REQUEST['row'];}else{$row = 10;}
			
			
			if(empty($map)) {/* 查询全部数据,无条件,只有时间 */
				
				$time['mark']=1;
				
				$map = $time;
				
				$lists = $this->where($time)->page($page,$row)->order('duration desc')->select();
				
				$count = $this->where($time)->count();
				
			} else {
				
				$group = 'duration,' . implode(',',array_keys($map));
				
				$map = array_merge($time,$map);
				
				$map['mark']=0;
				
				$lists = $this->field($group.',sum(new) as new,sum(new_device) as new_device,sum(new_pay) as new_pay,sum(new_money) as new_money,sum(active) as active,sum(active_pay) as active_pay,sum(active_money) as active_money')
					->where($map)->group($group)->order('duration desc')->page($page,$row)->select();
				
				
				$countresult = $this->field($group)->where($map)->group($group)->select();
				
				$count = count($countresult);
				
				foreach($lists as $k => $v) {
					
					$lists[$k] = $this->data_assembly($v);
					
				}
				
				
				
			}	
		
			$current = $this->accumulation([],$lists);
			
			$data['data'] = $lists;
			$data['current'] = $this->data_assembly($current);
			$data['total'] = $this->data_total($map);
			
			$page = set_pagination($count,$row);
			if($page) {$data['page']=$page;}
			
			return $data;
			
		}
		
		/**
		 * 全部汇总
		 * @param		array		$map		条件数组
		 * @param		array		$data 	要累加求和的数组数据(可选)
		 * @return	array		全部汇总数据
		 * @author 鹿文学
		 */
		public function data_total($map,$data=array()) {
			
			$totalresult = $this->field('sum(new) as new,sum(new_device) as new_device,sum(new_pay) as new_pay,sum(new_money) as new_money,sum(active) as active,sum(active_pay) as active_pay,sum(active_money) as active_money')
					->where($map)->order('duration desc')->select();			
			
			$total = $totalresult[0];
			
			if(!empty($data)) {			
				
				$total = $this->accumulation($total,$data);	
				
			}
			
			return $this->data_assembly($total);
			
		}
		
		/**
		 * 数据累加
		 * @param		array		$total		原数据
		 * @param		array		$data			要加入的数据(可以二维)
		 * @return	array		累加后的数组
		 * @author 鹿文学
		 */
		public function accumulation($total,$data) {
			if(count($data) !== count($data,1)) {
				foreach($data as $k => $v){
					$total['new'] += $v['new'];
					$total['new_device'] += $v['new_device'];
					$total['new_pay'] += $v['new_pay'];
					$total['new_money'] += $v['new_money'];
					$total['active'] += $v['active'];
					$total['active_pay'] += $v['active_pay'];
					$total['active_money'] += $v['active_money'];					
				}					
			} else {
				
				$total['new'] += $data['new'];
				$total['new_device'] += $data['new_device'];
				$total['new_pay'] += $data['new_pay'];
				$total['new_money'] += $data['new_money'];
				$total['active'] += $data['active'];
				$total['active_pay'] += $data['active_pay'];
				$total['active_money'] += $data['active_money'];
				
			}
			
			return $total;
			
		}
		
		
		
		/**
		 * 投放数据列表(截止到昨天)
		 * @param 	integer  	$p  			页码
		 * @param 	integer  	$row  		每页条数
     * @param 	array  		$map  		条件数组
     * @param 	array  		$time  		时间数组		      * @param 	array  		$offset  	偏移量
     * @return 	array    	结果数据集
     * @author 	鹿文学 
     */
		public function data($p=1,$row=10,$map=array(),$time=array(),$offset=0) {
			
			if($p>1) {
				$start_row = ($p-1)*$row-$offset;
			} else {
				$row = $row-$offset;$start_row=0;
			}
			
			if(empty($map)) {
				
				
				$time['mark']=1;
				
				$lists = $this->where($time)->limit($start_row,$row)->order('duration desc')->select();
				
				$count = $this->where($time)->count();
				
				
			} else {
				
				
				$group = 'duration,' . implode(',',array_keys($map));
				
				$map = array_merge($time,$map);
				
				$map['mark']=0;
				
				$lists = $this->field($group.',sum(new) as new,sum(new_device) as new_device,sum(new_pay) as new_pay,sum(new_money) as new_money,sum(active) as active,sum(active_pay) as active_pay,sum(active_money) as active_money')
					->where($map)->group($group)->order('duration desc')->limit($start_row,$row)->select();
				
				
				$countresult = $this->field($group)->where($map)->group($group)->select();
				
				$count = count($countresult);
				
				foreach($lists as $k => $v) {
					
					$lists[$k] = $this->data_assembly($v);
					
				}
				
				
			}
			
			$data['data'] = $lists;
			$data['count'] = $count+$offset;
			
			return $data;
			
		}
		
		
		
		
		/**
		 * 数据处理(计算付费率及arpu)
		 * @param		array		$data		要处理的数组
		 * @return	array		处理后的数组数据
		 * @author 鹿文学
		 */
		public function data_assembly($data=array()) {
			if(empty($data)) {return [];}
			$data['new_rate'] = round($data['new_pay']/$data['new']*100,2);
			$data['active_rate'] = round($data['active_pay']/$data['active']*100,2);
			$data['active_arpu'] = round($data['active_money']/$data['active'],2);
			$data['pay_arpu'] = round($data['active_money']/$data['active_pay'],2);
			
			return $data;
		}
		
		/**
		 * 获取最新的数据时间
		 * @author  鹿文学
		 */
		public function get_new_line_time() {
			
			$result = $this->field('duration')->where(['mark'=>1])->order('duration desc')->find();
			
			return $result['duration']?$result['duration']:0;
			
		}
		
		

    /**
     * 创建时间不写则取当前时间
     * @return int 时间戳
     * @author huajie <banhuajie@163.com>
     */
    protected function getCreateTime(){
        $create_time    =   I('post.create_time');
        return $create_time?strtotime($create_time):NOW_TIME;
    }
		
		protected function getUpdateTime(){
        $update_time    =   I('post.update_time');
        return $update_time?strtotime($update_time):NOW_TIME;
    }

		/**
     * 新增或更新一个游戏
     * @param array  $data 手动传入的数据
     * @return boolean fasle 失败 , int  成功 返回完整的数据
     * @author 王贺 
     */
    public function update($data = null){
        /* 获取数据对象 */
        $data = $this->token(false)->create($data);
        if(empty($data)){
            return false;
        } 
        /* 添加或新增基础内容 */
        if(empty($data['id'])){ //新增数据
            $id = $this->add($data); //添加基础内容

            if(!$id){
                $this->error = '新增基础内容出错!';
                return false;
            }
        } else { //更新数据
            $status = $this->save(); //更新基础内容
            if(false === $status){
                $this->error = '更新基础内容出错!';
                return false;
            }
        }
        
        
        return $data;
    }
		
		
		
    
	
	
	
	
}