<?php

namespace crmeb\repositories;


use app\models\system\SystemBadmin;
use crmeb\exceptions\AuthException;
use crmeb\services\CacheService;
use Firebase\JWT\ExpiredException;
use Psr\SimpleCache\InvalidArgumentException;
use think\db\exception\ModelNotFoundException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\facade\Cache;
use Firebase\JWT\JWT;

/**
 * Class UserRepository
 * @package crmeb\repositories
 */
class BAdminRepository
{

    /**
     * 获取Admin授权信息
     * @param $token
     * @return array
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws InvalidArgumentException
     * @throws \think\db\exception\DbException
     */
    public static function adminParseToken($token): array
    {
        if (!$token || !CacheService::hasToken($token) || !($cacheToken = CacheService::getTokenBucket($token)))
            throw new AuthException('请登录！', 410000);

        if (isset($cacheToken['max']) && $cacheToken['max'] >= 3) {
            CacheService::clearToken($token);
            throw new AuthException('登陆过期！', 410001);
        }

        try {
            [$adminInfo, $type] = SystemBadmin::parseToken($token);
            CacheService::setTokenBucket($cacheToken['token'], $cacheToken, $cacheToken['exp']);
        } catch (ExpiredException $e) {
            list($headb64, $bodyb64, $cryptob64) = explode('.', $token);
            $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64));
            $type = $payload->jti->type;
            $adminInfo = SystemBadmin::where('id', $payload->jti->id)->find();
            if (!$adminInfo) {
                CacheService::clearToken($token);
                throw new AuthException('登陆过期！', 410001);
            }
            if (isset($cacheToken['max'])) {
                $cacheToken['max'] = bcadd($cacheToken['max'], 1, 0);
            } else {
                $cacheToken['max'] = 1;
            }
            CacheService::setTokenBucket($cacheToken['token'], $cacheToken, $cacheToken['exp']);
        } catch (\Throwable $e) {
            CacheService::clearToken($token);
            throw new AuthException('登陆过期！', 410001);
        }

        if (!isset($adminInfo) || !$adminInfo || !$adminInfo->id || $type != "badmin") {
            CacheService::clearToken($token);
            throw new AuthException('登录状态异常，请重新登录！', 410002);
        }
        $adminInfo->type = $type;
        return $adminInfo->toArray();

    }
}