<?php
if(!defined("PLAYBOX")){
	exit;
}

class Page{
	private $pagenoname	='pageno';	//翻页参数的名字，防止给其他参数相冲突
	private $middlesize	=10;		//显示中间条数 //偶数
	private $total		=0;			//总条数
	private $pagesize	=10;		//每页条数
	private $pages		=0;			//总页数
	private $pageno		=1;			//当前页数
	
	public $showno		=true;		//无数据是否显示提示信息
	
	public function __construct($total,$pagesize=10,$middlesize=10,$pagenoname='pageno'){
		$this->total		=$total;
		$this->pagesize		=$pagesize;
		$this->pages		=ceil($this->total/$this->pagesize);
		$this->middlesize	=$middlesize;
		$this->pagenoname	=$pagenoname;
		
		$pageno=isset($_GET[$this->pagenoname]) ? $_GET[$this->pagenoname] : 1;
		$this->pageno		=preg_match("/^[1-9][0-9]*$/",$pageno)===1 ? $pageno : 1;
	}

	public function showtool(){
		if($this->total==0){
			if($this->showno){
				echo '无数据';
			}
			return;
		}
		
		$from	=max(1,min($this->pages - ($this->middlesize+3)+1,$this->pageno - ($this->middlesize/2)));
		$to		=min(max($from+10,$this->pageno + ($this->middlesize/2),1+($this->middlesize+3)-1),$this->pages);
		$qian	=$from-1;
		$hou	=$this->pages-$to;
		
		echo '<span>'.$this->pagesize.'条/页，共'.$this->total.'条</span>';
		
		if($this->pageno>1){
			echo '<a href="'.$this->geturl($this->pageno-1).'">上一页</a>';
		}
		
		if($qian==1){
			echo '<a href="'.$this->geturl(1).'">1</a>';
		}elseif($qian==2){
			echo '<a href="'.$this->geturl(1).'">1</a>';
			echo '<a href="'.$this->geturl(2).'">2</a>';
		}elseif($qian>=3){
			echo '<a href="'.$this->geturl(1).'">1</a>';
			echo '<span>...</span>';
		}
		
		for($i=$from;$i<=$to;$i++){
			if($i==$this->pageno){
				echo "<strong>$i</strong>";
			}else{
				echo '<a href="'.$this->geturl($i).'">'.$i.'</a>';
			}
		}
		
		if($hou>=3){
			echo '<span>...</span>';
			echo '<a href="'.$this->geturl($this->pages).'">'.$this->pages.'</a>';
		}elseif($hou==2){
			echo '<a href="'.$this->geturl($this->pages-1).'">'.($this->pages-1).'</a>';
			echo '<a href="'.$this->geturl($this->pages).'">'.$this->pages.'</a>';
		}elseif($hou==1){
			echo '<a href="'.$this->geturl($this->pages).'">'.$this->pages.'</a>';
		}
		
		if($this->pageno < $this->pages){
			echo '<a href="'.$this->geturl($this->pageno+1).'">下一页</a>';
		}
		
	}
	
	private function geturl($i){
		parse_str($_SERVER['QUERY_STRING'],$output);
		return htmlentities($_SERVER['SCRIPT_NAME']."?".http_build_query(array_merge($output,array($this->pagenoname=>$i))));
	}
	
	public function __get($p){
		return $this->$p;
	}
}
?>