<?php

declare (strict_types=1);
namespace App\Controller;

use Phper666\JWTAuth\JWT;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use App\Tools\Result;
use App\JsonRpc\UserServiceInterface;
/**
 * @AutoController()
 */
class LoginController extends AbstractController
{
    use \Hyperf\Di\Aop\ProxyTrait;
    use \Hyperf\Di\Aop\PropertyHandlerTrait;
    function __construct(\Hyperf\Logger\LoggerFactory $loggerFactory)
    {
        if (method_exists(parent::class, '__construct')) {
            parent::__construct(...func_get_args());
        }
        $this->__handlePropertyHandler(__CLASS__);
    }
    #[Inject]
    protected ValidatorFactoryInterface $validationFactory;
    /**
     * @var UserServiceInterface
     */
    #[Inject]
    private $userServiceClient;
    public function login(Jwt $jwt)
    {
        $this->logger->info("验证之前");
        $reqData = $this->request->all();
        $validator = $this->validationFactory->make($reqData, ['username' => 'required', 'password' => 'required', 'type' => 'required'], ['username.required' => '用户名不能为空', 'password.required' => '密码不能为空', 'type.required' => '登录方式必填']);
        if ($validator->fails()) {
            $errorMessage = $validator->errors()->first();
            return Result::error($errorMessage);
        }
        $where = [];
        if ($reqData['type'] == 1) {
            //密码登录
            $where = ['user_name' => $reqData['username']];
        }
        $this->logger->info("验证之前");
        $userInfos = $this->userServiceClient->verifyUserInfo($where);
        $this->logger->info("验证用户返回值：", $userInfos);
        if (md5(md5($reqData['password']) . $userInfos['data']['salt']) != $userInfos['data']['password']) {
            return Result::error("用户名或密码错误");
        }
        $userData = [
            'uid' => $userInfos['data']['id'],
            // 如果使用单点登录，必须存在配置文件中的sso_key的值，一般设置为用户的id
            'user_name' => $userInfos['data']['user_name'],
            'role_id' => $userInfos['data']['role_id'],
            'mobile' => $userInfos['data']['mobile'],
            'email' => $userInfos['data']['email'],
            'rong_token' => $userInfos['data']['rong_token'],
            'level_id' => $userInfos['data']['level_id'],
        ];
        // 使用默认场景登录
        $token = $jwt->getToken('default', $userData);
        $data = ['token' => $token->toString(), 'exp' => $jwt->getTTL($token->toString())];
        return Result::success($data);
    }
    # http头部必须携带token才能访问的路由
    public function getData(Jwt $jwt)
    {
        var_dump($this->UserId);
        $a = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJwaHBlcjY2Ni9qd3QiLCJ1aWQiOjEsInVzZXJuYW1lIjoieHgiLCJqd3Rfc2NlbmUiOiJkZWZhdWx0IiwianRpIjoiZGVmYXVsdF82NjYyYTg5NTQ5MTk2MS40NTgzOTUyNCIsImlhdCI6MTcxNzc0MTcxNywibmJmIjoxNzE3NzQxNzE3LCJleHAiOjE3MTc3NDg5MTd9.cTqoaSn5P3mW8__O2O2rv2dxiGtfSZk-E8fisjHFwCg';
        $arr = $jwt->getClaimsByToken($a);
        var_dump($arr, "===####");
        return $this->response->json(['code' => 0, 'msg' => 'success', 'data' => ['a' => 1]]);
    }
}