package card_t_mall_order

import (
	"context"
	"fmt"
	"kami/internal/consts"
	"kami/internal/errHandler"
	"kami/internal/model"
	"kami/internal/model/entity"
	"kami/utility/pool"
	"kami/utility/utils"
	"time"

	"github.com/duke-git/lancet/v2/retry"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/gclient"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/text/gstr"
	"github.com/gogf/gf/v2/util/gconv"
)

// CallbackOrder 回调订单给第三方
func (h *sRechargeTMallGameOrder) CallbackOrder(ctx context.Context, data *entity.V1RechargeTMallOrder) (bool, error) {
	client := gclient.New()
	timestamp := gtime.Now().Timestamp()
	params := g.Map{
		"merchantOrder": data.MerchantOrder,
		"orderId":       data.OrderNo,
		"amount":        data.Amount,
		"status":        data.Status,
		"remark":        data.Remark,
		"timestamp":     timestamp,
		"sign":          utils.TmpEncrypt(data.MerchantOrder + data.OrderNo + gconv.String(timestamp)),
	}
	glog.Info(ctx, "回调订单：", params["orderId"], "回调地址：", data.CallbackUrl)
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	response := client.GetContent(ctx, data.CallbackUrl, params)
	glog.Info(ctx, "回调结果：", response)
	if gstr.ToLower(response) == "success" {
		return true, nil
	} else {
		return false, gerror.NewCode(errHandler.HttpClientGetError, fmt.Sprintf("回调失败：%s", response))
	}
}

func (h *sRechargeTMallGameOrder) CallBackOrderToUpstream(ctx context.Context, orderNo string) (err error) {
	orderEntity, err := h.GetById(ctx, orderNo, nil)
	if err != nil {
		return
	}
	err = pool.New(pool.AppleCardTMallCallback, 20).Add(context.WithoutCancel(ctx), func(ctx2 context.Context) {
		isOk := false
		err2 := retry.Retry(func() error {
			isOk, _ = h.CallbackOrder(ctx2, orderEntity)
			if isOk {
				_ = h.AddOrderHistory(ctx2, &model.AddAgisoCallBackHistoryInput{
					OrderNo: orderEntity.OrderNo,
					Status:  consts.RechargeTMallGameOrderCallbackSucceed,
				}, nil)
				return nil
			}
			_ = h.AddOrderHistory(ctx2, &model.AddAgisoCallBackHistoryInput{
				OrderNo: orderEntity.OrderNo,
				Status:  consts.RechargeTMallGameOrderCallbackFailed,
				Remark:  fmt.Sprintf("回调失败，原因：回调接口返回失败"),
			}, nil)
			return gerror.NewCode(errHandler.HttpClientGetError, fmt.Sprintf("回调失败，原因：回调接口返回失败"))
		}, retry.Context(ctx))
		if err2 != nil {
			glog.Error(ctx, "回调上游失败：", err2)
		}
		_ = h.ModifyCallBackStatus(ctx, orderEntity.OrderNo, isOk, nil)
	})
	return
}
