package com.bonus.auth.controller;

import javax.servlet.http.HttpServletRequest;
import com.bonus.common.core.utils.global.SystemGlobal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.bonus.auth.form.LoginBody;
import com.bonus.auth.service.SysLoginService;
import com.bonus.common.core.domain.R;
import com.bonus.common.core.utils.JwtUtils;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.security.auth.AuthUtil;
import com.bonus.common.security.service.TokenService;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.system.api.model.LoginUser;

/**
 * token 控制
 * 
 * @author bonus
 */
@RestController
@Slf4j
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));
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request) {
        try{
            String token = SecurityUtils.getToken(request);
            if (StringUtils.isNotEmpty(token) && !SystemGlobal.undefined.equals(token.toLowerCase()))
            {
                String username = JwtUtils.getUserName(token);
                String userId= JwtUtils.getUserId(token);
                // 删除用户缓存记录
                AuthUtil.logoutByToken(token);
                // 记录用户退出日志
                sysLoginService.logout(username,userId);
            }
        }catch (Exception e){
            sysLoginService.logout("","");
            log.error(e.toString(),e);
        }
        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();
    }

}
