package com.keyware.shandan.component;

import com.keyware.shandan.beans.ClientDetailVo;
import com.keyware.shandan.common.util.StringUtils;
import com.keyware.shandan.config.InMemoryTokenStoreImpl;
import com.keyware.shandan.service.ClientDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

/**
 * @author Administrator
 */
@Slf4j
@Component
public class ClientLogoutHandler {

    @Autowired
    private ClientDetailService clientDetailService;

    @Autowired
    private AsyncRestTemplate restTemplate;

    @Autowired
    private InMemoryTokenStoreImpl tokenStore;

    /**
     * 发起客户端登出请求
     */
    public void callClientsLogout(String userId, String clientId) {
        if (StringUtils.isNotBlank(userId)) {
            List<ClientDetailVo> clientList = clientDetailService.getByLogoutClients();
            List<String> oauthClientIds = tokenStore.getClientIdsByUserName(userId);
            clientList.stream()
                    .filter(client-> oauthClientIds.contains(client.getClientId()))
                    .forEach(client -> {
                if (!client.getClientId().equals(clientId) && StringUtils.isNotBlank(client.getLogoutUri())) {
                    try {
                        String url = appendUserIdParam(client.getLogoutUri(), userId);
                        restTemplate.getForObjectAsync(url, String.class).addCallback(result -> {
                            log.info("异步调用登出请求接口成功，客户端：{}, 用户ID：{}", client.getTitle(), userId);
                        }, failure -> {
                            log.warn("异步调用登出请求接口失败，客户端：{}； 请求地址：{}； 失败原因：{}", client.getTitle(), client.getLogoutUri(), failure.getMessage());
                        });
                    } catch (URISyntaxException e) {
                        log.warn("异步调用登出请求接口时异常，客户端：{}； 请求地址：{}；异常消息：{}", client.getTitle(), client.getLogoutUri(), e.getMessage());
                        e.printStackTrace();
                    }
                }
            });
            tokenStore.removeAccessTokenByUserName(userId);
        }
    }

    /**
     * 拼接用户参数
     *
     * @param url    url
     * @param userId 用户ID
     * @return 新的url
     * @throws URISyntaxException
     */
    private String appendUserIdParam(String url, String userId) throws URISyntaxException {
        URI uri = new URI(url);
        String param = "loginName=" + userId;
        if (StringUtils.isNotBlank(uri.getQuery())) {
            return url + "&" + param;
        } else {
            return url + "?" + param;
        }
    }
}
