package com.xhkjedu.sapi.utils;

import com.xhkjedu.sapi.config.ConfigKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static com.xhkjedu.utils.N_Utils.getSecondTimestamp;

/**
 * @ClassName ApiUtil
 * Description api工具类
 * Author WN
 * Date 2022/2/21 11:08
 **/
@Slf4j
public class ApiUtil {
    public static Integer id = 0;
    public static Map<String, String> uriMap = new ConcurrentHashMap<>();

    //获取id
    public static String getId(){
        Integer nummin = ConfigKey.nummin;
        Integer nummax = ConfigKey.nummax;
        if (id == 0 || id.equals(nummax)) {
            id = nummin;
        } else {
            id ++;
        }
        String _num = (getSecondTimestamp() + ConfigKey.numadd) +"" + id;
        long num = Long.parseLong(_num);
        return Long.toString(num,36).toUpperCase();
    }

    /**
     * 发送form-data请求返回json结果
     * @Param [apiUrl, param]
     * @Author ywx
     * @Date 2021/5/14 17:41
     * @return java.lang.String
     **/
    public static String sendFormData(String apiUrl, MultiValueMap<String, String> param) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            List<MediaType> acceptableMediaTypes = new ArrayList<>();
            acceptableMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
            acceptableMediaTypes.add(MediaType.APPLICATION_PROBLEM_JSON_UTF8);
            HttpEntity<MultiValueMap<String, String>> requestParams = new HttpEntity<>(param, headers);
            ResponseEntity<String> response = new RestTemplate().postForEntity(apiUrl, requestParams, String.class);
            String result = response.getBody();
            return result;
        } catch (RestClientException e) {
            log.error("发送form-data请求失败",e.getMessage());
            return null;
        }
    }
}
