package card_info_t_mall_game

import (
	"context"
	"kami/internal/consts"
	"kami/internal/errHandler"
	"kami/internal/model"
	"kami/internal/service"
	tmallAPI "kami/utility/integration/tmall/api"

	"github.com/gogf/gf/v2/os/glog"

	"kami/api/card_info_t_mall_game/v1"

	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
)

func (c *ControllerV1) CallBackOrderManual(ctx context.Context, req *v1.CallBackOrderManualReq) (res *v1.CallBackOrderManualRes, err error) {
	tMallGameOrderService := service.RechargeTMallGameOrder()
	orderEntity, err := tMallGameOrderService.GetById(ctx, req.OrderNo, nil)
	if err != nil || orderEntity.Id == 0 {
		err = errHandler.WrapError(ctx, gcode.CodeNotFound, err, "订单不存在")
		return
	}
	tMallClient := tmallAPI.NewClient()
	switch consts.RechargeTMallGameOrder(orderEntity.Status) {
	//如果是发货失败的情况，再次尝试发货
	case consts.RechargeTMallGameOrderStatusDeliveryFailed:
		//尝试发货，尝试三次
		for range 3 {
			if isSucceed, err3 := tMallClient.VirtualDelivery(ctx, orderEntity.ShopId); !isSucceed || err3 != nil {
				err4 := tMallGameOrderService.UpdateOrderStatusByTBOrderNo(ctx, &model.UpdateOrderStatusByTBOrderNoInput{
					OrderNo:    orderEntity.OrderNo,
					Status:     consts.RechargeTMallGameOrderStatusDeliveryFailed,
					SourceType: consts.RechargeTMallGameShopSourceTypeTMall,
				}, nil)
				glog.Error(ctx, "更新订单数据失败", err4)
			} else {
				glog.Info(ctx, "虚拟发货成功")
				if err4 := tMallGameOrderService.UpdateOrderStatusByTBOrderNo(ctx, &model.UpdateOrderStatusByTBOrderNoInput{
					OrderNo:    orderEntity.OrderNo,
					Status:     consts.RechargeTMallGameOrderStatusDeliverySucceed,
					SourceType: consts.RechargeTMallGameShopSourceTypeTMall,
				}, nil); err4 != nil {
					glog.Error(ctx, "更新订单数据失败", err4)
				}
				break
			}
		}
	case consts.RechargeTMallGameOrderStatusFinishedWithWrongAmount,
		consts.RechargeTMallGameOrderStatusFinishedWithWrongStatus:
		_ = tMallGameOrderService.UpdateOrderStatusByTBOrderNo(ctx, &model.UpdateOrderStatusByTBOrderNoInput{
			OrderNo:      orderEntity.OrderNo,
			Status:       consts.RechargeTMallGameOrderStatusFinished,
			SourceType:   "",
			OriginalData: "",
			Remark:       "手动设置订单状态->成功",
		}, nil)
		err = tMallGameOrderService.CallBackOrderToUpstream(ctx, req.OrderNo)
	default:
		err = gerror.NewCode(gcode.CodeInvalidRequest, "订单正在处理中，请稍后重试~")
		_ = tMallGameOrderService.AddOrderHistory(ctx, &model.AddAgisoCallBackHistoryInput{
			OrderNo: req.OrderNo,
			Status:  consts.RechargeTMallGameOrderCallbackFailedManual,
		}, nil)
		return
	case consts.RechargeTMallGameOrderStatusFinished:
		err = tMallGameOrderService.CallBackOrderToUpstream(ctx, req.OrderNo)
	}
	return
}
