package com.philisense.www.handler;

import com.alibaba.fastjson.JSON;
import com.philisense.www.constant.HttpStatus;
import com.philisense.www.pojos.entity.JwtUser;
import com.philisense.www.utils.JwtTokenUtils;
import com.philisense.www.utils.ServletUtils;
import com.philisense.www.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义退出处理类 返回成功
 *
 * @Description:
 * @author
 */
@Component("jwtLogoutSuccessHandler")
public class JwtLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired
    private JwtTokenUtils jwtTokenUtils;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        JwtUser jwtUser = jwtTokenUtils.getJwtUser(request);
        if (StringUtils.isNotNull(jwtUser)) {
            // 删除用户缓存记录
            jwtTokenUtils.delJwtUser(jwtUser.getToken());
        }

        Map<String,Object> responsemap = new HashMap<>();
        responsemap.put("success", true);
        responsemap.put("message", "注销成功");
        responsemap.put("error", "no");
        responsemap.put("status", HttpStatus.SUCCESS);
        responsemap.put("timestamp", new Date());
        responsemap.put("path", request.getRequestURI());
        ServletUtils.renderString(response, JSON.toJSONString(responsemap));
    }
}
