<?php
declare (strict_types = 1);

namespace app\admin\controller;

use think\App;
use think\exception\ValidateException;
use think\Validate;
use think\Controller;
use think\facade\Request;
use util\RedisUtil;
/**
 * 控制器基础类
 */
abstract class AdminBase
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;
    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;
    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;
    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];
    // 当前用户的ID
    public $userId     = 0;
    // 当前用户的手机号
    public $mobile     = '';
    // 上级代理商
    public $adminId    = 0;
    // token
    public $token      = null;
    /**
     * 设置无需登陆的action
     * 格式：[
     *     '控制器名称(驼峰)' => ['action1', 'action2', ...],
     *     ...
     * ]
     */
    protected $noLogin = [
        'Index'     => ['welcome'],
        'Login'     => ['index', 'info', 'verify'],
    ];
    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app     = $app;
        $this->request = $this->app->request;

        // 控制器初始化
        $this->initialize();
    }

    // 初始化
    public function initialize()
    {
        $this->token   = $this->request->header('Access-Token', '');//['Access-Token'];
        $this->adminId = input('aid','');
        // 根据token获取用户的数据
        if(!$this->adminId || $this->token) {
            // 获取当前用户数据
            $adminData = $this->token ? RedisUtil::getAdminToken($this->token) : [];
            // 当前用户的ID
            if(empty($adminData) || !$adminData['aid'] || $adminData['role'] !== '1'){
                $this->adminId = '';
            }
            $this->adminId = isset($adminData['aid']) ? $adminData['aid'] : '';
        }
        /**
         * @var string $controller 当前控制器
         * @var string $action 当前方法(action)
         */
        $controller = Request::controller();
        $action     = Request::action();
        // 验证用户是否登录，排除无需登录的action
        if (!(isset($this->noLogin[$controller]) && in_array($action, $this->noLogin[$controller]))) {
            if ($this->adminId == '') {
                if(php_sapi_name() == 'cli'){
                    //echo json_encode(['aid' => $this->adminId, 'status' => 200, 'msg' => '请登陆'],JSON_UNESCAPED_UNICODE);
                    return false;
                }else{
                    echo json_encode(['aid' => $this->adminId, 'status' => 200, 'msg' => '请登陆'],JSON_UNESCAPED_UNICODE);
                    exit;
                }
            }
        }
    }

    /**
     * 验证数据
     * @access protected
     * @param  array        $data     数据
     * @param  string|array $validate 验证器名或者验证规则数组
     * @param  array        $message  提示信息
     * @param  bool         $batch    是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v     = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }
        $v->message($message);
        
        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }
        return $v->failException(true)->check($data);
    }

}
