<?php

namespace app\controller;

use app\model\User;
use app\util\JwtUtil;
use app\util\Util;
use support\Redis;
use support\Request;

class UserController
{
    /**
     * 不需要登录的方法
     */
    protected $noNeedLogin = ['login'];

    public function login(Request $request)
    {
//        Util::isEmpty($request->post('email'));
        $email = Util::getParam($request,'email');
        if(Util::isEmpty($email)){
            return Util::fail([],'email'.trans('not_null'));
        }
//        Util::isEmpty($request->post('password'));
            $password = Util::getParam($request,'password');
        if(Util::isEmpty($password)){
            return Util::fail([],'password'.trans('not_null'));
        }
        $user = User::select(['id','name','sex','role','avatar','email','password'])
            ->where('status',0)
            ->where('email',$request->post('email'))
            ->first();
        if(!$user){
            return Util::fail(['user'=>$user],trans('user_none'));
        }
        $user = $user->toArray();

        $userPassword = $user['password'];

        //加密
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

        //验证密码
        if (!password_verify($userPassword, $hashedPassword)) {
            return Util::fail([],trans('password_error'));
        }
        $userId = $user['id']; // 实际从数据库获取


        Redis::set('user_'.$userId, $user);

        //密码验证成功后加密生成 Token
        $token = JwtUtil::generateToken($userId);
        $result = $user;
        unset($result['password']);
        $result['token'] = $token;

        return Util::success($result,trans('login_success'));
    }


}