package org.jeecg.modules.iam.req;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jeecg.modules.iam.dto.IamResponseDTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * 统一验证平台请求
 */
@Component
public class IamReq {

    private static String postUserInfoUrl = "http://47.110.134.43:15105/common-uuv/login/user/temp-code";

    private static RestTemplate restTemplate = new RestTemplate();


    @Resource
    public void setRestTemplate(RestTemplate restTemplate) {
        IamReq.restTemplate = restTemplate;
    }

    @Value("${iam.postUserInfoUrl}")
    public void setPostUserInfoUrl(String postUserInfoUrl) {
        IamReq.postUserInfoUrl = postUserInfoUrl;
    }


    public static IamResponseDTO execute(String tempCode) {
        // 1.组装请求参数
        // 1.1 请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cache-Control", "no-cache");
        headers.set("Accept", "*/*");
        headers.set("Accept-Encoding", "gzip, deflate, br");
        headers.set("Connection", "keep-alive");
        headers.set("procInstId", "10000001"); // 自定义请求头
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); // 根据需要设置请求体类型

        // 1.2 组装空请求体和请求头
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(new LinkedMultiValueMap<>(), headers);


        // 2.执行请求
        ResponseEntity<String> response = restTemplate.postForEntity(postUserInfoUrl + "?tempCode=" + tempCode, requestEntity, String.class);


        if (response.getStatusCode() == HttpStatus.OK) {
            return JSONObject.parseObject(response.getBody(), IamResponseDTO.class);
        } else {
            IamResponseDTO iamResponseDTO = new IamResponseDTO();
            iamResponseDTO.setStatus("err");
            iamResponseDTO.setMessage("网络错误,网络错误码:" + response.getStatusCode());
            iamResponseDTO.setErrCode("http状态码:" + response.getStatusCode());
            return iamResponseDTO;
        }
    }

    public static void main(String[] args) {
        String tempCode = "841d5c67-ad61-4593-b504-eb12077ddca1";
        execute(tempCode);
    }

}
