<?php

namespace KIF\Core;

use Exception;

abstract class FController {
	
	/**
	 * @var 请求
	 */
	protected $_setTemplate = false;
	
	/**
	 * @var 模板类
	 */
	protected $_view;
	
	
	/**
	 *
	 * 所有输出到模版的变量,都存放到这里面,以便统一管理
	 * @var array
	 */
	protected $output = array();
	
	protected $tpl;
	
	/**
	 * 导航菜单
	 *
	 * @var Array
	 */
	protected $navMenus = array();
	
	
	protected $telData ;
	
	
	public function __construct() {
		//这行一定放在最前面; *因为__set方法用到它(当$this->xx = xx 的时候调用此方法)*
		$this->_view = new CViewRender ();
		$this->telData = $this->includeTemplateData();
		
		$this->ctl = $this->getController ();
		$this->act = $this->getAction ();
		$this->exe = $this->getExecName ();
	
	}
	
	/**
	 * 加载环境
	 */
	abstract public function prepare($args);
	
	/**
	 * 回显html内容
	*/
	public function display() {
		if ($this->_setTemplate) {
			$content = $this->_view->display ();
			return $content;
		}
	}
	
	/**
	 * 获取模板解析后的内容
	 */
	public function fetch($file) {
		
		///////////////增加/////////////////
		if(isset($this->telData[$file])){
			$this->tpl = $this->telData[$file];
			return $this->render(true);
		}
		////////////////////////////////
		
		$this->setTemplate ( $file );
		$content = $this->_view->fetch ();
		return $content;
	}
	
	/**
	 * 设置模板
	 */
	public function setTemplate($file) {
		///////////////增加/////////////////
		if(isset($this->telData[$file])){
			$this->tpl = $this->telData[$file];
			$this->render();
			return true;
		}
		////////////////////////////////
		
		
		$this->_setTemplate = true;
		$this->_view->setTemplate ( $file );
	}
	
	/**
	 * 魔术方法,自动给模板提供数据 *important!*
	 */
	public function __set($key, $val) {
		$this->$key = $val;
		$this->setOutput($key, $val);
		//再分配给模板
		$this->_view->set ( $key, $val );
	}
	
	/**
	 * 魔术方法,控制器中,调用没有的方法,直接到request中调用 *important!*
	 * 如:$this->getController();
	 */
	public function __call($method, $args) {
		//return call_user_func_array(array(CBase::$request, $method), $args);
	}
	
	/**
	 * 消息提示,后续扩展
	 */
	public function showMessage($msg, $url = '') {
	
		$str = '<script>';
		if ($msg) {
			$str .= "alert('$msg');";
		}
		if ($url) {
			$str .= "location.href ='$url';";
		} else {
			if ($second) {
				$str .= "top.location.reload();";
			} else {
				$str .= "history.go(-1);";
			}
		}
		$str .= '</script>';
		die ( $str );
	}
	
	/**
	 * 表单提交后,映射到相应的处理方法
	 */
	public function submitMap() {
		$funcName = "_" . strtolower ( $this->act ) . $this->exe;
		if (! method_exists ( $this, $funcName )) {
			$this->showMessage ( '参数错误,非法操作~' );
		}
		//处理
		$this->$funcName ();
	}
	
	
	/**
	 * 获取控制器名称
	 */
	public function getController()
	{
		$conName = ucfirst(strip_tags($_REQUEST['c']));
		return $conName ? $conName : 'Default';
	}
	
	/**
	 * 获取动作
	 */
	public function getAction()
	{
		return isset($_REQUEST['a']) ?  ucfirst(strip_tags($_REQUEST['a'])) : 'Default';
	}
	
	/**
	 * 获取动作
	 */
	public function getExecName()
	{
		return isset($_REQUEST['e']) ?  ucfirst(strip_tags($_REQUEST['e'])) : '';
	}
	
	
	/**
	 *
	 * 渲染结果
	 * @param boolean $return 是否返回。true:返回渲染结果;false:直接输出结果
	 * @return string | NULL
	 */
	public function render($return = false) {
		if (!$this->tpl) {// 没有指定模文件
			return null;
		}
		
		$objView = new View();
	
		$this->output['navMenus'] = $this->navMenus;
	
		$config = Config::getInstance()->current();
		$this->output['web_cfg'] = $config['web_cfg'];
	
		$objView->assign($this->output);
		
		if ($return) {
			return $objView->r($this->tpl);
		} else {
			$objView->d($this->tpl);
		}
	}
	
	/**
	 * 添加导航栏
	 *
	 * @param string $title
	 * @param string $href
	 * @param string $target
	 * @param string $icon
	 * @return \KIF\Core\Controller
	 */
	protected function addNavMenu($title, $href = null, $target = '_self', $icon = null) {
		$this->navMenus[] = array(
				'title' => $title,
				'href' => $href,
				'target'	=> $target,
				'icon' => $icon,
		);
		return $this;
	}
	
	/**
	 *
	 * 设定指定的名、值,模版里可以使用到
	 * @param string $name
	 * @param mixed $value
	 * @throws Exception
	 */
	protected function setOutput($name, $value) {
		if (!is_string($name)) {
			throw new Exception('set output to template error, name not string !');
		}
		$this->output[$name] = $value;
	}
	
	/**
	 * 获取专题数据文件
	 *
	 * @param string $name
	 */
	static public function includeTemplateData() {
		//$appPath = Config::getInstance ()->get ( 'App_Path' );
		return include '/export/manager/product/app/product/kif/include/FControllerTemplate.data.php';
	}
	
	
}


class CViewRender extends CRender {
	/**
	 * 构造函数
	 *
	 * @param string $templateFile    模板文件(扩展名为:tpl.php)
	 * @param string $templateEngine  模板引擎
	 */
	public function __construct($templateFile = null, $templateEngine = "php") {
		
		if (! $templateEngine)
			$templateEngine = "php";
		if (! is_null ( $templateFile ))
			$this->setTemplate ( $templateFile );
	}

	/**
	 * 显示解析模板内容
	 */
	public function display() {
		//$timer2 = new CTimer('模板渲染耗时:');
		$content = $this->render ();
		echo $content;
		return $content;

		//echo $timer2->mark('secs ', 6)."<br/>";
	}

	/**
	 * 包含模板文件
	 */
	public function embedFile($file) {
		if ($this->checkTemplateFile ( $file )) {
			if ($this->_viewData) {
				extract ( $this->_viewData );
			}
			include_once (APP_TEMPLATE . '/' . $file . '.tpl.php');
		}
	}

	/**
	 * 获取模板内容
	 */
	public function fetch() {
		return $this->render ();
	}

	/**
	 * 设置$_viewData数组值
	 */
	public function set($key, $val) {
		$this->_viewData [$key] = $val;
	}

	/**
	 * 魔术函数  给类属性赋值
	 */
	public function __set($key, $val) {
		$this->set ( $key, $val );
	}

	/**
	 * 设置模板文件
	 *
	 * @param  string $templateFile   缺损模板文件名
	 */
	public function setTemplate($file) {
		$this->_templateFile = (defined ( 'APP_TEMPLATE' ) ? APP_TEMPLATE . '/' : "") . $file . ".tpl.php";
	}

	/**
	 * 获取模板文件名
	 */
	public function getTemplate() {
		return $this->_templateFile;
	}

	/**
	 * 解析模板并返回内容
	 *
	 * @return string 解析内容
	 */
	public function render() {
		//$timer2 = new CTimer($this->_templateFile.'渲染耗时内部调试:');
		if (! $this->checkTemplateFile ( $this->_templateFile )) {
			trigger_error ( "($this->_templateFile)模板文件不存在" );
		}

		if ($this->_viewData) {
			extract ( $this->_viewData );
		}
		//开始缓存
		ob_start ();
		include ($this->_templateFile);
		$content = ob_get_clean ();
		ob_flush ();
		flush ();
		//echo $timer2->mark('secs ', 6)."<br/>";
		return $content;
	}
}


abstract class CRender {
	/**
	 * @var array  提取的内容数据
	 */
	protected $_viewData;

	/**
	 * @var string   模板文件
	 */
	protected $_templateFile;

	/**
	 * 解析模板文件并输出渲染内容
	 */
	abstract function display();

	/**
	 * 获取模板内容
	*/
	abstract function fetch();

	/**
	 * 渲染内容
	*/
	abstract function render();

	/**
	 * 验证文件是否存在
	 *
	 * @return boolean
	*/
	public function checkTemplateFile() {

		if (! $this->_templateFile) {
			//           throw new Exception("ddd");
			return false;
		}

		if (! is_file ( $this->_templateFile )) {
			//             throw new Exception("模板文件不存在:".$this->_templateFile);
			return false;
		}

		return true;
	}
}