package card_apple_order

import (
	"context"
	"fmt"
	"time"

	"github.com/gogf/gf/v2/net/gtrace"
	"github.com/gogf/gf/v2/os/gctx"

	"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"

	"kami/internal/consts"
	"kami/internal/dao"
	"kami/internal/errHandler"
	"kami/internal/model"
	"kami/internal/model/entity"
	"kami/utility/config"
	"kami/utility/pool"
	"kami/utility/utils"
)

// CallbackOrder 回调订单给第三方
func (h *sAppleOrder) CallbackOrder(ctx context.Context, data *entity.V1CardAppleRechargeInfo) (bool, error) {
	timestamp := gtime.Now().Timestamp()
	status := data.Status
	if consts.AppleRechargeOrderAmountDifferent == consts.AppleRechargeOrderStatus(data.Status) {
		status = int(consts.AppleRechargeOrderFail)
	}

	params := g.Map{
		"attach":    data.Attach,
		"order_id":  data.OrderNo,
		"amount":    data.ActualAmount,
		"status":    status,
		"remark":    data.Remark,
		"timestamp": timestamp,
		"sign":      utils.TmpEncrypt(data.Attach + data.OrderNo + gconv.String(timestamp)),
	}

	glog.Info(ctx, "回调参数：", params, "回调地址：", data.CallbackUrl)
	client := gclient.New()
	client.SetTimeout(30 * time.Second)
	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 *sAppleOrder) CallBackOrderToUpstream(ctx context.Context, orderNo string) (err error) {
	ctx, span := gtrace.NewSpan(ctx, "苹果回调")
	defer span.End()
	orderEntity, err := h.GetOneByOrderNo(ctx, orderNo, nil)
	if err != nil {
		return
	}
	err = pool.New(pool.AppleCardCallBack, 20).Add(gctx.GetInitCtx(), func(ctx context.Context) {
		isOk, err2 := h.CallbackOrder(ctx, &orderEntity)
		// 增加回调次数
		_, err = dao.V1CardAppleRechargeInfo.Ctx(ctx).DB(config.GetDatabaseV1()).
			Where(dao.V1CardAppleRechargeInfo.Columns().OrderNo, orderNo).
			Increment(dao.V1CardAppleRechargeInfo.Columns().CallbackCount, 1)
		if isOk {
			_ = h.ModifyCallBackStatus(ctx, orderEntity.OrderNo, true, nil)
			return
		}
		glog.Error(ctx, "回调上游失败，原因：", err2)
		_ = h.AddHistory(ctx, &model.AppleCardRechargeHistoryInput{
			OrderNo:    orderEntity.OrderNo,
			RechargeId: int(orderEntity.Id),
			AccountID:  orderEntity.AccountId,
			Operation:  consts.AppleRechargeOperationCallBackFailed,
			Remark:     fmt.Sprintf("回调订单%d失败，原因：回调接口返回失败", orderEntity.CallbackCount+1),
		}, nil)
		if orderEntity.CallbackCount+1 >= consts.AppleOrderMaxCallbackCount {
			_ = h.ModifyCallBackStatus(ctx, orderEntity.OrderNo, false, nil)
		}
	})
	return
}
