<?php
namespace app\index\behavior;
use think\Request;
use think\facade\Config;
use think\Loader;
use think\Container; 
use traits\controller\Jump;
use think\exception\HttpResponseException;
use think\Response;
use think\response\Redirect;
abstract class Plugin {
	 use Jump;
   /**
     * 视图实例对象
     * @var view
     * @access protected
     */
    protected $view = null;

    public $info                =   array();
    public $addon_path          =   '';
    public $config_file         =   '';
    public $custom_config       =   '';
    public $admin_list          =   array();
    public $custom_adminlist    =   '';
    public $access_url          =   array();

    protected $beforeActionList = [];
	
	
    protected $middleware = [];
 // 模板配置信息
    protected $config = [
        'type' => 'Think',
        'view_path' => '',
        'view_suffix' => 'html',
        'strip_space' => true,
        'view_depr' => '',
        'tpl_begin' => '{',
        'tpl_end' => '}',
        'taglib_begin' => '{',
        'taglib_end' => '}',
    ];
  
    public function __construct()
	
    {     $this->app     =  Container::get('app');
		  $this->request = $this->app['request'];
       

       

              // 初始化配置信息
        $this->config = Config::get('template') ?: $this->config;
		
      
		$this->view_path = $this->config['view_path'] ?: 'view/';
		$this->view = Container::get('view')?Container::get('view'):'view/'; 

        $this->plugin_path   =   PLUGIN_PATH . $this->getName() . '/';    
        if(is_file($this->plugin_path . 'config.php')){
            $this->config_file = $this->plugin_path . 'config.php';
        } 
		$this->assign( "common",INSTALL_PATH.'public/common');
		$this->assign( "img", http().input("server.HTTP_HOST").INSTALL_PATH.'plugin/'. $this->getName(). '/'.$this->view_path.'static/images');
		$this->assign( "css",INSTALL_PATH.'plugin/'. $this->getName(). '/'.$this->view_path.'static/css');
		$this->assign( "js",INSTALL_PATH.'plugin/'. $this->getName(). '/'.$this->view_path.'static/js');
		$this->assign( "root",INSTALL_PATH);
		$this->assign( "plugin",INSTALL_PATH.'plugin/'. $this->getName());
    }
	
	
      final protected function assign($name = '', $value='')
    {
        $this->view->engine->assign($name, $value);
        return $this;
    } 
	  
    public function registerMiddleware()
    {
        foreach ($this->middleware as $key => $val) {
            if (!is_int($key)) {
                $only = $except = null;

                if (isset($val['only'])) {
                    $only = array_map(function ($item) {
                        return strtolower($item);
                    }, $val['only']);
                } elseif (isset($val['except'])) {
                    $except = array_map(function ($item) {
                        return strtolower($item);
                    }, $val['except']);
                }

                if (isset($only) && !in_array($this->request->action(), $only)) {
                    continue;
                } elseif (isset($except) && in_array($this->request->action(), $except)) {
                    continue;
                } else {
                    $val = $key;
                }
            }

            $this->app['middleware']->controller($val);
        }
    }

  
    protected function beforeAction($method, $options = [])
    {
        if (isset($options['only'])) {
            if (is_string($options['only'])) {
                $options['only'] = explode(',', $options['only']);
            }

            $only = array_map(function ($val) {
                return strtolower($val);
            }, $options['only']);

            if (!in_array($this->request->action(), $only)) {
                return;
            }
        } elseif (isset($options['except'])) {
            if (is_string($options['except'])) {
                $options['except'] = explode(',', $options['except']);
            }

            $except = array_map(function ($val) {
                return strtolower($val);
            }, $options['except']);

            if (in_array($this->request->action(), $except)) {
                return;
            }
        }

        call_user_func([$this, $method]);
    }
	final protected function theme($theme)
    {
        $this->view->theme($theme);
        return $this;
    }
 
    final protected function fetch($templateFile = CONTROLLER_NAME)
    {
        if(!is_file($templateFile)){
            $templateFile = $this->plugin_path .$this->view_path. $templateFile . ".html";
            if(!is_file($templateFile)){
                die('_TEMPLATE_NOT_EXIST_' . ":$templateFile");
            }
        }  
		return $this->view->engine->layout(false)->fetch($templateFile);
     
    }
	
  /**
     * 获取插件名
     * @return string
     */
    final public function getName()
    {
        $class = get_class($this);
        list($space, $name, $class) = explode('\\', $class);

        return $name;
    }
	
   
    /**
     * 检查配置信息是否完整
     * @return bool
     */
    final public function checkInfo()
    {
        $info_check_keys = array('name','title','description','status','author','version');
        foreach ($info_check_keys as $value) {
            if(!array_key_exists($value, $this->info))
                return false;
        }
        return true;
    } 
	
	final public function jumpurl($url = '')
    {
      header('Location: ' . $url);exit;
    }
  
    final public function getConfig($name = '')
    {
        static $_config = [];
        if(empty($name)){
            $name = $this->getName();
        }
        if(isset($_config[$name])){
            return $_config[$name];
        }
       
        $map['name']    =   $name;
        $map['status']  =   1;
			
        $config  =   db('plugin')->where($map)->value('config');
        if($config){
            $config   =   json_decode($config, true);
        }else{
            $config =   [];
            $arr = include $this->config_file;
		
            foreach ($arr as $key => $value) {
			
                if($value['type'] == 'group'){
                    foreach ($value['options'] as $gkey => $val) {
                        foreach ($val['options'] as $k => $v) {
                            $config[$k] = $v['value'];
                        }
                    }
                }else{
					
                    $config[$key] =isset($arr[$key]['value'])?$arr[$key]['value']:'';
                }
            }
			
        }
        $_config[$name]     =   $config;
        return $config;
    }
  
    /**
     * 必须实现安装
     * @return mixed
     */
    abstract public function install();

    /**
     * 必须卸载插件方法
     * @return mixed
     */
    abstract public function uninstall();

}