package request

import (
	"bytes"
	"encoding/json"
	"errors"
	"io"
	"net/http"

	"gitee.com/yansen_zh/wxcomponent/utils/log"
)

func post(url string, contentType string, body []byte) ([]byte, error) {

	logger := log.GetLogger()
	logger.Info("发送请求: ", url)

	if len(body) > 0 {
		logger.Info(body)
	}

	resp, e1 := http.Post(url, contentType, bytes.NewReader(body))
	if e1 != nil {
		return nil, e1
	}

	if resp.StatusCode > 299 {
		return nil, errors.New(resp.Status)
	}

	body, e2 := io.ReadAll(resp.Body)
	resp.Body.Close()
	if e2 != nil {
		return nil, e2
	}

	logger.Info("微信端返回: ", body)

	return body, nil
}

// PostJSON 使用 POST 方式发送 json 数据
func PostJSON(url string, body interface{}) ([]byte, error) {
	data, e1 := json.Marshal(body)
	if e1 != nil {
		return nil, e1
	}

	return post(url, ContentTypeJSON, data)

}