package com.bonus.sgzb.auth.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.bonus.sgzb.auth.form.LoginBody;
import com.bonus.sgzb.auth.form.RegisterBody;
import com.bonus.sgzb.auth.service.SysLoginService;
import com.bonus.sgzb.common.core.domain.R;
import com.bonus.sgzb.common.core.utils.JwtUtils;
import com.bonus.sgzb.common.core.utils.StringUtils;
import com.bonus.sgzb.common.security.auth.AuthUtil;
import com.bonus.sgzb.common.security.service.TokenService;
import com.bonus.sgzb.common.security.utils.SecurityUtils;
import com.bonus.sgzb.system.api.model.LoginUser;

/**
 * token 控制
 * 
 * @author ruoyi
 */
@RestController
public class TokenController
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form) {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @PostMapping("sendCode")
    public R<?> sendCode(@RequestBody LoginBody form) {
        // 用户登录
        LoginUser userInfo = sysLoginService.loginCode(form.getPhone(), form.getCode());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @PostMapping("checkCode")
    public R<?> checkCode(@RequestBody LoginBody form) {
        // 校验验证码
        boolean result = sysLoginService.checkCode(form.getPhone(), form.getCode());
        if (result) {
            return R.ok(null, "验证码正确");
        }
        return R.fail("短信验证码错误");
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request)
    {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @PostMapping("register")
    public R<?> register(@RequestBody RegisterBody registerBody)
    {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }
}
