package com.njyunzhi.pet_identity.common;

import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

@Component
public class HttpUtils {

    public byte[] download(String url) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        Map<String, Object> urlAndParams = parseURL(url);
        String formatURL = (String) urlAndParams.get("url");
        Map<String, String> params = (Map<String, String>) urlAndParams.get("params");

        ResponseEntity<byte[]> resp = restTemplate.exchange(formatURL, HttpMethod.GET, entity, byte[].class, params);
        return resp.getBody();
    }

    public String get(String url) throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<String>(headers);

        Map<String, Object> urlAndParams = parseURL(url);
        String formatURL = (String) urlAndParams.get("url");
        Map<String, String> params = (Map<String, String>) urlAndParams.get("params");

        ResponseEntity<String> resp = restTemplate.exchange(formatURL, HttpMethod.GET, entity, String.class, params);
        return resp.getBody();
    }

    public String post(String url, Map<String, String> header, String body) throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        headers.setAll(header);
        HttpEntity<String> entity = new HttpEntity<String>(body, headers);

        Map<String, Object> urlAndParams = parseURL(url);
        String formatURL = (String) urlAndParams.get("url");
        Map<String, String> params = (Map<String, String>) urlAndParams.get("params");

        ResponseEntity<String> resp = restTemplate.exchange(formatURL, HttpMethod.POST, entity, String.class, params);
        return resp.getBody();
    }

    // RestTemplate 不能正常的处理 querystring, 必须按照约定的方式处理
    private Map<String, Object> parseURL(String url) {
        Map<String, Object> res = new HashMap<>();

        String[] parts = url.split("\\?");
        String baseURL = parts[0];

        if (parts.length < 2) {
            res.put("url", baseURL);
            res.put("params", new HashMap<>());
            return res;
        }


        String[] fields = parts[1].split("&");
        Map<String, String> params = new HashMap<>();
        List<String> searchList = new ArrayList<>();
        for (String field : fields) {
            String[] pairs = field.split("=");
            if (2 != pairs.length) {
                continue;
            }

            try {
                String key = URLDecoder.decode(pairs[0].trim(), "UTF-8");
                String val = URLDecoder.decode(pairs[1].trim(), "UTF-8");

                // 转化为 "foo={foo}" 这种字符串
                searchList.add(String.format("%s={%s}", key, key));
                // 把 foo 对应的值存储起来
                params.put(key, val);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        // url 格式类似 http://foo.org/bar?name={name}
        String formatURL = baseURL + "?" + String.join("&", searchList);
        res.put("url", formatURL);
        res.put("params", params);

        return res;
    }
}
