<?php
namespace app\bsadmin\middleware;
use think\facade\View;
use think\facade\Session;
use think\facade\Cache;
use app\bsadmin\model\Admin as AdminModel;
use app\bsadmin\model\AdminLog as AdminLogModel;

class Auth
{
    public function handle($request, \Closure $next)
    {
        if(Session::has('AdminUser')&&!AdminModel::where(['id'=>Session::get('AdminUser.uid')])->value('status')){
            Session::delete('AdminUser');
        }
        $nowTime=intval(date('H'));
        if(!($nowTime>=Session::get('AdminUser.start') && $nowTime<=Session::get('AdminUser.end') && in_array(date('w'),explode(',',Session::get('AdminUser.week'))))){
            Session::delete('AdminUser');
        }
        $authRet=$this->auth();
        if (true!==$authRet) {
            if(request()->isAjax()){
                $this->ajaxReturn($authRet,-100);
            }else{
                if (request()->controller()!='Login' 
                    || request()->action()!='unauthorized') {
                    return redirect('/unauthorized?msg='.$authRet);
                }
            }
        }else{
            if ($request->controller()=='Login') {
                if(Session::has('AdminUser')){
                    if (Session::has('redirect_remember')){
                        Session::delete('redirect_remember');
                        return redirect()->restore();
                    }
                    return redirect('/');
                }
            }else{
                if(!Session::has('AdminUser.uid')){
                    if (request()->isAjax()) {
                        $this->ajaxReturn('请先登录',-100);
                    }else{
                        Session::set('redirect_remember',true);
                        return redirect('/login')->remember();
                    }
                }
            }
        }
        return $next($request);
    }
    protected function auth()
    {
        $McaWhere['domain']=app('http')->getName();
        $McaWhere['controller']=request()->controller();
        $McaWhere['fun']=request()->action();
        $roleId=Session::get('AdminUser.rid');
        $role=config('role.'.$roleId);
        $NotVerify=config('auth_not_verify.'.$McaWhere['domain'].'/'.$McaWhere['controller'].'/'.$McaWhere['fun']);
        $admin_log=new AdminLogModel;
        $AuthMenu=Cache::get('role.auth_menu');
        if ($AuthMenu && !empty($AuthMenu[$roleId])) {
            $AuthMenu=$AuthMenu[$roleId];
        }else{
            $AuthMenu='[]';
        }
        $auth_ret='';
        if ($NotVerify) {
            $admin_log->l_title=$NotVerify['title'];
            $admin_log->l_uid=0;
            $admin_log->l_route=request()->url();
            $admin_log->l_rol_mcaute=json_encode($McaWhere,JSON_UNESCAPED_UNICODE);
            if (!request()->isPost())
                $admin_log->l_param=json_encode(request()->param(),JSON_UNESCAPED_UNICODE);
            $admin_log->l_ip=request()->ip();
            $McaFind=['aid'=>1,'pid'=>0,'ppid'=>1,'status'=>1,'title'=>$NotVerify['title']];
            $auth_ret=$admin_log->save()?true:false;
        }else{
            if (!Session::has('AdminUser'))
                return true;
            $McaFind=config('auth.'.$McaWhere['domain'].'/'.$McaWhere['controller'].'/'.$McaWhere['fun']);
            if($McaFind && in_array($McaFind['aid'],$role['auth'])){
                $admin_log->l_title=$McaFind['title'];
                $admin_log->l_uid=Session::get('AdminUser.uid');
                $admin_log->l_route=request()->url();
                $admin_log->l_rol_mcaute=json_encode($McaWhere,JSON_UNESCAPED_UNICODE);
                if (!request()->isPost())
                    $admin_log->l_param=json_encode(request()->param(),JSON_UNESCAPED_UNICODE);
                $admin_log->l_ip=request()->ip();
                $admin_log->save();
                if($McaFind['status']){
                    $auth_ret=true; 
                }else{
                    $auth_ret='系统维护，暂停访问';
                }
            }else{
                $auth_ret='无权访问';
            }
        }
        if (!request()->isAjax()){
            View::assign('webtitle',$McaFind['title']);
            View::assign('AuthMenu',$AuthMenu);
            View::assign('McaFind',$McaFind);
        }
        return $auth_ret;
    }
    /**
     * [ajaxReturn 返回json]
     * @param  integer $code [description]
     * @param  [type]  $data [description]
     * @return [type]        [description]
     */
    protected function ajaxReturn($msg='Success',$code=0){
        header('Content-type:text/json');
        print(json_encode(['code'=>$code,'msg'=>$msg],JSON_UNESCAPED_UNICODE));
        die;
    }
}