/**
  @author: yaoyuliang
**/
package utils

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"errors"
	"gin-vue-admin/models"
	"io"
	"io/ioutil"
	"net/http"
	"strings"
)

func CustomHttpRequestUpload(method, url string, p interface{}, sign map[string]string) (interface{}, error) {

	body, err := GatewayHttpRequest(method, url, sign, p, "")
	if err != nil {
		return nil, err
	}

	var param models.Data

	err = json.Unmarshal(body, &param)
	if err != nil {
		return param, err
	}

	if param.Code != 0 {
		return param, errors.New(param.Msg)
	}

	return param, nil
}

func GatewayHttpRequest(method, url string, sign map[string]string, param interface{}, bodyInfo string) (body []byte, err error) {

	var info io.Reader

	if param != nil {
		b, err_ := json.Marshal(param)
		if err_ != nil {
			return nil, err
		}
		info = bytes.NewReader(b)
	}

	if bodyInfo != "" {
		info = strings.NewReader(bodyInfo)
	}

	req, err := http.NewRequest(method, url, info)
	if err != nil {
		return body, err
	}

	req.Header.Set("Content-Type", "application/json")
	if sign != nil && len(sign) > 0 {
		for k, v := range sign {
			req.Header.Set(k, v)
		}
	}

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return body, err
	}

	defer resp.Body.Close()
	if resp != nil {
		body, err = ioutil.ReadAll(resp.Body)
		if err != nil {
			return body, err
		}
	}

	if resp.StatusCode != http.StatusOK {
		return body, errors.New("unknown mistake")
	}

	return body, err

}

func GetReqHeaderSignData(chainCode, hospitalCode string) map[string]string {

	data := make(map[string]string)

	if str, err := AesEncrypt([]byte(chainCode+"|"+hospitalCode), []byte("dbcaespassword01")); err != nil {
		return nil
	} else {
		data["sign"] = base64.StdEncoding.EncodeToString(str)
		return data
	}
}
