package com.ylx.framework.security.handle;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.json.JSONUtil;
import com.ylx.common.core.domain.model.WxLoginUser;
import com.ylx.framework.web.service.WxTokenService;
import lombok.extern.slf4j.Slf4j;
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 com.alibaba.fastjson2.JSON;
import com.ylx.common.constant.Constants;
import com.ylx.common.core.domain.AjaxResult;
import com.ylx.common.core.domain.model.LoginUser;
import com.ylx.common.utils.MessageUtils;
import com.ylx.common.utils.ServletUtils;
import com.ylx.common.utils.StringUtils;
import com.ylx.framework.manager.AsyncManager;
import com.ylx.framework.manager.factory.AsyncFactory;
import com.ylx.framework.web.service.TokenService;

/**
 * 自定义退出处理类 返回成功
 *
 * @author ylx
 */
@Slf4j
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
    @Autowired
    private TokenService tokenService;


    @Autowired
    private WxTokenService wxTokenService;

    /**
     * 退出处理
     *
     * @param request
     * @param response
     * @param authentication
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.info("用户退出登录");
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            log.info("PC用户退出登录");
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, MessageUtils.message("user.logout.success")));
        }else{
            log.info("微信用户退出登录");
            WxLoginUser wxUser = wxTokenService.getWxUser(request);
            if (StringUtils.isNotNull(wxUser)) {
                // 删除用户缓存记录
                wxTokenService.delWxUser(wxUser.getToken());
                String userName = wxUser.getUsername();
                // 记录用户退出日志
                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"))));
    }
}
