package services

import (
	"encoding/json"
	"eta/eta_data_analysis/utils"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
)

// PostEdbLib 调用指标接口
func PostEdbLib(param map[string]interface{}, method string) (result []byte, err error) {
	postUrl := utils.EDB_LIB_URL + method
	postData, err := json.Marshal(param)
	if err != nil {
		return
	}
	result, err = HttpPost(postUrl, string(postData), "application/json")
	if err != nil {
		return
	}
	return
}

func HttpPost(url, postData string, params ...string) ([]byte, error) {
	fmt.Println("HttpPost Url:" + url)
	body := ioutil.NopCloser(strings.NewReader(postData))
	client := &http.Client{}
	req, err := http.NewRequest("POST", url, body)
	if err != nil {
		return nil, err
	}
	contentType := "application/x-www-form-urlencoded;charset=utf-8"
	if len(params) > 0 && params[0] != "" {
		contentType = params[0]
	}
	req.Header.Set("Content-Type", contentType)
	req.Header.Set("authorization", utils.MD5(utils.APP_EDB_LIB_NAME_EN+utils.EDB_LIB_Md5_KEY))
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("client.Do err:" + err.Error())
		return nil, err
	}
	defer resp.Body.Close()
	b, err := ioutil.ReadAll(resp.Body)
	fmt.Println("HttpPost:" + string(b))
	return b, err
}
