package com.chushang.auth.controller;

import com.chushang.auth.service.UserService;
import com.chushang.common.core.util.JwtUtils;
import com.chushang.common.core.util.StringUtils;
import com.chushang.common.core.web.AjaxResult;
import com.chushang.datascope.entity.DataScopeEntity;
import com.chushang.security.auth.AuthUtil;
import com.chushang.security.service.TokenService;
import com.chushang.security.utils.SecurityUtils;
import com.chushang.system.entity.bo.LoginBody;
import com.chushang.security.entity.vo.LoginUser;
import com.chushang.system.entity.po.SysUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * token 控制
 *
 * @author ruoyi
 */
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class UserController
{
    final TokenService tokenService;
    final UserService userService;

    @PostMapping("login")
    public AjaxResult login(@RequestBody LoginBody form)
    {
        // 用户登录
        LoginUser<SysUser, DataScopeEntity> loginUser = userService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return AjaxResult.success(tokenService.createToken(loginUser));
    }

    @DeleteMapping("logout")
    public AjaxResult logout(HttpServletRequest request)
    {
        String token = SecurityUtils.getToken(request);
        log.info("退出登录 {}", token);
        if (StringUtils.isNotEmpty(token))
        {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            userService.logout(username);
        }
        return AjaxResult.success();
    }

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

}
