<?php
/**
 * Created by PhpStorm.
 * User: 中闽 < 1464674022@qq.com >
 * Date: 2019/12/5
 * Time: 17:44
 */

namespace app\admin\controller\base;

use app\admin\model\Urlconfig;
use app\common\behavior\AdminLogBehavior;
use app\common\service\WebService;
use think\Controller;
use think\Db;
use think\Hook;
use think\Session;

class Permissions extends Controller
{
    const ADMIN_ID = 'admin';
    const ADMIN_NAME = 'admin_name';
    const ADMIN_CATE_ID = 'admin_cate_id';

    protected function _initialize()
    {
        (new WebService())->checkInstalled();

        Hook::listen('admin_log');

        if ($this->request->isCli()) {
            return;
        }

        //检查ip黑名单
        $black_ip = \app\common\model\Webconfig::getValue('black_ip', 3600);
        if (!empty($black_ip)) {
            $black_ip = explode(',', $black_ip);
            $ip = $this->request->ip();
            if (in_array($ip, $black_ip)) {
                //退出登录
                if (Session::has(self::ADMIN_ID)) {
                    Session::delete(self::ADMIN_ID);
                }
                $this->error('你已被封禁！', 'admin/common/login');
            }
        }

        //检查是否登录
        if (!Session::has(self::ADMIN_ID)) {
            if ((new Urlconfig())->isWeekBackend()) {
                $this->redirect('admin/common/login');
            } else {
                abort(404, '404 not found');
            }
        }

        //检查访问的url是否再用户的权限范围内,mysql查询自动忽略了大小写
        $where['module'] = $this->request->module();
        $where['controller'] = $this->request->controller();
        $where['function'] = $this->request->action();
        $where['type'] = 1;//权限节点

        //用户的权限菜单id
        $menus = Db::name('admin_cate')->where('id', Session::get(self::ADMIN_CATE_ID))->value('permissions');
        $menus = explode(',', $menus);

        $string = $this->request->query();
        $param_menu = Db::name('admin_menu')->where($where)->where('parameter', $string)->find();
        if ($param_menu) {
            if (false == in_array($param_menu['id'], $menus)) {
                (new AdminLogBehavior())->updateLastLog("缺少权限");
                $this->error('缺少权限');
            }
        } else if ($string) {
            $menu = Db::name('admin_menu')->where($where)->where('parameter', '')->find();
            if ($menu && !in_array($menu['id'], $menus)) {
                (new AdminLogBehavior())->updateLastLog("缺少权限");
                $this->error('缺少权限');
            }
        }
        if ($this->request->has('check_permission')) {
            $this->success('has permission');
        }
    }

    /**
     * 查询当前用户权限
     * @return array|mixed 菜单id数组
     */
    public function getPermission()
    {
        //用户的权限菜单id
        $menus = Db::name('admin_cate')->where('id', Session::get(self::ADMIN_CATE_ID))->value('permissions');
        $menus = explode(',', $menus);
        return $menus;
    }
}
