<?php

namespace app\admin;

use app\BaseController;
use app\common\model\AdminModel;
use app\common\model\MenuModel;
use think\facade\Session;
use think\facade\View;

/**
 * 控制器基础类
 */
class AdminBaseController extends BaseController
{
    // 初始化
    protected function initialize()
    {
        // 验证登陆信息
        $access_admin = session('access_admin');
        if (!$access_admin) {
            $this->adminReturn('请重新登录');
        }

        // 验证权限
        if ($access_admin['role'] != AdminModel::ROLE_SUPER && $this->request->controller() != 'Home') {
            $url   = mb_strtolower($this->request->controller() . '/' . $this->request->action());
            $check = MenuModel::where('urlstr', $url)->find();
            if (!empty($check)) {
                $url_ids = explode(',',$access_admin['powerids']);
                if (!in_array($check['id'],$url_ids)) {
                    $this->adminReturn('您没有访问权限');
                }
                if ($check['status'] == MenuModel::STATUS_DISABLE) {
                    $this->adminReturn('您没有访问权限');
                }
            }
        }

        $lay        = mb_strtolower($this->request->controller()) . '-' . $this->request->action();
        $lay_table  = "lay-{$lay}-table";
        $lay_btn    = "lay-{$lay}-btn";
        View::assign([
            'lay_table'  => $lay_table,
            'lay_btn'    => $lay_btn,
        ]);
    }

    /**
     * 返回
     */
    protected function adminReturn($msg)
    {
        if ($this->request->isAjax()) {
            ajax_return(1001, $msg);
        } else {
            $content  = '<script language="javascript" type="text/javascript"> top.location.href="/admin/login/index"; </script>';
            $response = \think\Response::create($content);
            throw new \think\exception\HttpResponseException($response);
        }
    }
}
