<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/22
 * Time: 17:00
 */

namespace app\index\behavior;

use think\Request;
use think\Controller;

class Addons extends Controller
{
    /**
     * 插件路由访问
     * @param Request $request
     * @return mixed
     */
    public function run(Request $request)
    {
        // 是否自动转换控制器和操作名
        $convert = config('url_convert');
        $filter = $convert ? 'strtolower' : '';
        // 处理路由参数
        $addon = $request->param('addon', '', $filter);
        $controller = $request->param('controller', 'index', $filter);
        $action = $request->param('action', 'index', $filter);
        if (!empty($addon) && !empty($controller) && !empty($action)) {
            // 设置当前请求的控制器、操作
            $request->setController($controller)->setAction($action);
            if ($this->check()) {
                // 获取类的命名空间
                $class = get_addon_class($addon, 'controller', $controller);
                if (class_exists($class)) {
                    $model = new $class();
                    // 调用操作
                    if (!method_exists($model, $action)) {
                        abort(500, '控制器不存在');
                    }
                    return call_user_func_array([$model, $action], [$request]);
                } else {
                    abort(500, '控制器不存在');
                }
            }
        }
    }

    /**
     * 插件检测
     */
    private function check($name = '')
    {
        $roles = ['user', 'admin'];
        if (in_array(\request()->controller(), $roles)) {
            $_controller = \request()->controller();
            if (empty(session($_controller))) {
                if ($_controller == 'admin') die(json_encode(['code' => 1000, 'msg' => '请登录...']));
                $this->redirect($_controller . '/index/login');
            }
        }
        return true;
    }

}