package service

import (
	"context"
	"encoding/json"
	"fmt"
	"merchant/internal/config"
	"merchant/internal/models/order"
	"merchant/internal/utils"
	"time"

	"github.com/beego/beego/v2/client/httplib"
	"github.com/beego/beego/v2/core/logs"
)

func CreateOrder(ctx context.Context, input *order.CreatedOrder, paySecret string) (*order.CreateOrderResponse, error) {
	input.Sign = utils.GetMD5SignMF(input.ToStrMap(), paySecret)
	logs.Info("创建订单", input)

	req := httplib.NewBeegoRequestWithCtx(ctx, fmt.Sprintf("%s/gateway/createOrder", config.GetGatewayAddr()), "POST").
		SetTimeout(30*time.Second, 30*time.Second).Retries(3)

	response, err := req.JSONBody(input)
	if err != nil {
		return nil, err
	}

	createOrderResponse := struct {
		Data order.CreateOrderResponse `json:"data,omitempty"`
		Code int                       `json:"code"`
		Msg  string                    `json:"msg"`
	}{
		Data: order.CreateOrderResponse{},
		Code: 0,
		Msg:  "",
	}
	respString, err := response.String()
	if err != nil {
		return nil, err
	}

	err = json.Unmarshal([]byte(respString), &createOrderResponse)
	if err != nil {
		return nil, err
	}

	logs.Info("生成订单成功", respString, "地址：", config.GetGatewayAddr())
	return &createOrderResponse.Data, nil
}

func SubmitOrderBackendTask(ctx context.Context, input *order.SubmitOrder) error {
	pool.Submit(func() {
		resp, err := SubmitOrder(context.Background(), input)
		if err != nil {
			logs.Error("提交订单失败", err)
		}
		logs.Info("提交订单成功", resp)
	})
	return nil
}

func SubmitOrder(ctx context.Context, input *order.SubmitOrder) (*order.SubmitOrderResponse, error) {
	req := httplib.NewBeegoRequestWithCtx(ctx, fmt.Sprintf("%s/gateway/scan", config.GetGatewayAddr()), "POST").
		SetTimeout(5*time.Second, 5*time.Second).Retries(3)

	params := input.ToStrMap()
	params["sign"] = utils.GetMD5SignMF(params, input.PaySecret)

	for k, v := range params {
		req.Param(k, v)
	}

	response, err := req.String()
	if err != nil {
		logs.Error("提交订单失败", err)
		return nil, err
	}

	logs.Info("提交订单成功", fmt.Sprintf("%s/gateway/scan", config.GetGatewayAddr()), params, response)
	submitOrderResponse := order.SubmitOrderResponse{}
	err = json.Unmarshal([]byte(response), &submitOrderResponse)
	if err != nil {
		logs.Error("提交订单失败", err)
		return nil, err
	}

	logs.Info("提交订单成功", response)
	return &submitOrderResponse, nil
}
