package com.lij.himeeter.framework.security.handle;

import com.alibaba.fastjson2.JSON;
import com.lij.himeeter.common.constant.Constants;
import com.lij.himeeter.common.core.domain.AjaxResult;
import com.lij.himeeter.common.core.domain.model.LoginUser;
import com.lij.himeeter.common.utils.MessageUtils;
import com.lij.himeeter.common.utils.ServletUtils;
import com.lij.himeeter.common.utils.StringUtils;
import com.lij.himeeter.framework.manager.AsyncManager;
import com.lij.himeeter.framework.manager.factory.AsyncFactory;
import com.lij.himeeter.framework.web.service.TokenService;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import java.io.IOException;

/**
 * <pre>
 *
 * 文件名 :  LogoutSuccessHandlerImpl
 * 创建时间 : 2025年01月02日 14:53
 *
 * 文件描述 : 无
 *
 * </pre>
 *
 * @author Nobita
 * @version 1.0.0
 */

@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Autowired
    private TokenService tokenService;


    /**
     * 退出处理
     *
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, MessageUtils.message("user.logout.success")));
        }
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.success(MessageUtils.message("user.logout.success"))));
    }
}
