package utils

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"net/url"
	"strings"
	"time"
)

func SerializeJson(data interface{}) []byte {
	reply, _ := json.Marshal(data)
	return reply
}

func UnserislizeJson(str string, data interface{}) {
	_ = json.Unmarshal([]byte(str), data)
}

func ChangeData(dataBefore interface{}, dataAfter interface{}) {
	UnserislizeJson(string(SerializeJson(dataBefore)), dataAfter)
}

func RequesBody(reqBody io.ReadCloser) []byte {
	var bodyBytes []byte
	bodyBytes, _ = ioutil.ReadAll(reqBody)
	return bodyBytes
}

// 发送POST请求
// url：         请求地址
// data：        POST请求提交的数据
// contentType： 请求体格式，如：application/json
// content：     请求放回的内容
func Post(url string, data interface{}, token string) string {
	// 超时时间：10秒
	client := &http.Client{Timeout: 10 * time.Second}

	jsonStr, _ := json.Marshal(data)
	fmt.Println(string(jsonStr))
	reqest, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))

	if token != "" {
		reqest.Header.Add("Authorization", "Bearer "+token)
	}
	reqest.Header.Add("Content-Type", "application/json")
	reqest.Header.Add("Connection", "keep-alive")
	if err != nil {
		panic(err)
	}

	resp, _ := client.Do(reqest)
	defer resp.Body.Close()

	result, _ := ioutil.ReadAll(resp.Body)
	return string(result)
}

func Get(path string, params map[string]string) (string, error) {

	var client = http.Client{
		Timeout: 10 * time.Second,
	}
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("http get err: ", err)
			fmt.Println("client: ", client)
			return
		}
	}()
	param := "?"
	for key, val := range params {
		param += key + "=" + url.QueryEscape(val) + "&"
	}
	param = strings.Trim(param, "&")

	fmt.Println(path + param)
	resp, err := client.Get(path + param)
	resp.Header.Set("Content-Type", "application/json; charset=utf-8")
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)

	return string(body), nil
}

func PostWithFormData(method, url string, postData *map[string]string, token string) string {
	body := new(bytes.Buffer)
	w := multipart.NewWriter(body)
	for k, v := range *postData {
		w.WriteField(k, v)
	}
	w.Close()
	req, _ := http.NewRequest(method, url, body)
	req.Header.Set("Content-Type", w.FormDataContentType())
	req.Header.Set("Authorization", "Bearer "+token)
	resp, _ := http.DefaultClient.Do(req)
	data, _ := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	fmt.Println(resp.StatusCode)
	fmt.Printf("%s", data)
	return string(data)
}
