<?php
namespace app\daohang\controller;

use app\common\controller\Base;

class Front extends Base
{
    protected $homePage = 'https://www.daicuo.org/product/daohang';
    
    // 继承初始化方法
    public function _initialize()
    {
        // 继承上级
        parent::_initialize();
        // 权限验证
        $this->_authCheck();
        // 模板路径
        $this->site['path_view'] = config('template.view_path');
        // 前台钩子
        \think\Hook::listen('hook_front_init', $this->site);
        // 模板标签
        $this->assign($this->site);
	}
    
    //空操作
    public function _empty($action='')
    {
        $this->actionCheck($action);
        
        //加载模板
        $tplPath = './'.$this->site['path_view'].$this->site['controll'].'/'.$action.'.tpl';
        if(is_file($tplPath)){
            return $this->fetch($action);
        }
        
        return '扩展内容模型需自行开发模板（'.$tplPath.'）';
    }

    //请求验证
    protected function requestCheck()
    {
        //后台验证开关
        $configMax = intval(config('daohang.request_max'));
        if($configMax < 1){
            return true;
        }
        //客户端唯一标识
        $client = md5($this->request->ip().$this->request->header('user-agent'));
        //60秒内最大请求次数
        $requestMax = intval(DcCache('request'.$client));
        if($requestMax > $configMax){
            $this->error(lang('daohang/error/rest'), 'daohang/index/index');
        }
        //记录客户端请求数
        DcCache('request'.$client, $requestMax+1, 300);
    }
    
    //模型验证
    protected function actionCheck($action='index')
    {
        //模型扩展开关
        if(!config('daohang.plus_action')){
            $this->error(lang('daohang/error/action'), $this->homePage);
        }
        //允许的操作名
        if(!in_array($action,explode(',',config('daohang.plus_action')))){
            $this->error(lang('daohang/error/action'), $this->homePage);
        }
        //合法请求
        return true;
    }
    
    //模板加载
    protected function fetchTpl($action='index', $tplName='')
    {
        //自定义模板名
        if($tplName){
            $action = $tplName;
        }
        //默认模板名直接加载
        if($action == 'index'){
            $this->fetch('index');
        }
        //自定义模型或自定义模板名需验证路径
        if( is_file('./'.$this->site['path_view'].$this->site['controll'].'/'.$action.'.tpl') ){
            return $this->fetch($action);
        }
        //初始加载
        return $this->fetch('index');
    }
}