package utils

import (
	"LAPP_ACURA_MOM_BACKEND/conf"
	"bytes"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"net/url"
	"os"
)

func GetRequest(u string, headers map[string]string) (body []byte, err error) {
	proxy := func(_ *http.Request) (*url.URL, error) {
		return url.Parse(conf.DbConfig.Proxy)
	}

	transport := &http.Transport{Proxy: proxy}
	client := &http.Client{Transport: transport}
	req, err := http.NewRequest(http.MethodGet, u, nil)
	if err != nil {
		return nil, err
	}
	for key, value := range headers {
		req.Header.Add(key, value)
	}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	body, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return body, nil
}

func PostFormDataWithSingleFile(u string, filepath string, filename string, headers map[string]string) (body []byte, err error) {
	proxy := func(_ *http.Request) (*url.URL, error) {
		return url.Parse(conf.DbConfig.Proxy)
	}
	transport := &http.Transport{Proxy: proxy}
	client := &http.Client{Transport: transport}
	bodyBuf := &bytes.Buffer{}
	bodyWrite := multipart.NewWriter(bodyBuf)
	file, err := os.Open(filepath)

	if err != nil {
		return nil, err
	}
	defer file.Close()
	// file 为key
	fileWrite, err := bodyWrite.CreateFormFile("file", filename)
	if err != nil {
		return nil, err
	}
	_, err = io.Copy(fileWrite, file)
	if err != nil {
		return nil, err
	}
	err = bodyWrite.Close() //要关闭，会将w.w.boundary刷写到w.writer中
	if err != nil {
		return nil, err
	}
	// 创建请求
	contentType := bodyWrite.FormDataContentType()
	req, err := http.NewRequest(http.MethodPost, u, bodyBuf)
	if err != nil {
		return nil, err
	}
	// 设置头
	req.Header.Set("Content-Type", contentType)
	for key, value := range headers {
		req.Header.Add(key, value)
	}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	body, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return body, nil
}

func Post(url string, data []byte) (body []byte, err error) {
	client := http.Client{}
	// 创建请求
	reader := bytes.NewReader(data)
	req, err := http.NewRequest(http.MethodPost, url, reader)
	if err != nil {
		return nil, err
	}
	// 设置头
	req.Header.Set("Content-Type", "application/json;charset=UTF-8")
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	body, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return body, nil
}
