package utils

import (
	"bytes"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"fonchain-fiee/pkg/e"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"time"
)

const (
	ExcelPrefix = "xlsx"
)

func SHA256V(str []byte) string {
	h := sha256.New()
	h.Write(str)
	return hex.EncodeToString(h.Sum(nil))
}

func Get(url string) string {
	client := &http.Client{Timeout: 5 * time.Second}
	resp, err := client.Get(url)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	var buffer [512]byte
	result := bytes.NewBuffer(nil)
	for {
		n, err := resp.Body.Read(buffer[0:])
		result.Write(buffer[0:n])
		if err != nil && err == io.EOF {
			break
		} else if err != nil {
			panic(err)
		}
	}

	return result.String()
}

// PostForm 发送post请求
func PostForm(urlStr string, data url.Values) (string, error) {
	resp, err := http.PostForm(urlStr, data)

	if err != nil {
		// handle error
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// handle error
	}
	return string(body), err
}

func CheckDirPath(path string, create bool) (exists bool, err error) {
	exists = false
	if path == "" {
		err = errors.New(e.GetMsg(e.InvalidParams))
		return
	}
	if _, err = os.Stat(path); os.IsNotExist(err) {
		if !create {
			return
		}
		if err = os.MkdirAll(path, os.ModePerm); err != nil {
			return
		}
	}
	exists = true
	return
}
