package com.hzs.system.login.controller;

import javax.servlet.http.HttpServletRequest;

import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.system.login.service.IUserLoginService;
import com.hzs.system.sys.dto.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.hzs.common.auth.LoginBody;
import com.hzs.common.core.utils.JwtUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.security.auth.AuthUserUtil;
import com.hzs.common.security.service.UserTokenService;
import com.hzs.common.security.utils.SecurityUtils;

/**
 * 管理端 token 控制
 *
 * @author hzs
 */
@RequestMapping("/auth/manage")
@RestController
public class UserTokenController {

    @Autowired
    private UserTokenService userTokenService;

    @Autowired
    private IUserLoginService iUserLoginService;

    /**
     * 用户登录
     *
     * @param form
     * @return
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody form) {
        // 用户登录
        LoginUser loginUser = iUserLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return AjaxResult.success(userTokenService.createToken(loginUser));
    }

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

}
