<?php
namespace Base;

class BaseCacheModel extends AppBaseModel {
	
    protected $_cache_temp = '';
	protected $cacheOpt = array();	
	protected $_returnData = array();	
	

	public function _initialize(){
		$this->cacheOpt['temp']      =   PROJECT_PATH . 'runtime/' . $this->_cache_temp;
		$this->cacheOpt['expire']    =   86400*14;
	}	
	
	/**
	 * 获取缓存实例
	 * @param unknown $arr
	 * @return object
	 */
	protected function getCacheInstance($arr=array()){
		$opt = array_merge($this->cacheOpt,$arr);
		return S($opt);
	}
	
	/**
	 * 缓存find查找
	 * @param unknown $options
	 * @return array
	 */
	public function cacheFind($options=array()){
		$c = $this->getCacheInstance();
		$options    =  $this->_parseOptions($options);
		
		$cache  =   $options['cache'];
		$options['method'] = 'find';
        $key    =   is_string($cache['key'])?$cache['key']:md5(serialize($options));		
		if(!$c->get($key)){
			unset($options['alias']);
			$c->set($key,$this->find($options));
		}
		return $c->get($key);
	}
	
	/**
	 * 缓存select查找
	 * @param unknown $options
	 * @return array
	 */
	public function cacheSelect($options=array()){
		$c = $this->getCacheInstance();
		$options    =  $this->_parseOptions($options);
		$cache  =   $options['cache'];
		$options['method'] = 'select';
		$key    =   is_string($cache['key'])?$cache['key']:md5(serialize($options));
		if(!$c->get($key)){
			unset($options['alias']);
			$c->set($key,$this->select($options));
		}
		return $c->get($key);
	}
	/**
	 * 缓存Count计数
	 * @param unknown $options
	 * @return array
	 */
	public function cacheCount($field=null){
		$c = $this->getCacheInstance();
		$options['field']       =   $field;
		$options                =   $this->_parseOptions($options);
		$cache  =   $options['cache'];
		$key    =   is_string($cache['key'])?$cache['key']:md5(serialize($options));
		if(!$c->get($key)){
			unset($options['alias']);
			$this->options = $options;
			$c->set($key,$this->count($field));
		}
		return $c->get($key);
	}
	/**
	 * 清除缓存
	 */
	public function cacheClear(){
		$c = $this->getCacheInstance();
		return $c->clear();
	}

	public function getTargetInfo($map){
    	$info = $this->where($map)->cacheFind();
    	return $info;
	}

	/**
	 * 获取数据返回（带分页）缓存24小时
	 * @param array $map
	 * @param number $pageopt
	 * @return mixed
	 */
	public function getList($map=array(),$limit=20,$page,$field='') {
        // $page = intval($this->postJson['page']);    
        // $page = $page <= 0 ? 1 : $page;
		$map = array_merge($map,array('status'=>0));
		if(is_null($limit)) {
			$data = $this->where($map)->order($this->getPk().' desc')->cacheSelect();
		}else{
			$data['count'] = $this->where($map)->cacheCount();
			$data['data']  = $this->where($map)->order($this->getPk().' desc')->limit($limit)->field($field)->page($page)->cacheSelect();
			$data['pager'] = $this->_pager($page, ceil($data['count']/$limit));
		}
		return $data;
	}


	

}