<?php
class BaseController{
	public $tplParams = array();
	public $layout = NULL;
	public $layoutTpl = true;
	function __construct(){
		// $randKey = v('rand');
		// if( Url::getClass() != 'main' && Url::getClass() != 'invite' ){
		// 	$this->checkAccess( $randKey );
		// }
		// $this->makeRandKey();

		//checkLogin();
	}
	protected function makeRandKey(){
		if( $_SESSION['__lastClass'] != Url::getClass() ){
			$_SESSION['__rand'] = $this->getRandChar('12');
			$_SESSION['__lastClass'] = Url::getClass();
		}
		Url::$custom = array('rand' => $_SESSION['__rand']);
	}
	protected function getRandChar($length){
	   $str = null;
	   $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
	   $max = strlen($strPol)-1;

	   for($i=0;$i<$length;$i++){
	    $str.=$strPol[rand(0,$max)];
	   }
	   return $str;
	}
	protected function checkAccess( $randKey ){
		if( !$_SESSION['__rand'] || $_SESSION['__rand'] != $randKey  ){
			header("Location: ".Url::make('class=main'));
		}
		$referer = $_SERVER['HTTP_REFERER'];
		$refererInfo = parse_url( $referer );
		if( $refererInfo['host'] != $_SERVER['HTTP_HOST'] ){
			header("Location: ".Url::make('class=main'));
		}
	}
	protected function _add( $key , $value = NULL ){
		if( $value == NULL && is_array($key) ){
			$this->tplParams += $key;
		}else{
			$this->tplParams[$key] = $value;		
		}
	}
	protected function showMessage( $message , $type = 'notice' , $show = true ){
		$message = '<message type="'.$type.'">'.$message.'</message>';
		if( $show ){
			echo $message;
		}else{
			return $message;	
		}
	}
	protected function render( $tplName = NULL , $data = array() ){
		if( c('custom') ){
			$weixinJsApiInfo = array();
			$weixinJsApiInfo['noncestr'] = $this->getRandChar(12);
			$weixinJsApiInfo['timestamp'] = time();
			$weixinJsApiInfo['url'] = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
			$weixinJsApiInfo['jsapi_ticket'] = getJsTicket();
			ksort( $weixinJsApiInfo, SORT_STRING );
			$str = NULL;
			foreach ($weixinJsApiInfo as $key => $value) {
				$str .= "$key=$value&";
			}
			$str = substr($str, 0 , -1);
			$_signature = sha1 (  $str );
			$weixinJsApiInfo['signature'] = $_signature;
			$this->_add('weixinJsApiInfo' , $weixinJsApiInfo );
		}
		if( $data && is_array( $data )  ){
			$data = array_merge( $data ,  $this->tplParams );
		}else{
			$data = $this->tplParams;
		}
		if( !$tplName ){
			$tpl = $tplName?$tplName:get_class($this);
			if( Url::getMethod() != c('default_method') ){
				$tpl .= '_'.Url::getMethod();
			}
		}else{
			$tpl = $tplName;
		}
		
		render( $data , $tpl , $this->layout , $this->layoutTpl );
	}
	protected function getAjax( $method , $extra = array() ){
		if( !method_exists(  $this , $method ) ) die('Ajax method is not exists' );
		//save  info
		$url = Url::getUrl();
		
		$extra['method'] = $method;
		$GLOBALS['__isAjax'] = true;
		
		Url::setUrl( Url::make($extra) );

		ob_start();
		$this->$method();
		$html = ob_get_clean();
		//replace back
		unset($GLOBALS['__isAjax']);
		Url::setUrl( $url );
		
		return $html;
	}
	protected function success( $data , $notice = null ){
		$res = [];
		$res['code'] = 0;
		$res['data'] = $data;
		if( $notice ){
			$res['notice'] = [
				'msg' => $notice
			];
		}
			echo json_encode( $res );
	}
	protected function fail( $msg , $error = 1 ){
			$res = [];
			$res['code'] = $error;
			$res['msg'] = $msg;
			echo json_encode( $res );
	}
	protected function checkLogin(){
			// return;
			if( $_SESSION['token']  && $_SESSION['token_expire'] > time() ){
					return;
			}
			if( $this->refreshToken() ){
					return;
			}
		
			$this->fail('请登录后在访问' , -1 );
			exit;
	}
	protected function refreshToken( ){
		$refreshToken = $_SESSION['refresh_token'];
		$res = Api( 'api/oauth/refreshtoken/'.$refreshToken );
		$res = json_decode( $res , true );
		if( $res['data'] ){
				$data = json_decode($res['data'],1);
				$token = $data['token'];
				// $update = [];
				// $update['token'] = $token;
				// $update['token_expire'] = time() + $data['token_effective_time'];
				// $update['refresh_token'] = $data['refreshToken'];
				// db()->update( 'users' , $update , ['id' => $_SESSION['id'] ]  );
				$_SESSION['token'] = $token;
				$_SESSION['refresh_token'] = $data['refreshToken'];
				$_SESSION['token_expire'] = time() + $data['token_effective_time'];
				return true;
		}
		return false;
	}
	protected function getList( $list , $dateFormat = 'Y-m-d H:i' , $key = 'uniid' ){
		if( $list ){
			foreach( $list as $v ){
				$ids[] = $v['ID'];
			}
			$data = db()->getData( 'select * from `contents`  where `'.$key.'` IN(\''.join("','" , $ids ).'\') ' , $key );
			foreach( $list as &$v ){
				$uniid = $v['ID'];
				$time = $v['Time'];
				$v = [];
				$v['downloadcount'] = $data[$uniid]['down_count'];
				$v['viewcount'] = $data[$uniid]['view_count'];
				$v['image'] = $data[$uniid]['preview_info'];
				$v['data_id'] = $data[$uniid]['data_id'];
				$v['title'] = $data[$uniid]['title'];
				$v['content'] = $data[$uniid]['content'];
				$v['time'] = date( $dateFormat  , strtotime( $time ) );
			}
			return $list;
		}
	}
	protected function history( $apiName , $timeFomat ){
		$page = $this->post['page'];
		$page  = intval( $page );
		$order = $this->post['order'] == 'asc'?'asc':'desc';
		$recent = [];
		$older = [];
		$hasMore = true;
		if( $page < 1 ){
				$page = 1;
		}
		if( $page == 1 ){
				$recentQueue = [
						'begin_time' => date("Y-m-d H:i:s",  strtotime('-7 days') ) ,
						'end_time' => date("Y-m-d H:i:s" ),
						'page_index' => 1,
						'page_size' => 100000,
						'Order' => $order
				];
				$res = uApi('api/user/marketing/'.$apiName ,$recentQueue );
			
				if( $res ){
						$recent = $this->getList( $res , $timeFomat );
				}
		}
		$olderQueue = [
				'end_time' => date("Y-m-d H:i:s",  strtotime('-7 days') ),
				'page_index' => $page,
				'page_size' => 20,
				'Order' => $order
		];
		$res = uApi('api/user/marketing/'.$$apiName  ,$recentQueue );
		if( count( $res )  != 20 ){
				$hasMore = false;
		}
		if( $res ){
				$older = $this->getList( $res ,  $timeFomat );
		}
		$return = [];
		$return['recent'] =$recent;
		$return['older'] = $older;
		$return['hasMore'] = $hasMore;
		$this->success( $return );
}
	protected function getWhere(){
		$where = [];
		if( $this->post['typeInfo'] ){
			$typeNames = [];
			$tids = [];
			foreach( $this->post['typeInfo'] as $v ){
					if( $v['checked']  && is_array( $v['tid']) ){
						$tids = array_merge( $tids , $v['tid'] );
					}
			}
			if( $tids && is_numeric( join('', $tids ) )  ){
					$where[] = 'type in(\''.join( "','", $tids ).'\')';
			}
		}
		$tab = $this->post['tab'];
		if( $this->post['cate'] ){
			$cate = $this->post['cate'];
			$fileIds = $this->getFileIds( $cate ); 
			if( $fileIds ){
				if( is_numeric( join( '' , $fileIds) ) ){
					$where[] = "data_id IN(".join(',',$fileIds ).")";	
				}
			}
			// if( 
			// 	$cate['product_type_id'] && 
			// 	is_numeric(join('',$cate['product_type_id'])) 
			// ){
			// 	$where[] = "data_id IN(select data_id from rel_prodcut where product_type_id in ( '".join("','",$cate['product_type_id']  )."' ) )";
			// }else if( 
			// 	$this->post['article_type_id'] && 
			// 	is_numeric(join('',$cate['article_type_id']))
			// ){
			// 	$where[] = "data_id IN(select data_id from rel_solution where article_type_id in ( '".join("','",$cate['article_type_id']  )."' ) )";
			// } 
		}else if( $tab ){
			if( $tab == 'Product' ){
				$where[] = "data_id IN(select data_id from rel_prodcut where product_type_id != '0' )";
			}else if($tab == 'Industry'){
				$where[] = "data_id IN(select data_id from rel_solution where article_type_id != '0' )";
			}
		}
		
		return $where;
	}
	private function getFileIds( $obj ){
		$fileIds = [];
		if( $obj['children'] ){
			foreach(  $obj['children']  as $v ){
				$fileIds = array_merge( $fileIds ,$this->getFileIds( $v ) );
			}
			
		}
		if( $obj['fileIds'] ){
			$fileIds = array_merge( $fileIds ,  $obj['fileIds'] );
		}
		return $fileIds;
	}
}
