<?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
{

    #[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);
        $h = $this->request->getHeaders();
//        var_dump($this->request->getHeaders());
//        $a= 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJwaHBlcjY2Ni9qd3QiLCJ1aWQiOjMyLCJ1c2VyX25hbWUiOiIxIiwicm9sZV9pZCI6MSwibW9iaWxlIjoiMTU4MDEyNDU3NTUiLCJlbWFpbCI6IjVAcXEuY29tIiwicm9uZ190b2tlbiI6IiIsImxldmVsX2lkIjo4LCJqd3Rfc2NlbmUiOiJkZWZhdWx0IiwianRpIjoiZGVmYXVsdF82Njc1MjJkZDQ3YWYxMi41MTE5MjI5MiIsImlhdCI6MTcxODk1MjY2OSwibmJmIjoxNzE4OTUyNjY5LCJleHAiOjE3MjE1NDQ2Njl9.e0JW8fgNrwBdFgmQ8GNtES2ME1SbcbIih5MsQWzT6sk';
        $arr =  $jwt->getClaimsByToken($h['token'][0]);
        var_dump($h['token'][0],"+++++++++++",$arr,"===####");
        return $this->response->json(['code' => 0, 'msg' => 'success', 'data' => ['a' => 1]]);
    }
}