<?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 LaunchRecordModel 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 	integer  	$start  开始时间
     * @param 	integer  	$end  	结束时间
     * @return 	array    	结果数据集
     * @author 	鹿文学 
     */
    public function lists($p=1,$map=array(),$start='',$end='') {
			
			$page = intval($p);
      $page = $page ? $page : 1; //默认显示第一页数据
			
			if(isset($_REQUEST['row'])) {$row = $_REQUEST['row'];}else{$row = 10;}
			
			$currentdate = mktime(0,0,0,date('m'),date('d'),date('Y'));
			
			$launch_data = D('LaunchData');
			
			if(empty($start)) {
				
				$time = ['duration'=>['lt',$currentdate]];
			
				$data = $launch_data->data($p,$row,$map,$time,1);
				
			} elseif(date('Ymd',$start) != date('Ymd',$end)) {
				
				$time = ['duration'=>['between',[$start,$currentdate-1]]];
				
				$data = $launch_data->data($p,$row,$map,$time,1);				

			} else {								
				
				$data = ['data'=>[],'count'=>1];
				
			}
			
			if(empty($map)) {$time['mark']=1;}else{$time['mark']=0;$time = array_merge($time,$map);}
			
				
			/* 计算今天的实时数据 */
			
			$today = $this->data_day($map,$currentdate,$end);
			
			$today = $launch_data->data_assembly($today);
			
			$total = $launch_data->data_total($time,$today);
			
			if($p==1) {
				
				array_unshift($data['data'],$today);
				
			}
			
			$current = $launch_data->accumulation([],$data['data']);
			
			$data['current'] = $launch_data->data_assembly($current);		
			
			$data['total'] = $total;
			
			$page = set_pagination($data['count'],$row);
			if($page) {$data['page']=$page;}
			
			return $data;
			
		}
		
		/**
		 * 计算一天的实时数据
		 * @param		array			$map			条件数组
		 * @param		integer		$start		开始时间(时间戳)
		 * @param		integer		$end			结束时间(时间戳)
		 * @return	array			结果集
		 * @author 鹿文学
		 */
		public function data_day($map,$start,$end) {
			
			$data = [];
			
			$extend = $map;
			
			$extend['create_time'] = array('between',[$start,$end]);
			
			$new = $this->where($extend)->select();
			
			$register = $this->field('user_id')->where($map)->select();
			
			$device = $this->where(array_merge($extend,['unique_code'=>array('neq','')]))->group('unique_code')->count();
			
			unset($map['platform_id']);
			
			$userlogin = D('UserLoginRecord');
			
			$spend = D('Spend');
			
			$userloginmap = $spendmap = $map;
			
			$newids = array_column($new,'user_id');
			
			$spendmap['pay_time']=array('between',[$start,$end]);
			
			$new_pay = 0;
			
			$new_money = 0;
			
			if(!empty($newids)) {
				
				$spendmap['user_id'] = array('in',$newids);
				
				$new_pay = $spend->player($spendmap);
				
				$new_money = $spend->amount($spendmap);
				
			}
			
			$regids = array_column($register,'user_id');
			
			$userloginmap['login_time'] = array('between',[$start,$end]);
			$iserloginmap['user_id'] = array('in',$regids);
			
			$active = $userlogin->active($userloginmap);
			
			$activeids = array_column($active,'user_id');
			
			$active_pay = 0;
			
			$active_money = 0;
			
			if(!empty($activeids)) {
				
				$spendmap['user_id'] = array('in',$activeids);
				
				$active_pay = $spend->player($spendmap);
				
				$active_money = $spend->amount($spendmap);
				
			}
			
			
			$data['new'] = count($new);
			$data['duration'] = strtotime(date('Y-m-d'));
			$data['new_device'] = $device;
			$data['new_pay'] = $new_pay;
			$data['new_money'] = $new_money;
			$data['active'] = count($active);
			$data['active_pay'] = $active_pay;
			$data['active_money'] = $active_money;
			$data['game_id'] = $extend['game_id']?$extend['game_id']:0;
			$data['platform_id'] = $extend['platform_id']?$extend['platform_id']:0;
			
			return $data;
			
		}
		
		
		/**
		 * 投放数据列表(截止到昨天)
		 * @param 	integer  	$p  		页码
     * @param 	array  		$map  	条件数组
     * @param 	array  		$time  	时间数组
     * @return 	array    	结果数据集
     * @author 	鹿文学 
     */
		public function data($p=1,$map=array(),$time=array()) {

			return D('LaunchData')->lists($p,$map,$time);
			
		}
		
		/**
		 * 获取最早的数据时间
		 * @author 鹿文学
		 */
		public function get_old_line_time() {
			
			$result = $this->field('create_time')->order('create_time asc')->find();
			
			return $result['create_time']?$result['create_time']:0;
			
		}
		
		/**
		 * 查找数据列表(从之前某天到昨天的数据的统计)
		 * @param		integer		$start 			开始时间
		 * @param		integer		$end				结束时间
		 * @author  鹿文学
		 */
		public function auto_data($start,$end) {
			
			if(empty($start) || empty($end)) {return '';}
			
			
			$datelist = get_date_list($start,$end);
			
			
			$userlogin = D('UserLoginRecord');
			
			$spend = D('Spend');
			
			$launch_data = D('LaunchData');
			
			$data = [];
			
			foreach($datelist as $k => $v) {
				$time = strtotime($v);
				$result = $this->get_data_day($time,$time+86399,$userlogin,$spend,$launch_data);
				if(!empty($result)) {
					$data = array_merge($data,$result);					
				}
			}
			
			return $data;
			
		}
		
		
		/**
		 * 查找每天数据
		 * @param		integer		$start 			开始时间
		 * @param		integer		$end				结束时间
		 * @author  鹿文学
		 */
		public function get_data_day($start,$end,$userlogin,$spend,$launch_data) {
			
			$newmap['create_time'] = array('between',[$start,$end]);
			
			/* 新玩家 */
			$new = $this->field('platform_id,promote_id,game_id,group_concat(id) as ids,group_concat(user_id) as newids,count(user_id) as new')
					->where($newmap)->group('platform_id,promote_id,game_id')->select();
			
			$newmap['unique_code'] = array('neq','');
			
			$spendmap2['pay_time'] = $spendmap['pay_time']=array('between',[$start,$end]);
			
			/* 活跃玩家 */
			$active = $userlogin->active_by_launch_record($start,$end,$this);
			
			$total = ['platform_id'=>0,'platform_name'=>'','promote_id'=>0,'promote_account'=>'','game_id'=>0,'game_name'=>'','new'=>0,'new_device'=>0,'new_pay'=>0,'new_money'=>0,'active'=>0,'active_pay'=>0,'active_money'=>0,'duration'=>$start+28800,'mark'=>1,'create_time'=>time()];
			
			foreach($active as $k => $v) {
				$temp = array(
					'platform_id'=>$v['platform_id'],
					'platform_name'=>$v['platform_name'],
					'promote_id'=>$v['promote_id'],
					'promote_account'=>$v['promote_account'],
					'game_id'=>$v['game_id'],
					'game_name'=>$v['game_name'],
					'active'=>$v['active'],
					'mark'=>0,'new'=>0,'new_device'=>0,'new_pay'=>0,'new_money'=>0,'create_time'=>time(),
				);
				$spendmap2['user_id'] = array('in',$v['activeids']);
				$temp['active_pay'] = $spend->player($spendmap2);
				$temp['active_money'] = $spend->amount($spendmap2);
				$temp['duration'] = $start+28800;
				
				foreach($new as $key => $value) {
					if($value['platform_id']==$v['platform_id'] && $value['promote_id']==$v['promote_id'] && $value['game_id']==$v['game_id']) {
						$temp['new'] = $value['new'];
						$spendmap['user_id'] = array('in',$value['newids']);
						$newmap['id'] = array('in',$value['ids']);
						$device = $this->field('id')->where($newmap)->group('unique_code')->select();
						$temp['new_device'] = count($device);
						$temp['new_pay'] = $spend->player($spendmap);
						$temp['new_money'] = $spend->amount($spendmap);
					}
				}
				
				$temp = $launch_data->data_assembly($temp);
				
				$total['new'] += $temp['new'];
				$total['new_device'] += $temp['new_device'];
				$total['new_pay'] += $temp['new_pay'];
				$total['new_money'] += $temp['new_money'];
				$total['active'] += $temp['active'];
				$total['active_pay'] += $temp['active_pay'];
				$total['active_money'] += $temp['active_money'];
				
				ksort($temp);
				
				$data[$k]=$temp;
				
			}
			
			$total = $launch_data->data_assembly($total);
			ksort($total);
			array_unshift($data,$total);
			
			return $data;
			
		}
		
		/**
		 * 根据时间分组获取新玩家
		 * @param  array    $map      条件数组
		 * @param  string   $field	  字段别名
		 * @param  string   $group    分组字段名
		 * @author 鹿文学
		 */
		public function news($map=array(),$field='news',$group='time',$flag=1,$order='time') {
			
			switch($flag) {
				case 2:{$dateform = '%Y-%m';};break;
				case 3:{$dateform = '%Y-%u';};break;
				case 4:{$dateform = '%Y';};break;
				case 5:{$dateform = '%Y-%m-%d %H';};break;
				default:$dateform = '%Y-%m-%d';
			}
			
			$user = $this->field('FROM_UNIXTIME(create_time, "'.$dateform.'") as '.$group.',group_concat(user_id) as id ,COUNT(user_id) AS '.$field)
					->where($map)
					->group($group)
					->order($order)
					->select();
		
			return $user;

		}
		
		/**
		 * 根据时间分组获取新设备
		 * @param  array    $map      条件数组
		 * @param  string   $field	  字段别名
		 * @param  string   $group    分组字段名
		 * @author 鹿文学
		 */
		public function device($map=array(),$field='news',$group='time',$flag=1,$order='time') {
			
			switch($flag) {
				case 2:{$dateform = '%Y-%m';};break;
				case 3:{$dateform = '%Y-%u';};break;
				case 4:{$dateform = '%Y';};break;
				case 5:{$dateform = '%Y-%m-%d %H';};break;
				default:$dateform = '%Y-%m-%d';
			}
			
			$map['unique_code'] = array('neq','');
			
			$user = $this->field('FROM_UNIXTIME(create_time, "'.$dateform.'") as '.$group.',group_concat(unique_code) as id ,COUNT(unique_code) AS '.$field)
					->where($map)
					->group($group)
					->order($order)
					->select();
		
			return $user;
			
		}

    /**
     * 创建时间不写则取当前时间
     * @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;
    }
		
		
		
    
	
	
	
	
}