package service

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"time"
)

func CurPost(requestUrl string, requestBody interface{}, headerMap map[string]string) (string, error) {
	//转换json
	jsonBytes, err := json.Marshal(requestBody)
	if err != nil {
		return "", err
	}

	//创建请求
	req, err := http.NewRequest("POST", requestUrl, bytes.NewReader(jsonBytes))
	if err != nil {
		return "", err
	}
	//设置请求头
	req.Header.Set("Content-Type", "application/json;charset=UTF-8")
	for k, v := range headerMap {
		//req.Header.Set("Accept-Encoding", "gzip, deflate, br")
		req.Header.Set(k, v)
	}
	//发送请求
	clt := http.Client{Timeout: 30 * time.Second}
	res, err := clt.Do(req)
	if err != nil {
		return "", err
	}
	//获取结果
	body, err := io.ReadAll(res.Body)
	data := string(body)

	return data, err

}

func CurlGet(url string, values url.Values, header http.Header) (string, error) {
	req, reqErr := http.NewRequest(http.MethodGet, url, nil)
	if reqErr != nil {
		return "", reqErr
	}
	if header != nil {
		req.Header = header
	}
	if values != nil {
		req.URL.RawQuery = values.Encode()
	}
	fmt.Println(req.URL.Host, req.URL.RawQuery)
	resp, resErr := http.DefaultClient.Do(req)
	if resErr != nil {
		return "", resErr
	}
	defer func() { _ = resp.Body.Close() }()
	content, readErr := io.ReadAll(resp.Body)
	if readErr != nil {
		return "", readErr
	}
	//if decodeErr := json.Unmarshal(content, result); decodeErr != nil {
	//	return "", decodeErr
	//}
	return string(content), nil
}
