package utils

import (
	"bytes"
	"crypto/tls"
	"fmt"
	"github.com/JCCE-nudt/apigw-go-sdk/core"
	"io"
	"mime/multipart"
	"net/http"
)

// SignClient AK/SK签名认证
func SignClient(r *http.Request, writer *multipart.Writer) (*http.Client, error) {
	r.Header.Add("content-type", "application/json;charset=UTF-8")
	r.Header.Add("X-Project-Id", "d18190e28e3f45a281ef0b0696ec9d52")
	r.Header.Add("x-stage", "RELEASE")
	r.Header.Add("x-sdk-content-sha256", "UNSIGNED-PAYLOAD")
	r.Header.Set("Content-Type", writer.FormDataContentType())
	s := core.Signer{
		Key:    "UNEHPHO4Z7YSNPKRXFE4",
		Secret: "JWXCE9qcYbc7RjpSRIWt4WgG3ZKF6Q4lPzkJReX9",
	}
	err := s.Sign(r)
	if err != nil {
		return nil, err
	}

	//设置client信任所有证书
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client := &http.Client{
		Transport: tr,
	}
	return client, nil
}

func SendRequest(method, url string, file multipart.File, fileName string) (string, error) {
	/*body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)*/
	// 创建一个新的缓冲区以写入multipart表单
	var body bytes.Buffer
	// 创建一个新的multipart writer
	writer := multipart.NewWriter(&body)
	// 创建一个用于写入文件的表单字段
	part, err := writer.CreateFormFile("file", fileName) // "file"是表单的字段名，第二个参数是文件名
	if err != nil {
		fmt.Println("Error creating form file:", err)
	}
	// 将文件的内容拷贝到multipart writer中
	_, err = io.Copy(part, file)
	if err != nil {
		fmt.Println("Error copying file data:", err)

	}
	err = writer.Close()
	if err != nil {
		fmt.Println("Error closing multipart writer:", err)
	}
	request, err := http.NewRequest(method, url, &body)
	if err != nil {
		fmt.Println("Error creating new request:", err)
		//return nil, err
	}
	signedR, err := SignClient(request, writer)
	if err != nil {
		fmt.Println("Error signing request:", err)
		//return nil, err
	}

	res, err := signedR.Do(request)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return "", err
	}
	//defer res.Body.Close()
	Resbody, err := io.ReadAll(res.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		//return nil, err
	}
	return string(Resbody), nil
}
