<?php
/**
 *
 * @author：llbjj
 * @DateTime：2022/5/4 13:42
 * @Description：登录
 *
 */

namespace Application\Controller;

use Application\Common\Container;
use Application\Common\RedisEnum;
use Application\Common\StatusCode;
use Application\Form\LoginForm;
use Application\Mvc\Controller\Plugins\RenderApiJson;
use Application\Service\Extension\Helper\StringHelper;
use Application\Service\Extension\Identity\Identity;
use Application\Service\Extension\Laminas;
use Application\Service\Extension\Sms\SmsRateLimitException;
use Application\Service\Extension\Validator\ValidatorApplication;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Laminas\Db\Sql\Where;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Mvc\Exception\InvalidArgumentException;
use Laminas\View\Model\JsonModel;
use Laminas\View\Model\ViewModel;
use Overtrue\Socialite\Exceptions\AuthorizeFailedException;
use Overtrue\Socialite\User;

/**
 * Class LoginController
 * @package Application\Controller
 * @method Container LocalService()
 * @method RenderApiJson RenderApiJson()
 */
class LoginController extends AbstractActionController
{
    /**
     * @note 账户密码登录
     * @return JsonModel
     */
    public function accountPwdAction() : JsonModel
    {
        return $this->RenderApiJson()->Success($this->LocalService()->loginClient->accoutPwd->login());
    }

    /**
     * 获取扫码登陆登录二维码地址
     * @doc https://www.showdoc.com.cn/1936668638131821/8824484392761392
     * @url GET http://xx.com/login-code
     * @return JsonModel
     */
    public function loginCodeAction(): JsonModel
    {
        $model = new LoginForm();

        // 获取登录网址
        $wechatConfig = $this->getEvent()->getApplication()->getConfig()['wechat'];

        $code = StringHelper::generateHashValue();

        $info = $model->getLoginInfo($code);

        $this->LocalService()->redisExtend->getRedisInstance()->setex(RedisEnum::TMP_CODE . $code, 180, $info);

        return $this->RenderApiJson()->Success([
            'url' => strtr(
                $wechatConfig['forward_code_url'],
                ['{auk}' => $wechatConfig['forward_auk'], '{state}' => $code]
            ),
            'code' => $code
        ]);
    }

    /**
     * v2版本获取扫码登陆二维码
     * @url GET http://xx.com/v2/login-code
     * @return JsonModel
     */
    public function loginCodeV2Action(): JsonModel
    {
        $model = new LoginForm();

        $code = StringHelper::generateHashValue();

        $info = $model->getLoginInfo($code);

        $this->LocalService()->redisExtend->getRedisInstance()->setex(RedisEnum::TMP_CODE . $code, 180, $info);

        $host = "{$_SERVER['REQUEST_SCHEME']}://{$_SERVER['HTTP_HOST']}";

        if ($_SERVER['HTTP_HOST'] === 'local.kingdone.com') {
            $host = 'https://esm.kingdone.com';
        }

        return $this->RenderApiJson()->Success([
            'url' => "{$host}/oauth?code={$code}",
            'code' => $code
        ]);
    }

    public function oAuthAction(): ViewModel
    {
        // 获取登录网址
        $wechatConfig = $this->getEvent()->getApplication()->getConfig()['wechat'];

        $code = $_GET['code'];
        if (!$code) {
            return $this->RenderApiJson()->Error(StatusCode::E_LOGIN_CODE_EXPIRE, '无效的二维码');
        }

        $view = new ViewModel();
        $view->setTemplate('application/login/auth');
        $view->setTerminal(true);
        $view->setVariables([
            'authUrl' => strtr(
                $wechatConfig['forward_code_url'],
                ['{auk}' => $wechatConfig['forward_auk'], '{state}' => $code]
            )
        ]);

        return $view;
    }

    /**
     * 用户是否已经扫码登录
     * @doc https://www.showdoc.com.cn/p/7b784fee3c5be975d574144dc02836fc
     * @url POST http://xx.com/is-scan
     * @return JsonModel
     */
    public function isScanAction(): JsonModel
    {
        // 验证是否登录成功
        $code = $this->getRequest()->getPost()->get('code');
        $redis = $this->LocalService()->redisExtend->getRedisInstance();

        // 判断code 是否过期
        if (!$redis->get(RedisEnum::TMP_CODE . $code)) {
            return $this->RenderApiJson()->Error(StatusCode::E_LOGIN_CODE_EXPIRE, '二维码已过期，请刷新后重试');
        }

        // 检查用户状态, 是否绑定微信
        $statusKey = RedisEnum::USER_STATUS . $code;
        $info = $redis->get($statusKey);
        if (!$info) {
            return $this->RenderApiJson()->Error(StatusCode::E_RUNTIME, '未发现用户扫码');
        }

        $info = json_decode($info, true);
        if (!isset($info['bind_status'])) {
            return $this->RenderApiJson()->Error(StatusCode::E_RUNTIME, '获取用户信息失败');
        }

        // 未绑定和已绑定的用户返回信息做一下处理
        if ($info['bind_status'] == -1) {
            return $this->RenderApiJson()->Success([
                'bind_status' => -1,
                'bind_code' => $code
            ]);
        } else {
            $redis->del($statusKey);

            if (isset($info['group']) && $info['group'] == 2) {
                return $this->RenderApiJson()->Success($info, 'OK', [
                    'auth' => $this->LocalService()->identity->generateTokenByUserId($info['id'], Identity::PLATFORM_REAL)
                ]);
            }

            return $this->RenderApiJson()->Success($info);
        }
    }

    /**
     * @return \Laminas\Http\Response
     */
    public function forwardAction(): \Laminas\Http\Response
    {
        $auk = $this->params()->fromQuery('auk', '');
        $scan_code = $this->params()->fromQuery('state');

        $wechatConfig = $this->LocalService()->config['wechat'];
        $callBackUrl = "{$wechatConfig['forward_callback_url']}?auk={$auk}&scan_code={$scan_code}";
        $redirectUrl = $this->LocalService()->wechat->getApp()
            ->oauth
            ->scopes(['snsapi_userinfo'])->with(['forceSnapShot' => true])
            ->redirect($callBackUrl);
        return $this->redirect()->toUrl($redirectUrl);
//        die;
    }

    /**
     * 微信扫码回调
     * @throws GuzzleException
     * @throws AuthorizeFailedException
     */
    public function callbackAction()
    {
        $auk = $this->params()->fromQuery('auk', '');
        $code = $this->params()->fromQuery('code', '');
        $scan_code = $this->params()->fromQuery('scan_code', '');

        if($auk !== ''){
            $callBackUrl = $this->LocalService()->config['wechatRedirectUrlConfig'][$auk];
            return $this->redirect()->toUrl($callBackUrl.'?code='.$code.'&scan_code='.$scan_code);
        }else{
            // 微信配置信息
            $wechatConfig = $this->LocalService()->config['wechat'];

            if($wechatConfig['open_forward']){
                // 获取微信用户信息
                $user = $this->LocalService()->httpSv->post($wechatConfig['forward_user_url'], ['code'=>$code]);
                $user = new User($user);
            }else{
                $user = $this->LocalService()->wechat->getApp()->oauth->userFromCode($code);
            }

            $model = new LoginForm();
            $model->code = $scan_code;
            $status = $model->setCallback($user);

            if ($status['bind_status'] == -1) {
                include __DIR__ . '/../../view/application/login/bind.phtml';
            }else{
                include __DIR__ . '/../../view/application/login/success.phtml';
            }
            die;
        }
    }

    /**
     * Notes: 通过code值获取wechat用户信息
     * User: llbjj
     * DateTime: 2022/7/26 13:46
     *
     */
    public function wechatuserAction(): JsonModel
    {
        $code = $this->params()->fromPost('code');
        $scopes = $this->params()->fromPost('scopes', 'snsapi_userinfo');
        $user = $this->LocalService()->wechat->getApp()->oauth->scopes([$scopes])->userFromCode($code);
        $userData = [
            'id' => $user->getId(),
            'nickname' => $user->getNickname(),
            'avatar' => $user->getAvatar(),
            'openid' => $user->getId(),
        ];
        return $this->RenderApiJson()->Success($userData);
    }

    /**
     * 发送短信
     * @doc https://www.showdoc.com.cn/p/020e03537a97fb3c19c8871d60a2427a
     * @url POST http://xx.com/send-sms
     * @return JsonModel
     * @throws Exception
     */
    public function sendSmsAction(): JsonModel
    {
        $mobile = $this->params()->fromPost('mobile');

        if (!Laminas::$serviceManager->adminUser->fetchOne(['where' => ['mobile' => $this->params()->fromPost('mobile'), 'is_del' => 0]])) {
            throw new InvalidArgumentException("没有匹配的账户信息，请联系客服后重试!", StatusCode::E_FIELD_VALIDATOR['code']);
        }

        $redis = Laminas::$serviceManager->redisExtend->getRedisInstance();
        $limitKey = RedisEnum::SMS_LIMIT . $mobile;

        // 验证发送速率
        if ($redis->get($limitKey)) {
            throw new SmsRateLimitException("短信发送频繁, 60秒内只能发送一次。");
        }

        $response = $this->LocalService()->sms->send($mobile);
        if ($response['error'] != 0) {
            throw new InvalidArgumentException("验证码发送失败", StatusCode::E_FIELD_VALIDATOR['code']);
        }
        $this->LocalService()->redisExtend->getRedisInstance()->setex(RedisEnum::SMS . $mobile, 60 * 5, $response['code']);

        // 设置请求速率key
        $redis->setex(RedisEnum::SMS_LIMIT . $mobile, 60, 1);

        return $this->RenderApiJson()->Success();
    }

    public function h5SendSmsAction(): JsonModel
    {
        $mobile = $this->params()->fromPost('mobile');

        $redis = Laminas::$serviceManager->redisExtend->getRedisInstance();
        $limitKey = RedisEnum::SMS_LIMIT . $mobile;

        // 验证发送速率
        if ($redis->get($limitKey)) {
            throw new SmsRateLimitException("短信发送频繁, 60秒内只能发送一次。");
        }

        // 验证手机号是否是受试者用户
        $adminUser = $this->LocalService()->adminUser->fetchOne([
            'where' => ['is_del' => 0, 'mobile' => $mobile, 'patient_status' => 0],
            'columns' => ['id', 'patient_openid']
        ]);

        if(empty($adminUser)) return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '用户不存在，请联系相关客服！');
        if(!empty($adminUser['patient_openid'])) return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '请勿重复绑定！');

        $response = $this->LocalService()->sms->send($mobile);
        if ($response['error'] != 0) {
            throw new InvalidArgumentException("验证码发送失败", StatusCode::E_FIELD_VALIDATOR['code']);
        }
        $this->LocalService()->redisExtend->getRedisInstance()->setex(RedisEnum::SMS . $mobile, 60 * 5, $response['code']);

        // 设置请求速率key
        $redis->setex(RedisEnum::SMS_LIMIT . $mobile, 60, 1);

        return $this->RenderApiJson()->Success();
    }

    /**
     * @note 发送登录验证码（账户登录使用）
     * @return JsonModel
     * @throws \RedisException
     */
    public function sendLoginSmsAction(): JsonModel
    {
        $mobile = $this->params()->fromPost('mobile');

        if(empty($mobile)) {
            throw new InvalidArgumentException("手机号不能为空！");
        }

        $redis = Laminas::$serviceManager->redisExtend->getRedisInstance();
        $limitKey = RedisEnum::SMS_LIMIT . $mobile;

        // 验证发送速率
        if ($redis->get($limitKey)) {
            throw new SmsRateLimitException("短信发送频繁, 60秒内只能发送一次。");
        }

        // 验证手机号是否是受试者用户
        $adminUser = $this->LocalService()->adminUser->fetchOne([
            'where' => [
                'is_del' => 0,
                'mobile' => $mobile,
                'or' => [
                    'real_status' => 0,
                    'status' => 0,
                ],
            ],
            'columns' => ['id']
        ]);

        if(empty($adminUser)) return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '用户不存在，请联系相关客服！');

        $response = $this->LocalService()->sms->send($mobile);
        if ($response['error'] != 0) {
            throw new InvalidArgumentException("验证码发送失败", StatusCode::E_FIELD_VALIDATOR['code']);
        }
        $this->LocalService()->redisExtend->setDatabase(6)->getRedisInstance()->setex(RedisEnum::SMS_LOGIN . $mobile, 60 * 5, $response['code']);

        // 设置请求速率key
        $redis->setex(RedisEnum::SMS_LIMIT . $mobile, 60, 1);

        return $this->RenderApiJson()->Success();
    }

    /**
     * 绑定用户
     * @doc https://www.showdoc.com.cn/p/9bdf32451aed20b9120fbe047427691b
     * @url POST http://xx.com/bind
     * @throws Exception
     */
    public function bindAction(): JsonModel
    {
        $validator = new ValidatorApplication();

        $mobile = $this->params()->fromPost('mobile');
        // 验证短信验证码
        $code = $this->LocalService()->redisExtend->getRedisInstance()->get(RedisEnum::SMS . $validator->attributes['mobile']);
        if (!$code || $code != $this->params()->fromPost('checkcode')) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, "验证码有误");
        }

        $callbackInfo = $this->LocalService()->redisExtend->getRedisInstance()->get(RedisEnum::USER_STATUS . $validator->attributes['bind_code']);
        // 如果扫完码超过了一个小时还没进行绑定操作, key已经过期了
        if (!$callbackInfo) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, "已绑定或绑定超时。");
        }

        $callbackInfo = json_decode($callbackInfo, true);
        // 更新对应用户的信息
        $this->LocalService()->adminUser->update([
            'avatar' => $callbackInfo['avatar'],
            'nickname' => $callbackInfo['nickname'],
            'openid' => $callbackInfo['openid'],
        ], ['mobile' => $validator->attributes['mobile']]);

        // 获取用户信息
        $user = $this->LocalService()->adminUser->fetchOne([
            'where' => ['mobile' => $validator->attributes['mobile'], 'is_del' => 0]
        ]);

        $this->LocalService()->redisExtend->getRedisInstance()->del(RedisEnum::USER_STATUS . $validator->attributes['bind_code']);
        return $this->RenderApiJson()->Success($this->LocalService()->identity->getLoginInfo($user['id']));
    }

    /**
     * 登出
     * @doc https://www.showdoc.com.cn/p/fdd7b478543cdbcd19c64f9443dd2a73
     * @url GET http://xx.com/logout
     * @return JsonModel
     */
    public function logoutAction(): JsonModel
    {
        $this->LocalService()->identity->disCard();
        return $this->RenderApiJson()->Success();
    }

    /**
     * 小程序登录
     * @doc https://www.showdoc.com.cn/p/b89babadc4ef3ebc46910f8605355ef8
     * @url GET http://xx.com/mini-login
     * @return JsonModel
     * @throws GuzzleException|InvalidConfigException|Exception
     */
    public function miniLoginAction(): JsonModel
    {
        // 获取手机号code
        $code = $this->params()->fromPost('code');

        // 获取openid code, 目前没用了
        $sessionCode = $this->params()->fromPost('session_code');

        $platform = $this->params()->fromPost('platform');

        $phoneResponse = $this->LocalService()->wechat->getMiniApp($platform)->phone_number->getUserPhoneNumber($code);

        if ($phoneResponse['errmsg'] != 'ok') {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '微信授权失败');
        }

        if (!isset($phoneResponse['phone_info']['purePhoneNumber'])) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '获取手机号失败!');
        }

        $data = $this->LocalService()->identity->generateTokenByMobile(
            $phoneResponse['phone_info']['purePhoneNumber'],
            Identity::PLATFORM_MINI_PROGRAM
        );

        if (count($data) !== count($data, COUNT_RECURSIVE) && count($data) > 1) {
            return $this->RenderApiJson()->Success([], 'OK', ['auth' => $data]);
        } else {
            return $this->RenderApiJson()->Success(
                current($data)
            );
        }
    }

    public function patientH5OauthAction() {
        $code = $this->params()->fromPost('code', '');  // 微信Code值，用于获取openid
        $type = $this->params()->fromPost('type', 'default');
        if( empty($code) ) return $this->RenderApiJson($type)->Success([
            'status' => 1,
            'msg' => '非法登录！'
        ]);

        // 获取微信公众号用户信息
        $wechatUserInfo = $this->LocalService()->wechat->getPatientH5App($type)->oauth->scopes(['snsapi_base'])->userFromCode($code);
        if( empty($wechatUserInfo->getId()) ) return $this->RenderApiJson()->Success([
            'status' => 1,
            'msg' => '公众号授权失败!'
        ]);

        // 查询微信公众号openid对应的用户信息
        $adminUser = $this->LocalService()->adminUser->fetchOne([
            'where' => [
                'is_del' => 0,
                'patient_openid' => $wechatUserInfo->getId()
            ],
            'columns' => [ 'id', 'mobile', 'patient_status']
        ]);

        if( empty($adminUser) ) return $this->RenderApiJson()->Success([
            'status' => 2,
            'msg' => '账户未绑定！',
            'openid' => $wechatUserInfo->getId()
        ]);
        if( !empty($adminUser['patient_status']) ) return $this->RenderApiJson()->Success([
            'status' => 1,
            'msg' => '账户已禁用，请联系相关客服人员！'
        ]);

        // 受试者登录
        $authData = $this->LocalService()->identity->generateTokenByUserId($adminUser['id'], Identity::PLATFORM_H5_PROGRAM_PATIENT);

        return $this->RenderApiJson()->Success([
            'token' => $authData['token'],
            'status' => 0
        ]);
    }

    public function h5BindAction()
    {
        $openid = $_POST['openid'];
        $smsCode = $_POST['sms_code'];
        $mobile = $_POST['mobile'];
        $type = $_POST['type'];

        // 验证短信验证码
        $smsCodeVal = $this->LocalService()->redisExtend->setDatabase(6)->getRedisInstance()->get(RedisEnum::SMS . $mobile);
        if (!$smsCodeVal || $smsCodeVal != $smsCode) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, "验证码有误");
        }

        $adminUser = $this->LocalService()->adminUser->fetchOne([
            'where' => ['is_del' => 0, 'mobile' => $mobile, 'patient_status' => 0],
            'columns' => ['id', 'patient_openid']
        ]);

        if(empty($adminUser)) return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '用户不存在，请联系相关客服人员！');

        if (!empty($adminUser['patient_openid'])) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, "请勿重复绑定。");
        }

        $wechatUserInfo = $this->LocalService()->wechat->getPatientH5App($type)->user->get($openid);
        if (empty($wechatUserInfo['openid'] ?? '')) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, "获取用户信息失败，请重试。");
        }

        // 更新受试者用户的openid
        Laminas::$serviceManager->adminUser->updateField($adminUser['id'], 'patient_openid', $openid);

        // 授权登录
        $authData = $this->LocalService()->identity->generateTokenByUserId($adminUser['id'], Identity::PLATFORM_H5_PROGRAM_PATIENT);

        return $this->RenderApiJson()->Success(['token' => $authData['token']]);
    }

    public function getwebsitefilingAction(): JsonModel
    {
        return $this->RenderApiJson()->Success($this->LocalService()->adminWebsitefiling->getCurrentWebsiteFiling());
    }


    public function indexAction(){
        $viewModel = new ViewModel();
        $viewModel->setTerminal(true);
        return $viewModel;

    }

    public function patientH5Action() {
        $time = $this->params()->fromQuery('date', '');
        $type = $this->params()->fromQuery('type', 'default');

        $sendUrl = $this->LocalService()->config['sendUrl'];
        $sendUrl .= '/#/patientH5?type='.$type;
        if($time) $sendUrl .= '&date=' . $time;
        $redirectUrl = rawurlencode($sendUrl);

        $appid = $this->LocalService()->wechat->getPatientH5App($type)->getConfig()['app_id'];

        return $this->redirect()->toUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirectUrl}&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect");
    }

    /**
     * @note webH5 静默授权登录
     * @return \Laminas\Http\Response
     */
    public function webH5Action(): \Laminas\Http\Response
    {
        $wechatH5Config = $this->LocalService()->config['wechat']['h5Proxy'];
        // 开启代理
        if($wechatH5Config['open_forward']) {
            return $this->redirect()->toUrl(strtr(
                $wechatH5Config['forward_code_url'],
                ['{auk}' => $wechatH5Config['forward_auk']]
            ));
        }

        $sendUrl = $this->LocalService()->config['sendUrl'];
        $sendUrl .= '/#/webH5';

        if(!empty($this->params()->fromQuery())) $sendUrl .= "?" . http_build_query($this->params()->fromQuery());


        return $this->redirect()->toUrl(
            $this->LocalService()->wechat->getApp()
                ->oauth
                ->scopes(['snsapi_base'])
                ->with(['forceSnapShot' => true])
                ->redirect($sendUrl)
        );
    }

    /**
     * @note webH5 代理
     * @return \Laminas\Http\Response
     */
    public function webH5ForwardAction(): \Laminas\Http\Response
    {
        $wechatH5Config = $this->LocalService()->config['wechat']['h5Proxy'];

        return $this->redirect()->toUrl(
            $this->LocalService()->wechat->getApp()
                ->oauth
                ->scopes(['snsapi_base'])
                ->with(['forceSnapShot' => true])
                ->redirect(
                    $wechatH5Config['forward_callback_url'] . "?". http_build_query($this->params()->fromQuery())
                )
        );
    }

    /**
     * @note webH5 代理回调
     * @return \Laminas\Http\Response
     */
    public function webH5CallbackAction(): \Laminas\Http\Response
    {
        $auk = $this->params()->fromQuery('auk', '');
        $code = $this->params()->fromQuery('code', '');

        return $this->redirect()->toUrl(
            $this->LocalService()->config['wechatH5RedirectUrlConfig'][$auk] . "?code=" . $code
        );
    }

    public function webH5OauthAction() {
        $code = $this->params()->fromPost('code', '');  // 微信Code值，用于获取openid
        if( empty($code) ) return $this->RenderApiJson()->Success([
            'status' => 1,
            'msg' => '非法登录！'
        ]);

        // 获取微信公众号用户信息
        $wechatH5Config = $this->LocalService()->config['wechat']['h5Proxy'];
        // 开启代理
        if($wechatH5Config['open_forward']) {
            // 获取微信用户信息
            $wechatUserInfo = $this->LocalService()->httpSv->post(
                $this->LocalService()->config['wechat']['forward_user_url'],
                [
                    'code'=>$code,
                    'scopes' => 'snsapi_base'
                ]
            );
            $wechatUserInfo = new User($wechatUserInfo);
        }else {
            $wechatUserInfo = $this->LocalService()->wechat->getApp()->oauth->scopes(['snsapi_base'])->userFromCode($code);
        }

        if( empty($wechatUserInfo->getId()) ) return $this->RenderApiJson()->Success([
            'status' => 1,
            'msg' => '公众号授权失败!'
        ]);

        // 查询微信公众号openid对应的用户信息
        $adminUser = $this->LocalService()->adminUser->fetchOne([
            'where' => [
                'is_del' => 0,
                'openid' => $wechatUserInfo->getId()
            ],
            'columns' => [ 'id', 'mobile', 'status', 'real_status']
        ]);

        if( empty($adminUser) ) {
            // 插入用户状态, 3600秒生存时间, 防止扫完码不取数据一直占用内存
            Laminas::$serviceManager->redisExtend->getRedisInstance()->setex(RedisEnum::USER_STATUS . $code, 60 * 60 , json_encode([
                'bind_status' => -1,
                'nickname' => $wechatUserInfo->getNickname(),
                'avatar' => $wechatUserInfo->getAvatar(),
                'openid' => $wechatUserInfo->getId(),
            ]));
            return $this->RenderApiJson()->Success([
                'status' => 2,
                'msg' => '账户未绑定！',
                'openid' => $wechatUserInfo->getId()
            ]);
        }

        if( !empty($adminUser['status']) && !empty($adminUser['real_status']) ) return $this->RenderApiJson()->Success([
            'status' => 1,
            'msg' => '账户已禁用，请联系相关客服人员！'
        ]);

        // 受试者登录
        $authData = $this->LocalService()->identity->generateTokenByUserId($adminUser['id'], Identity::PLATFORM_H5_WEB);

        return $this->RenderApiJson()->Success([
            'token' => $authData['token'],
            'status' => 0
        ]);
    }
}