<?php

/**
 *--------------------------------------
 * 控制器基类
 *--------------------------------------
 * @project		: pfa
 * @author		: cblee
 * @created		: 2012-9-23
 * @copyright	: (c)2012 AsThis
 *--------------------------------------
 */

class Ctrlr extends Pfa
{
	protected $te = null;

	public function __construct()
	{
		/* 获得模板引擎实例 */
		$this->te = get_instance('Te', '', 'get_te');
	}

	/* 模板变量赋值 */
	public function assign($var, $value)
	{
		$this->te->assign($var, $value);
	}

	/* 显示内容 */
	public function display($file = '', $charset = '', $contentType = '')
	{
		/* 网页字符编码 */
		if(empty($charset))
		{
			$charset = C('APP.CHARSET');
		}
		if(empty($contentType))
		{
			$contentType = C('TE.TPL_CONTENT_TYPE');
		}
		header('Content-Type:'.$contentType.'; charset='.$charset);
		header('Cache-control: private'); /*支持页面回跳 */

		$this->te->display($file);
	}

	/* 创建HTML htmlfile 生成的静态文件名称 htmlpath 生成的静态文件路径 $templateFile 指定要调用的模板文件 */
	protected function build_html($htmlfile = '', $htmlpath = '', $templateFile = '')
	{
		return $this->te->build_html($htmlfile, $htmlpath, $templateFile);
	}

	/* 操作错误跳转 */
	public function error($message = '', $jumpUrl = '')
	{
		$this->disp_jump($message, $jumpUrl, 0);
	}

	/* 操作成功跳转 */
	public function success($message = '', $jumpUrl = '')
	{
		$this->disp_jump($message, $jumpUrl, 1);
	}

	/* 默认跳转操作 $status 1:success, 0:error */
	private function disp_jump($message, $jumpUrl = '', $status = 1)
	{
		if($status)
		{
			$this->assign('status', 'success');
		}
		else
		{
			$this->assign('status', 'error');
		}
		$this->assign('message', $message);
		$this->assign('jumpUrl', $jumpUrl);
		$this->display(C('TPL.DISP_JUMP'));
		exit();
	}

	/* Ajax方式返回数据到客户端 $data:数据, $info:提示信息, $status:ajax类型*/
	public function ajax_return($data, $info = '', $type = 'JSON')
	{
		if(!$this->is_ajax())
		{
			exit();
		}
		$result = array();
		$result['info'] = $info;
		$result['data'] = $data;
		if('JSON' == strtoupper($type))
		{
			/* 返回JSON数据格式到客户端 */
			header("Content-Type:text/html; charset=utf-8");
			exit(json_encode($result));
		}
		elseif('XML' == strtoupper($type))
		{
			/* 返回xml格式数据 */
			header("Content-Type:text/xml; charset=utf-8");
			exit(xml_encode($result));
		}
		elseif('EVAL' == strtoupper($type))
		{
			/* 返回可执行的js脚本 */
			header("Content-Type:text/html; charset=utf-8");
			exit($data);
		}
		else
		{
			/*TODO: */
		}
	}

	/* 判断是否AJAX请求 */
	protected function is_ajax()
	{
		if(isset($_SERVER['HTTP_X_REQUESTED_WITH']))
		{
			if('xmlhttprequest' == strtolower($_SERVER['HTTP_X_REQUESTED_WITH']))
			{
				return true;
			}
		}
		return false;
	}

	public function __call($method, $args)
	{
	}

}

?>