<?php

namespace think\addons;

use think\Request;
use think\Config;
use think\Loader;

/**
 * 插件基类控制器
 * Class Controller
 * @package think\addons
 */
class Controller extends \think\Controller
{
    // 当前插件操作
    protected $addon = null;
    protected $controller = null;
    protected $action = null;
    // 当前template
    protected $template;
    // 模板配置信息
    protected $config = [
        'type' => 'Think',
        'view_path' => '',
        'view_suffix' => 'html',
        'strip_space' => true,
        'view_depr' => DS,
        'tpl_begin' => '{',
        'tpl_end' => '}',
        'taglib_begin' => '{',
        'taglib_end' => '}',
    ];

    /**
     * 架构函数
     * @param Request $request Request对象
     * @access public
     */
    public function __construct(Request $request = null)
    {
        WSTConf('CONF',WSTConfig());
        if(WSTConf('CONF.seoShopSwitch')==0){
            $this->redirect('home/switchs/index');
            exit;
        }
        if (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            $isWeapp = (int)input('isWeapp',0);
            if($isWeapp!=1){
                $USER = session('WST_USER');
                if(empty($USER)) {
                    $openId = session('WST_WX_OPENID');
                    $state = input('param.state');
                    if($openId=="" && $state!=WSTConf('CONF.wxAppCode')){
                        $request = request();
                        $url=urlencode($request->url(true));
                        $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.WSTConf('CONF.wxAppId').'&redirect_uri='.$url.'&response_type=code&scope=snsapi_userinfo&state='.WSTConf('CONF.wxAppCode').'#wechat_redirect';
                        header("location:".$url);
                        exit;
                    }
                    if($state==WSTConf('CONF.wxAppCode')){
                      $request = request();
                        $url=urlencode($request->url(true));
                        $type = input('param.type');
                        if($type=='1'){
                            WSTBindWeixin(1);
                        }else{
                            WSTBindWeixin(0);
                        }
                    }
                    $wechatAutoRegister = WSTConf('CONF.wechatAutoRegister');
                    if($wechatAutoRegister) {
                        WSTAutoRegister(1);
                    }
                }
            }
        }
        // 生成request对象
        $this->request = is_null($request) ? Request::instance() : $request;
        // 初始化配置信息
        $this->config = Config::get('template') ?: $this->config;
        // 处理路由参数
        $route = $this->request->param('route', '');
        $param = explode('-', $route);
        // 是否自动转换控制器和操作名
        $convert = \think\Config::get('url_convert');
        // 格式化路由的插件位置
        $this->action = $convert ? strtolower(array_pop($param)) : array_pop($param);
        $this->controller = $convert ? strtolower(array_pop($param)) : array_pop($param);
        $this->addon = $convert ? strtolower(array_pop($param)) : array_pop($param);
        WSTSwitchs($this->addon,$this->controller,$this->action,'addon');
        $base = new \think\addons\BaseModel();
        $status = $base->getAddonStatus(ucfirst($this->addon));
        if(isset($status) && $status!=1){
            $request = request();
            $module = WSTVisitModule();
            header("Location:".url($module.'/error/index'));
        	exit();
        }
        // 生成view_path
        $view_path = $this->config['view_path'] ?: 'view';

        // 重置配置
        Config::set('template.view_path', ADDON_PATH . $this->addon . DS . $view_path . DS);
        parent::__construct($request);
        $this->assign("v",WSTConf('CONF.wstVersion')."_".WSTConf('CONF.wsthomeStyleId'));
        $this->initLayout();
    }

    /**
     * 定义模板
     */
    public function initLayout(){
        $wsthomeStyle = WSTConf('CONF.wsthomeStyle')?WSTConf('CONF.wsthomeStyle'):'default';
        $wstmobileStyle = WSTConf('CONF.wstmobileStyle')?WSTConf('CONF.wstmobileStyle'):'default';
        $wstwechatStyle = WSTConf('CONF.wstwechatStyle')?WSTConf('CONF.wstwechatStyle'):'default';
        $this->assign('LAYOUT_HOME_BASE','home@'.$wsthomeStyle.'/base');
        $this->assign('LAYOUT_HOME_TOP','home@'.$wsthomeStyle.'/top');
        $this->assign('LAYOUT_HOME_HEADER','home@'.$wsthomeStyle.'/header');
        $this->assign('LAYOUT_HOME_RIGHT_CART','home@'.$wsthomeStyle.'/right_cart');
        $this->assign('LAYOUT_HOME_FOOTER','home@'.$wsthomeStyle.'/footer');
        $this->assign('LAYOUT_HOME_USER_BASE','home@'.$wsthomeStyle.'/users/base');
        $this->assign('LAYOUT_HOME_USER_HEADER','home@'.$wsthomeStyle.'/users/header');
        $this->assign('LAYOUT_ADMIN_BASE','admin@base');
        $this->assign('LAYOUT_MOBILE_BASE','mobile@'.$wstmobileStyle.'/base');
        $this->assign('LAYOUT_MOBILE_DIALOG','mobile@'.$wstmobileStyle.'/dialog');
        $this->assign('LAYOUT_MOBILE_FOOTER','mobile@'.$wstmobileStyle.'/footer');
        $this->assign('LAYOUT_WECHAT_BASE','wechat@'.$wstwechatStyle.'/base');
        $this->assign('LAYOUT_WECHAT_DIALOG','wechat@'.$wstwechatStyle.'/dialog');
        $this->assign('LAYOUT_WECHAT_FOOTER','wechat@'.$wstwechatStyle.'/footer');
    }
    
    public function checkAdminAuth(){
    	
    	$STAFF = session('WST_STAFF');
    	$request = request();
    	if(empty($STAFF)){
    		if($request->isAjax()){
    			echo json_encode(['status'=>-999,'msg'=>'对不起，您还没有登录，请先登录']);
    		}else{
    			header("Location:".url('admin/index/login'));
    		}
    		exit();
    	}else{
	    	$urls = WSTVisitPrivilege();
	    	$privileges = session('WST_STAFF.privileges');
	        $visit = $request->path();
	        if(!$privileges || (array_key_exists($visit,$urls) && !$this->checkUserCode($urls[$visit],$privileges))){
	        	if($request->isAjax()){
	        		echo json_encode(['status'=>-998,'msg'=>'对不起，您没有操作权限，请与管理员联系']);
	        	}else{
	        		header("Content-type: text/html; charset=utf-8");
	        	    echo "对不起，您没有操作权限，请与管理员联系";
	        	}
	        	exit();
	        }
    	}
    }
    private function checkUserCode($urlCodes,$userCodes){
        foreach ($urlCodes as $key => $value) {
            if(in_array($key,$userCodes))return true;
        }
        return false;
    }

    // 登录验证方法--用户
    protected function checkAuth(){
        $USER = session('WST_USER');
        if(empty($USER)){
            if(request()->isAjax()){
                die('{"status":-999,"msg":"您还未登录"}');
            }else{
                $module = WSTVisitModule();
                $this->redirect($module.'/users/login');
                exit;
            }
        }else{
            $userId = (int)session('WST_USER.userId');
            $uinfo = model("common/Users")->getFieldsById($userId,"userStatus,dataFlag");
            if(!($uinfo['dataFlag']==1 && $uinfo['userStatus']==1)){
                session('WST_USER',null);
                if(request()->isAjax()){
                    die('{"status":-1,"msg":"您的帐号已停用，请联系管理员"}');
                }else{
                    $module = WSTVisitModule();
                    $this->redirect($module.'/users/login');
                    exit;
                }
                
            }
        }
    }
    /**
    * 重写父类前置方法判断
    */
    protected function beforeAction($method, $options = [])
    {
        // 设置当前访问的controller、action
        request()->controller($this->controller);
        request()->action($this->action);
        if (isset($options['only'])) {
            if (is_string($options['only'])) {
                $options['only'] = explode(',', $options['only']);
            }
            if (!in_array($this->request->action(), $options['only'])) {
                return;
            }
        } elseif (isset($options['except'])) {
            if (is_string($options['except'])) {
                $options['except'] = explode(',', $options['except']);
            }
            if (in_array($this->request->action(), $options['except'])) {
                return;
            }
        }

        call_user_func([$this, $method]);
    }
    

    /**
     * 加载模板输出
     * @access protected
     * @param string $template 模板文件名
     * @param array $vars 模板输出变量
     * @param array $replace 模板替换
     * @param array $config 模板参数
     * @return mixed
     */
    public function fetch($template = '', $vars = [], $replace = [], $config = []){
        $controller = Loader::parseName($this->controller);
        if ('think' == strtolower($this->config['type']) && $controller && 0 !== strpos($template, '/')) {
            $depr = $this->config['view_depr'];
            $template = str_replace(['/', ':'], $depr, $template);
            if ('' == $template) {
                // 如果模板文件名为空 按照默认规则定位
                $template = str_replace('.', DS, $controller) . $depr . $this->action;
            } elseif (false === strpos($template, $depr)) {
                $template = str_replace('.', DS, $controller) . $depr . $template;
            }
        }
        $replace['__STYLE__'] = str_replace('/index.php','',\think\Request::instance()->root()).DS.'wstshop'.DS.'home'.DS.'view'.DS.WSTConf('CONF.wsthomeStyle');
        $replace['__ADMIN__'] = str_replace('/index.php','',\think\Request::instance()->root()).DS.'wstshop'.DS.'admin'.DS.'view';
        $replace['__WECHAT__'] = str_replace('/index.php','',\think\Request::instance()->root()).DS.'wstshop'.DS.'wechat'.DS.'view'.DS.WSTConf('CONF.wstwechatStyle');
        $replace['__MOBILE__'] = str_replace('/index.php','',\think\Request::instance()->root()).DS.'wstshop'.DS.'mobile'.DS.'view'.DS.WSTConf('CONF.wstmobileStyle');
        $replace['__RESOURCE_PATH__'] = WSTConf('CONF.resourcePath');
        return \Think\Controller::fetch($template, $vars, $replace, $config);
    }
    
    /**
     * 模板变量赋值
     * @access protected
     * @param mixed $name  要显示的模板变量
     * @param mixed $value 变量的值
     * @return void
     */
    public function assign($name, $value = ''){
    	$this->view->assign($name, $value);
    }
    
}
