<?php
declare (strict_types = 1);

namespace app\admin\controller\v1;

use app\admin\exception\InvalidLoginException;
use app\admin\model\v1\SysUserLoginLogModel;
use app\admin\model\v1\SysUserModel;
use app\admin\validate\v1\LoginValidate;
use thans\jwt\facade\JWTAuth;
use think\facade\Cache;

/**
 * 用户中心控制器
 */
class UserCenter
{
    /**
     * 登录验证接口
     */
    public function login()
    {
        // 获取参数
        $post = request()->post([
            'username',
            'password',
            'token',
            'captcha'
        ]);

        $user = new SysUserModel();
        $msg  = '';
        try {
            // 验证参数
            $validate = new LoginValidate();
            if (!$validate->check($post)) {
                throw new InvalidLoginException($validate->getError());
            }

            if (!empty($post['captcha'])) {
                // 校验验证码
                $code = Cache::get('captcha:token.' . $post['token']);
                if (!$code) {
                    throw new InvalidLoginException('验证码不存在或已过期');
                }
                Cache::delete('captcha:token.' . $post['token']);

                // 校验
                if (!password_verify($post['captcha'], $code)) {
                    throw new InvalidLoginException('验证码错误');
                }
            }
            
            // 验证用户
            $user = SysUserModel::usernameOrMobile($post['username'])->find();
            if (!$user) {
                throw new InvalidLoginException('用户不存在');
            }

            // 验证密码
            if ($user['password'] != password_with_salt($post['password'], $user['salt'])) {
                throw new InvalidLoginException('密码错误');
            }

            // 验证用户状态
            if ($user['status'] == -1) {
                throw new InvalidLoginException('用户已禁用，请联系管理员');
            }
        } catch (InvalidLoginException $e) {
            $msg = $e->getMessage();
            return error($msg);
        } catch (\Throwable $th) {
            $msg = $th->getMessage();
            return error('登录失败');
        }

        // 记录登录日志
        SysUserLoginLogModel::create([
            'user_id'    => $user['id'],
            'ip'         => ip2long(request()->ip()),
            'user_agent' => request()->header('user-agent'),
        ]);

        // 生成 jwt token
        $token = JWTAuth::builder(['uid' => $user['id']]);
        
        return success('登录成功', [
            'uid'      => $user['id'],
            'username' => $user['username'],
            'avatar'   => $user['avatar'],
            'token'    => $token,
        ]);
    }

    // 退出登录
    public function logout()
    {
        $token = request()->header('Authorization');
        if (\think\helper\Str::startsWith($token, 'Bearer ')) {
            $token = substr($token, 7);
        }

        // token 加入黑名单
        JWTAuth::invalidate($token);

        return success('操作成功');
    }
}
