package io.renren.modules.kubesphere.service;

import io.renren.common.utils.GsonUtil;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.kubesphere.config.KubeSphereConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * 令牌获取
 *
 * @author chenrj
 * @email 1412736935@qq.com
 * @since 2021/8/18
 */
@Service
public class OauthTokenService {
    private RestTemplate restTemplate = new RestTemplate();
    private final Logger logger = LoggerFactory.getLogger(getClass());

    public String oauthToken(UserEntity user) {
        String username = user.getUsername();
        String password = user.getPassword();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        // 这里是为了登陆kubesphere，要向kuberphere发送token
        params.add("grant_type", "password");
        params.add("username", "admin");
        params.add("password", "MKcloud123");
        HttpEntity<LinkedMultiValueMap<String, Object>> request = new HttpEntity<>(params, headers);
        // 泛型为接口返回数据的类型
        ResponseEntity<String> response = restTemplate.postForEntity(KubeSphereConfig.OAUTH_TOKEN, request, String.class);
        // 获取响应主体
        String res = response.getBody();
        Map<String, String> map = GsonUtil.convertJsonToMap(res);
        String token = map.get("access_token");
        logger.info(token);
        return token;
    }

}
