<?php
/**
* @author 龙虾 <15108148@qq.com>
* @version 2.0 2020-11-20
* @copyright 睿谷信息 <www.rgxx.com>
*/
namespace app\admin\controller;
use think\Controller;
use think\facade\Cache;
use app\common\model\Site;
use app\admin\model\Admin;
use app\admin\model\Adminrule;

class Base extends Controller
{
	// 管理员信息
	protected $admininfo;
	// 管理员菜单
	protected $adminmenu;
	// 站点信息
	protected $siteinfo;
	protected function initialize()
	{
		// 登录入口验证
		if(!defined('ENTER_NAME') || ENTER_NAME != 'ADMIN') {
			// $this->error(lang('errorpage'));
			abort(404,lang('errorpage'));
		}
		if(empty($this->request->syssn)) {
			$this->error('&#25480;&#26435;&#38169;&#35823;&#65292;&#31995;&#32479;&#29256;&#26435;&#20445;&#25252;&#65292;&#35831;&#32852;&#31995;&#82;&#71;&#67;&#77;&#83;&#23448;&#26041;&#65281;','//www.rgxx.com');
		}
		// 插入表单令牌
		// $this->view->filter(function($content){
		// 	if(strpos($content,'{__token__}')) {
		// 		$input_token = token(config('app.admin.token_name'));
		// 		// 指定表单令牌隐藏域位置
		// 		$content = str_replace('{__token__}',$input_token,$content);
		// 	}elseif(preg_match('/<\/form(\s*)>/is',$content,$match)) {
		// 		$input_token = token(config('app.admin.token_name'));
		// 		// 智能生成表单令牌隐藏域
		// 		$content = str_replace($match[0],$input_token.$match[0],$content);
		// 	}
		// 	return $content;
		// });
		$local_rule = strtolower(request()->controller() .'/'. request()->action());
        // 判断管理员登录
		if(session('?adminid')) {
			// 验证SESSION是否过期
			if(intval(config('app.admin.sessionexpire'))!==0) {
				if(session('session_start_time')) {
					if(time()-session('session_start_time') > intval(config('app.admin.sessionexpire')*60)) {
						loginlog(session('adminid'),'超时退出',2);
						session('adminid',NULL);
						session('siteid',NULL);
						session('session_start_time',NULL);
						session('sitealias',NULL);
						if(request()->isPost()) {
			        		$this->error(lang('relogin'),'index/login');
			        	} else {
			        		$this->redirect('index/login');
			        	}
					}
				}
				session('session_start_time',time()); //重新设置开始时间
			}
			// 管理员信息
			if(!Cache::get('admininfo'.session('adminid'))) {
				Cache::tag('admininfo')->set('admininfo'.session('adminid'),Admin::getAdminInfo(session('adminid')));
			}
			$this->admininfo = Cache::get('admininfo'.session('adminid'));
			if(is_null($this->admininfo)) {
				cache('admininfo'.session('adminid'),NULL);
				session('adminid',NULL);
				session('siteid',NULL);
				session('session_start_time',NULL);
				session('sitealias',NULL);
				$this->error(lang('accounterror'),'index/login');
			}
			// 管理规则并缓存(管理组ID)
			if(!Cache::get('adminmenu'.$this->admininfo['admingroup_id'])) {
				Cache::tag('adminmenu')->set('adminmenu'.$this->admininfo['admingroup_id'],Adminrule::getRules($this->admininfo['admingroup_id']));
			}
			$this->adminmenu = Cache::get('adminmenu'.$this->admininfo['admingroup_id']);
			// 站点ID
			if(!session('?siteid')) {
				$this->siteinfo = Site::whereIsdefault(1)->find();
			} else {
				$this->siteinfo = Site::get(session('siteid'));
			}
			session('siteid',$this->siteinfo['id']);
			session('sitealias',$this->siteinfo['alias']);
			$this->assign('siteinfo',$this->siteinfo);
			// 无需权限验证的规则
			$except_rule = [
				'index/login',		  // 登录页面
				'index/forget',		  // 密码找回
				'index/loginout',	  // 退出页面
				'index/index',		  // 后台首页
				'index/welcome',	  // 后台欢迎页
				'index/clearcache',   // 清除缓存
				'index/clearindex',   // 清除首页
				'cmsmodel/index',

				'upgrade/check_version',	// 版本检测
				'upgrade/system_update',	// 在线更新

				'upload/upload',      // 上传
				'media/show',      	  // 素材库
				'navlist/getnav',     // 获取栏目列表
				'token/getajaxtoken', // 获取ajax提交token
				'index/ajaxform'
				];
			$pageinfo = [];
			// 对已登陆的非开发组的权限认证
			if(!in_array($local_rule,$except_rule)) {
				// 暂时弃用此方式
				// if(!$this->admininfo['isboss']) {
				// 	$auth = new \rg\Auth();
				// 	if(!$auth->check($local_rule,$this->admininfo['id'])) {
				// 		$this->error(lang('noauth'));
				// 	}
				// }
				// 获取页面信息,权限认证
				$pageinfo_arr = array_column($this->adminmenu,NULL,'name');
				unset($pageinfo_arr['']);
				if(isset($pageinfo_arr[$local_rule])) {
					$pageinfo = $pageinfo_arr[$local_rule];
					$this->assign('pageinfo',$pageinfo);
					$this->assign('mbx',get_father($this->adminmenu,$pageinfo['id'])); // 面包屑
				} else {
					$this->error(lang('noauth'));
				}
			}
			$this->assign('admininfo',$this->admininfo);
		} else {
	        $except_login = ['index/login','index/forget'];
	        if(!in_array($local_rule,$except_login)) {
	        	if(request()->isPost()) {
	        		$this->error(lang('relogin'),'index/login');
	        	} else {
	        		$this->redirect('index/login');
	        	}
	        }
		}
	}


	// 表单令牌验证
    final public function checkToken($data)
    {
    	$name = "__rgcmsadmin__";
        if (!isset($data[$name])) {
            return false;
        }
        $validate = \Validate::make(["{$name}" => 'token:'.$name]);
        if (!$validate->check(["{$name}" => $data[$name]])) {
            return false;
        }
        return true;
    }

    // 自定义字段验证
	final public function checkDiyData($model_id,$data)
	{
		if(!isset($data['list_switch'])) {
			$validate = new \think\Validate;
			$rulelist = [];
			$listfields = model('modelfields')
				->where('model_id','=',$model_id)
				->where('status','=',1)
				->order('torder')->select()->toArray();
			foreach ($listfields as $k => $v) {
				$rule = [];
				if($v['verify'] == 'required') {
					$rule = array_merge(['require'],$rule);
				}
				if($v['type'] == 't2') {
					$rule = array_merge(['integer'],$rule);
				}
				if($v['type'] == 't3') {
					$rule = array_merge(['float'],$rule);
				}
				if($v['rule']) {
					$rule = array_merge([$v['rule']],$rule);
				}
				$rulelist[$v['name'].'|'.$v['title']] = $rule;
			}
			$validate->rule($rulelist);
			if (!$validate->check($data)) {
				$this->error($validate->getError());
			}
		}
	}

	// 空操作
	public function _empty()
	{
		$this->error(lang('noact'));
	}
}