package kami_gateway

import (
	"context"
	"encoding/json"
	"fmt"

	"github.com/duke-git/lancet/v2/convertor"
	"github.com/gogf/gf/v2/net/gclient"
	"github.com/gogf/gf/v2/net/gtrace"
	"github.com/gogf/gf/v2/os/glog"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/trace"
)

func SubmitOrder(ctx context.Context, input *SubmitOrderReq) (*SubmitOrderResponse, error) {
	ctx, span := gtrace.NewSpan(ctx, "submitOrder", trace.WithAttributes(
		attribute.String("input", fmt.Sprintf("%+v", input))),
	)

	defer span.End()
	input.NotifyUrl = input.GetNotifyUrl()
	params := input.ToStrMap()
	params["sign"] = GetMD5SignMF(params, input.PaySecret)

	paramsStr := map[string]string{}
	for k, v := range params {
		paramsStr[k] = convertor.ToString(v)
	}

	response, err := gclient.New().PostForm(ctx, input.GetUrl(), paramsStr)
	if err != nil {
		glog.Error(ctx, "提交订单失败", "url", input.GetUrl(), "params", params, "error", err)
		return nil, err
	}

	respData := response.ReadAll()
	glog.Info(ctx, "提交订单成功", "url", input.GetUrl(), "params", params, "response", string(respData))

	submitOrderResponse := SubmitOrderResponse{}
	err = json.Unmarshal(respData, &submitOrderResponse)
	if err != nil {
		glog.Error(ctx, "解析订单失败", "error", err)
		return nil, err
	}
	return &submitOrderResponse, nil
}
