<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/22
 * Time: 19:26
 */

abstract  class BaseController
{
    protected  $view_data=[];
    public function __construct()
    {
        $this->req=(new \Request());
        $class=get_called_class();
        $function_path=DOXCX_FRAME_PATH.str_replace("\\",DIRECTORY_SEPARATOR,strstr($class,'Controller',true)).'function.php';
        if(is_file($function_path)){
            include_once $function_path;
        }
        $this->_initialize();
    }
    public function _initialize(){

    }
    /**
     * 渲染模版
     * @param string $template
     * @param bool $bind_function #是否强制绑定并自动寻找当前方法的模版
     * @return false|string
     * @throws \Exception
     */
    public function show($template='',$bind_function=false){
        global $_PAGE;
        //需要视图 先计算出视图路径和 编译后的文件路径

        //加载编译后的视图文件
        // 页面缓存
        if(!$template&&$bind_function===true){ #自动寻找实际调用的类和方法
            $dispatcher_info=debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS,2)[1];
            $dispatcher_method=$dispatcher_info['function'];
            $view_path=ltrim(str_replace(['\\','/Controller/'],['/','/View/'],$dispatcher_info['class']),'/');
            $template=$view_path.'/'.$dispatcher_method;
        }

        ob_start();
        ob_implicit_flush(0);

        try {
            \Page::$my_view = $template;
            $_PAGE->tpl_replace_string['__PLUGIN__']=plugin_static();//添加自定义插件前端路径
            $_PAGE->_transpath();
            //编译视图模板
            $_PAGE->_trans();
            extract($this->view_data);
            //加载标签输出主文件
            include_once DOXCX_LIB.'/sys/tag.php';

            include $_PAGE->com_path;

        } catch (\Exception $e) {
            ob_end_clean();
            throw $e;
        }

        $content=ob_get_clean();
        //自动执行后台的推送的JS脚本
        if(!empty(\Page::$js_arr)){
            $content.='<script type="text/javascript">DOXCX(function(){'.implode(";", Page::$js_arr).'});</script>';
        }
        return $content;
    }
    /**
     * 分配模版变量
     * @param $name
     * @param $value
     * @return $this
     */
    public function assign($name,$value){
        if (is_array($name)) {
            $this->view_data = array_merge($this->view_data, $name);
        } else {
            $this->view_data[$name] = $value;
        }
        return $this;
    }
}