<?php


namespace app\adminapi\middleware;


use app\models\merchant\Merchant;
use app\Request;
use crmeb\exceptions\AuthException;
use crmeb\interfaces\MiddlewareInterface;
use crmeb\repositories\AdminRepository;
use crmeb\services\CacheService;
use think\facade\Config;

class AdminAuthTokenMiddleware implements MiddlewareInterface
{
    public function handle(Request $request, \Closure $next)
    {
        $authInfo = null;
        $token = trim(ltrim($request->header(Config::get('cookie.token_name', 'Authori-zation')), 'Bearer'));
        $md_u = strtolower(trim(ltrim($request->header(Config::get('cookie.md5_url', 'Ex-U')), 'KiToken')));
        // $md_u = 'e81c1f5749545c5f7d247b3a100ffe62';
        $mer = Merchant::where('local_md5', $md_u)->find();
        if (!$mer) {
            throw new AuthException('访问异常');
        }

        $adminInfo = AdminRepository::adminParseToken($token);

        if ($adminInfo['mer_id'] == 0) {
            $mer_id = $mer['id'];
        } else {
            if (in_array($mer['id'], explode(',', $adminInfo['mer_id']))) {
                $mer_id = $mer['id'];
            } else {
                CacheService::clearToken($token);
                throw new AuthException('账号异常，请重新登录', 410000);
            }
        }

        Request::macro('isAdminLogin', function () use (&$adminInfo) {
            return !is_null($adminInfo);
        });
        Request::macro('adminId', function () use (&$adminInfo) {
            return $adminInfo['id'];
        });

        Request::macro('adminInfo', function () use (&$adminInfo) {
            return $adminInfo;
        });

        Request::macro('mer_id', function () use (&$mer_id) {
            return $mer_id;
        });

        return $next($request);
    }
}