<?php
namespace Site\Model;

use Think\Model;

/**
 * 分类模型
 * lwx
 */
class SiteGiftModel 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 string	$field	礼包表字段
	 * @param integer	$row		限制条数
	 * @param string	$order	排序条件
	 * @return array  				结果数据列表
	 */
	public function lists($p=1,$field=true,$row=10,$order='tab_site_gift.create_time asc,tab_site_gift.id desc') {
		
		$page = intval($p);
		
		$page = $page ? $page : 1; //默认显示第一页数据
		$map['tab_site_gift.end_time'] = array("gt",time()-86400);
		$map['tab_site_gift.promote_id'] = PID;
        $map['tab_site_gift.novice'] = array('neq','');
        $map['tab_site_gift.status'] = 1;
		$_GET['rs'] && $map['tab_site_gift.recommend_status'] = $_GET['rs'];
		
		$_GET['gt'] && $map['tab_site_game.game_type_id'] = $_GET['gt'];
		
		if($field === true) {$field = 'tab_site_gift.*';}
		
		$ip = get_client_ip();
		
		if (DEVICES) {
			
			$map['tab_site_gift.giftbag_version']=DEVICES;
			
			$csql = $this->field('site_game_id')
						
						->join('tab_site_game on (tab_site_game.id=tab_site_gift.site_game_id)','inner')
						
						->where($map)->select(false);
						
			$csql2 = $this->table('('.$csql.') as a')->group('site_game_id')->select(false);
			
			$count = $this->table('('.$csql2.') as b')->count();			
			
			$total = intval(($count-1)/$row)+1;
			
			if ($page>$total) {return array('data'=>'','count'=>$count,'row'=>$row,'total'=>$total);}

			$sql = $this->field('tab_site_gift.id,tab_site_gift.gift_name,tab_site_gift.site_game_id,concat(IFNULL(tab_site_gift.gift_content,"##"),"@@")	 AS gift_content,replace(IFNULL(trim(tab_site_gift.novice),"##"),",","@@")	AS novice,tab_site_game.game_name,tab_site_game.game_icon,tab_site_game.game_source,IFNULL(tab_site_gift_record.id,0) as recordid')
			
						->join('tab_site_game on (tab_site_game.id=tab_site_gift.site_game_id)','inner')
						
						->join('tab_site_gift_record on (tab_site_gift_record.site_gift_id=tab_site_gift.id and tab_site_gift_record.ip="'.$ip.'")','left')
				
						->where($map)->order($order)->select(false);
			
			
			$list = $this->table('('.$sql.') as a')
			
						->field('a.site_game_id,a.game_name,a.game_icon,a.game_source,group_concat(a.id) as id,group_concat(a.gift_name) as gift_name,group_concat(a.novice) as novice,group_concat(a.gift_content) as gift_content,GROUP_CONCAT(a.recordid) as recordid')
						
						->group('a.site_game_id')->page($page,$row)->select();

			return array('data'=>$this->data_reorganization($list),'count'=>$count,'row'=>$row,'total'=>$total);
		
		} else {
			
			$count = $this->join('tab_site_game on (tab_site_game.id=tab_site_gift.site_game_id)','inner')->where($map)->count();

			$total = intval(($count-1)/$row)+1;
			
			if ($page>$total) {$page=$total;}
			
			$data = $this->field($field.',trim(tab_site_gift.novice) as novice,tab_site_game.game_name,tab_site_game.game_icon,tab_site_game.game_source,tab_site_gift_record.id as recordid')
			
						->join('tab_site_game on (tab_site_game.id=tab_site_gift.site_game_id)','inner')
						
						->join('tab_site_gift_record on (tab_site_gift_record.site_gift_id=tab_site_gift.id and tab_site_gift_record.ip="'.$ip.'")','left')
				
						->where($map)->order($order)->page($page,$row)->select();
			return array('data'=>$data,'count'=>$count,'row'=>$row);
			
		}
			
		
	}
	
	
	/**
	 * 数据重组
	 * @param array		$list		数据列表
	 * @return array  				结果数据列表
	 */
	private function data_reorganization($list) {
		
		if ($list){
			foreach($list as $k => $v) {
				$data[$k]['site_game_id'] = $v['site_game_id'];
				$data[$k]['game_name'] = $v['game_name'];
				$data[$k]['game_icon_url'] = get_cover($v['game_icon'],'path');
				$data[$k]['game_url'] = U('Game/detail',array('name'=>$v['game_name'],'account'=>I('account'),'source'=>$v['game_source']));
				$id = explode(',',$v['id']);
				$name = explode(',',$v['gift_name']);
				$recordid = explode(',',$v['recordid']);
				$novice = explode(',',$v['novice']);
				$content = explode('@@,',$v['gift_content']);
				$data[$k]['gift_count'] = count($id);
				$gift = '';
				foreach($id as $j => $i) {
					$gift[$j]['id'] = $i;
					$gift[$j]['gift_url']=U('Gift/detail',array('id'=>$i,'account'=>I('account')));
				}
				foreach($name as $j => $i) {
					$gift[$j]['gift_name'] = $i;
				}
				foreach($recordid as $j => $i) {
					$gift[$j]['recordid'] = $i;
				}
				foreach($novice as $j => $i) {
					$ne = str_replace('##','',$i);
					$gift[$j]['novice'] = $ne?count(explode('@@',$ne)):0;
				}
				foreach($content as $j => $i) {
					$giftcontent = str_replace('@@','',$i);
					$gift[$j]['gift_content'] = mb_strwidth($giftcontent,'utf-8')>50?mb_strimwidth($giftcontent,0,50,'...','utf-8'):$giftcontent;
				}
				
				$data[$k]['gift'] = $gift;
			}
			
			return $data;
		}else 
			return '';
	}
	
	
	
	/**
	 * 所有游戏礼包列表
	 * @param array		$map		搜索条件
	 * @param string	$field	游戏开服表字段
	 * @param string	$order	排序条件
	 * @return array  				结果数据列表
	 */
	public function all($p,$map=array(),$field=true,$row=10,$order='tab_site_gift.create_time asc,tab_site_game.id desc') {
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
		$map['tab_site_gift.promote_id'] = PID;
        $map['tab_site_gift.novice'] = array('neq','');
		$map['tab_site_gift.status'] = 1;
        $map['tab_site_gift.end_time'] = array("gt",time()-86400);
		$ip = get_client_ip();
		
		if($field === true) {$field = 'tab_site_gift.*';}
		
		if(DEVICES) {$map['tab_site_gift.giftbag_version']=DEVICES;}
		
		$count = $this->field($field.',trim(tab_site_gift.novice) as novice,tab_site_game.game_name,tab_site_game.game_icon,tab_site_game.game_type,tab_site_game.game_type_id,tab_site_game.game_source,tab_site_gift_record.id as recordid')
		
			->join('tab_site_game on (tab_site_game.id=tab_site_gift.site_game_id)','inner')
			
			->join('tab_site_gift_record on (tab_site_gift_record.site_gift_id=tab_site_gift.id and tab_site_gift_record.ip="'.$ip.'")','left')
			
			->where($map)->order($order)->count();
        $total = intval(($count-1)/$row)+1;
        if(DEVICES){$row = $count;};
        if ($page>$total) {if (DEVICES) {return array('data'=>'','count'=>$count,'row'=>$row,'total'=>$total);}else{$page=$total;}}

        $data = $this->field($field.',trim(tab_site_gift.novice) as novice,tab_site_game.game_name,tab_site_game.game_icon,tab_site_game.game_type,tab_site_game.game_type_id,tab_site_game.game_source,tab_site_gift_record.id as recordid')

            ->join('tab_site_game on (tab_site_game.id=tab_site_gift.site_game_id)','inner')

            ->join('tab_site_gift_record on (tab_site_gift_record.site_gift_id=tab_site_gift.id and tab_site_gift_record.ip="'.$ip.'")','left')

            ->where($map)->order($order)->page($page,$row)->select();
        return array('data'=>$data,'count'=>$count,'row'=>$row);
	}
	
	/**
	 * 取几条礼包数据
	 * @param array		$map		搜索条件
	 * @param integer	$limit	限制条数
	 * @param string	$field	游戏表字段
	 * @return array  				结果数据列表
	 */
	public function limits($map=array(),$limit=10,$field=true) {
		
		if (PID<=0) {return null;}
		
		$map['tab_site_gift.promote_id'] = PID;
		$map['tab_site_gift.novice'] = array('neq','');
		$map['tab_site_gift.status']=1;
        $map['tab_site_gift.end_time'] = array("gt",time()-86400);
		$ip = get_client_ip();
		
		if($field === true) {$field = 'tab_site_gift.*';}
        if(DEVICES) {$map['tab_site_gift.giftbag_version']=DEVICES;}
        $data = $this->field($field.',trim(tab_site_gift.novice) as novice,tab_site_game.game_name,tab_site_game.game_icon,tab_site_game.game_source,tab_site_gift_record.id as recordid')

            ->join('tab_site_game on (tab_site_game.id=tab_site_gift.site_game_id)','inner')

            ->join('tab_site_gift_record on (tab_site_gift_record.site_gift_id=tab_site_gift.id and tab_site_gift_record.ip="'.$ip.'")','left')

            ->where($map)->order('tab_site_gift.create_time asc')->limit($limit)->select();
        return $data;

	}
	
	/**
	 * 获取相关礼包数据
	 * @param array		$map		搜索条件
	 * @return array  				结果数据列表
	 */
	public function relevant($map=array()) {
		
		if (PID<=0) {return null;}
		
		$map['tab_site_gift.promote_id']= PID;
		
		$map['tab_site_gift.status'] = 1;
        $map['tab_site_gift.end_time'] = array("gt",time()-86400);
		$ip = get_client_ip();
		
		if(DEVICES) {$map['tab_site_gift.giftbag_version']=DEVICES;}
		
		return $this->field('tab_site_gift.id,tab_site_gift.site_game_id,tab_site_gift.gift_name,tab_site_gift.gift_content,trim(tab_site_gift.novice) as novice,tab_site_gift.giftbag_version,tab_site_game.game_name,tab_site_game.game_icon,tab_site_game.game_type,tab_site_game.game_type_id,tab_site_game.game_source,tab_site_gift_record.id as recordid')
		
			->join('tab_site_game on (tab_site_game.id=tab_site_gift.site_game_id)','inner')
			
			->join('tab_site_gift_record on (tab_site_gift_record.site_gift_id=tab_site_gift.id and tab_site_gift_record.ip="'.$ip.'")','left')
			
			->where($map)->order('tab_site_gift.create_time asc')->select();
		
	}
	
	/**
	 * 礼包详情
	 * @param integer	$id				礼包编号
	 * @return array  					结果数据
	 */
	public function detail($id=0) {
		if (!is_numeric($id) || $id <=0) {return null;}
		
		$map['tab_site_gift.id'] = $id;

		$map['tab_site_gift.promote_id'] = PID;
		
		$map['tab_site_gift.status']=1;
		
		$ip = get_client_ip();
		
		if(DEVICES) {$map['tab_site_gift.giftbag_version']=DEVICES;}
		
		$data = $this->field('tab_site_gift.*,trim(tab_site_gift.novice) as novice,tab_site_game.game_id,tab_site_game.game_icon,tab_site_game.game_source,tab_site_game.game_name,tab_site_game.sdk_version,tab_site_game.game_dow_url,tab_site_gift_record.id as recordid')
		
			->join('tab_site_game on (tab_site_game.id = tab_site_gift.site_game_id)','inner')
			
			->join('tab_site_gift_record on (tab_site_gift_record.site_gift_id=tab_site_gift.id and tab_site_gift_record.ip="'.$ip.'")','left')
			
			->where($map)->find();
		
		$other = D('SiteGame')->down($data['game_name'],$data['game_source'],3-$data['sdk_version'],PID);
		
		if ($data['game_source']==1) {
			$data['download'.$data['sdk_version']] = 'http://'.$_SERVER['HTTP_HOST'].U('Down/down_file',array('game_id'=>$data['game_id'],'promote_id'=>PID,'type'=>$data['sdk_version']));
			$data['download'.$other['sdk_version']] = 'http://'.$_SERVER['HTTP_HOST'].U('Down/down_file',array('game_id'=>$other['game_id'],'promote_id'=>PID,'type'=>$other['sdk_version']));
		}elseif ($data['game_source']==2) {
			$data['download'.$data['sdk_version']] = $data['game_dow_url'];
			$data['download'.$other['sdk_version']] = $other['game_dow_url'];
		}
		
		$data['novice_count'] = $data['novice']?count(explode(',',$data['novice'])):0;
		
		$data['surplus'] = $data['novice_count']/$data['novice_num']*100;
		
		return $data;
	}
	
	
	/**
	 * 领取礼包激活码
	 * @param integer	$id				礼包编号
	 * @return boolean  				true,成功
	 */
	public function getgift($id=0) {
		
		if (!is_numeric($id) || $id <=0) {$this->error='参数错误';return -1;}
		
		$map['id']=$id;
		
		if(DEVICES) {$map['giftbag_version']=DEVICES;}
		
		$data = $this->where($map)->find();
		// 没了
		if (empty(trim($data['novice']))) {$this->where(['id'=>$id])->save(['novice'=>'']);$this->error='领取失败,激活码已领完';return 4;}
		
		$record = M('site_gift_record','tab_');
		
		$ip = get_client_ip();

		if ($res = $record->where(['ip'=>$ip,'site_gift_id'=>$id])->find()) {
			// 已领取
			$this->error = $res['novice'];
			
			return 2;
		} else {
			
			$novice = explode(',',trim($data['novice']));
			
			$temp = array_shift($novice);
			
			$novice2 = count($novice)<1?'':implode(',',$novice);

			if($this->where(['id'=>$id])->save(['novice'=>$novice2])) {
				// 领取成功
				$giftrecord = ['ip'=>$ip,'novice'=>$temp,'create_time'=>time(),'site_gift_id'=>$id];
				if($record->add($giftrecord)) {
					$this->error = $temp;
					return 1;
				} else {
					$record->add($giftrecord);
					$this->error = $temp;
					return 3;
				}
			} else {
				// 领取失败
				$this->error = '领取失败';
				return 0;
			}
		}
		
	}

}