package com.hz.pm.api.external;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.hz.pm.api.external.model.dto.MhRetDTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * MhAuthClient
 * </p>
 *
 * @author WendyYang
 * @since 10:11 2023/12/28
 */
@Component
public class MhAuthClient {

    @Value("${mh.sso.client-id:}")
    private String clientId;

    @Value("${mh.sso.client-secret:}")
    private String clientSecret;

    @Value("${mh.api-host:}")
    private String apiHost;

    private static final TypeReference<MhRetDTO<String>> TYPE = new TypeReference<MhRetDTO<String>>() {
    };

    public MhRetDTO<String> getMhUserIdByAuthCode(String authCode) {
        String url = apiHost + "/single/login";
        HttpRequest request = HttpUtil.createPost(url);
        Map<String, Object> param = new HashMap<>(8);
        param.put("code", authCode);
        param.put("clientId", clientId);
        param.put("clientSecret", clientSecret);
        param.put("grantType", "authorization_code");
        request.body(JSONUtil.toJsonStr(param));
        try (HttpResponse execute = request.execute()) {
            String body = execute.body();
            return JSONUtil.toBean(body, TYPE, false);
        }
    }

}
