package com.fs.framework.security.handle;

import com.alibaba.fastjson.JSON;
import com.fs.common.constant.Constants;
import com.fs.common.constant.HttpStatus;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.framework.manager.AsyncManager;
import com.fs.framework.manager.factory.AsyncFactory;
import com.fs.framework.security.LoginAdminUser;
import com.fs.framework.security.LoginCompanyUser;
import com.fs.framework.service.TokenService;
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 javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义退出处理类 返回成功
 *

 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler
{
    @Autowired
    private TokenService tokenService;

    /**
     * 退出处理
     *
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException
    {
        Object user = tokenService.getLoginUser(request);

        if (StringUtils.isNotNull(user)) {
            //获取不同对象
            String type = request.getHeader("X-Frontend-Type");
            if ("admin".equals(type)){
                LoginAdminUser loginUser =(LoginAdminUser) user;
                String userName = loginUser.getUsername();
                // 删除用户缓存记录
                tokenService.delLoginUser(loginUser.getToken());
                // 记录用户退出日志
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
            } else if ("company".equals(type)){
                LoginCompanyUser loginUser =(LoginCompanyUser) user;
                String userName = loginUser.getUsername();
                // 删除用户缓存记录
                tokenService.delLoginUser(loginUser.getToken());
                // 记录用户退出日志
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
            }
        }
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(HttpStatus.SUCCESS, "退出成功")));
    }
}
