package com.bootdo.system.shiro;

import com.bootdo.common.config.ApplicationContextRegister;
import com.bootdo.common.config.ThirdPartSsoConfig;
import com.bootdo.common.utils.HttpDeleteThread;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.system.domain.ThirdMsgLogDO;
import com.bootdo.system.service.ThirdMsgLogDOService;
import com.bootdo.system.service.TokenCachService;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * 登出过滤
 * 自定义登出逻辑
 *
 * @author Mr.xiBel
 * @date 2022/4/4
 **/
public class SystemLogoutFilter extends LogoutFilter {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /*
     * sso相关配置
     */
    private ThirdPartSsoConfig thirdPartSsoConfig;


    private TokenCachService tokenCachService;

    /**
     * 第三方日志记录
     */
    @Resource
    private ThirdMsgLogDOService thirdMsgLogDOService;

    private void init() {
        this.thirdPartSsoConfig = ApplicationContextRegister.getBean(ThirdPartSsoConfig.class);
        this.thirdMsgLogDOService = ApplicationContextRegister.getBean(ThirdMsgLogDOService.class);
        this.tokenCachService = ApplicationContextRegister.getBean(TokenCachService.class);
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        init();
        Subject subject = getSubject(request, response);
        String redirectUrl = getRedirectUrl(request, response, subject);
        if (thirdPartSsoConfig.getSwitchFlag()) {
            try {
                loginOutSso();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        issueRedirect(request, response, redirectUrl);
        return false;

    }

    /**
     * sso登出通知
     *
     * @throws IOException
     */
    private void loginOutSso() throws IOException {
        Long userId = ShiroUtils.getUserId();
        String tokenCach = tokenCachService.getTokenCach(userId.toString());
        logger.info("method: loginOutSso, userId: {}, token: {}", userId, tokenCach);

        String loginoutUrl = thirdPartSsoConfig.getLoginoutUrl();
        logger.info("method: loginOutSso, userId: {},  token: {}, url: {}", userId, tokenCach, loginoutUrl);
        String result = HttpDeleteThread.run(loginoutUrl, tokenCach);
        logger.info("method: loginOutSso, userId: {},  token: {}, Result: {}", userId, tokenCach, result);

        thirdMsgLogDOService.insert(new ThirdMsgLogDO("第三方系统", new Date(), "sso退出登录", result));
    }
}