<?php


namespace app\http\middleware;


use app\models\store\StoreOrder;
use app\models\user\User;
use app\models\user\UserToken;
use app\Request;
use crmeb\exceptions\AuthException;
use crmeb\interfaces\MiddlewareInterface;
use crmeb\repositories\UserRepository;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\db\exception\DbException;

/**
 * token验证中间件
 * Class AuthTokenMiddleware
 * @package app\http\middleware
 */
class AuthTokenMiddleware implements MiddlewareInterface
{
    public function handle(Request $request, \Closure $next, bool $force = true)
    {
        $request->filter(['htmlspecialchars', 'strip_tags', 'addslashes', 'trim']);
        $authInfo = null;
        $token = trim(ltrim($request->header('Authori-zation'), 'Bearer'));
        if (!$token) $token = trim(ltrim($request->header('Authorization'), 'Bearer'));//正式版,删除此行,某些服务器无法获取到token调整为 Authori-zation
        try {
            $authInfo = UserRepository::parseToken($token);
            if (!is_null($authInfo)) {
//                $sub_uid = $request->header('UID', 0);
//                if ($authInfo['user']['main_uid'] == 0) {
//                    $check = function ($item) use ($authInfo) {
//                        return User::getUserInfo($item)['main_uid'] == $authInfo['user']['uid'] || User::getUserInfo($item)['uid'] == $authInfo['user']['uid'];
//                    };
//                } else {
//                    $check = function ($item) use ($authInfo) {
//                        return (User::getUserInfo($item)['main_uid'] == $authInfo['user']['main_uid']) || User::getUserInfo($item)['uid'] == $authInfo['user']['main_uid'];
//                    };
//                }
//                if ($sub_uid) {
//                    if ($check($sub_uid)) {
//                        $authInfo['user'] = User::where('uid', $sub_uid)->find();
//                    }
//                    $main_user = User::getUserInfo($authInfo['user']['main_uid'] ?: $authInfo['user']['uid']);
//                    if ($main_user['real_check'] == 1) {
//                        $authInfo['user']['real_check'] = 1;
//                        $authInfo['user']['real_name'] = $main_user['real_name'];
//                        $authInfo['user']['card_id'] = $main_user['card_id'];
//                    }
//                }
                if (!$authInfo['user']['real_check'] && !in_array($request->action(), ['realNameCheck', 'logout', 'user', 'userinfo', 'upload_image', 'image'])) {
                    throw new AuthException('请先进行实名认证');
                }
                if (!$authInfo['user']->is_promoter) {
                    $price = StoreOrder::where(['paid' => 1, 'refund_status' => 0, 'uid' => $authInfo['user']['uid']])->sum('pay_price');
                    $status = is_brokerage_statu($price);
                } else {
                    $status = false;
                }
                User::edit(['is_promoter' => $status ? 1 : $authInfo['user']->is_promoter], $authInfo['user']['uid'], 'uid');
                $authInfo['user']->is_promoter = $status ? 1 : $authInfo['user']->is_promoter;
            }
        } catch (AuthException $e) {
            if ($force)
                return app('json')->make($e->getCode(), $e->getMessage());
        }
        if (!is_null($authInfo)) {
            Request::macro('user', function () use (&$authInfo) {
                return $authInfo['user'];
            });
            Request::macro('tokenData', function () use (&$authInfo) {
                return $authInfo['tokenData'];
            });
        }
        Request::macro('isLogin', function () use (&$authInfo) {
            return !is_null($authInfo);
        });
        Request::macro('uid', function () use (&$authInfo) {
            return is_null($authInfo) ? 0 : $authInfo['user']->uid;
        });
        Request::macro('isReal', function () use (&$authInfo) {
            return !is_null($authInfo) ? 0 : $authInfo['user']->real_check;
        });
        return $next($request);
    }
}