package card_info_apple

import (
	"context"
	"fmt"
	"kami/internal/consts"
	"kami/internal/errHandler"
	"kami/internal/model"
	"kami/internal/service"

	v1 "kami/api/card_info_apple/v1"

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

func (c *ControllerV1) RechargeOrderModifyActualAmount(ctx context.Context, req *v1.RechargeOrderModifyActualAmountReq) (res *v1.RechargeOrderModifyActualAmountRes, err error) {
	_, err = service.SysAuth().LoginOnlyIFrame(ctx)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeNotAuthorized, err, "权限不足")
		return
	}
	isPass, err := service.BaseUserInfo().TotpValidate(ctx, req.TotpCode)
	if err != nil || !isPass {
		err = errHandler.WrapError(ctx, gcode.CodeInvalidRequest, err, "TOTP验证失败")
		return
	}
	rechargeOrderService := service.AppleOrder()
	orderEntity, err := rechargeOrderService.GetOneByOrderNo(ctx, req.OrderNo, nil, 0)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeInternalError, err, "查询订单失败")
		return
	}
	if orderEntity.Status != int(consts.AppleRechargeOrderFail) {
		err = errHandler.WrapError(ctx, gcode.CodeInvalidRequest, err, "订单未处于失败状态")
		return
	}
	//添加一条记录
	err = rechargeOrderService.UpdateActualAmountAndHistoryAndWallet(ctx, &model.AppleAccountUpdateAmountAndHistoryRecord{
		OrderInfo: &model.AppleAccountUpdateAmountRecord{
			OrderNo: orderEntity.OrderNo,
			Amount:  req.ActualAmount,
			Status:  consts.AppleRechargeOrderSuccess,
			Remark:  fmt.Sprintf("修正金额：%f", req.ActualAmount),
		},
		HistoryOperation: consts.AppleRechargeOperationHandleActualAmountSuccess,
		HistoryRemark:    fmt.Sprintf("修正金额：%.2f", req.ActualAmount),
		WalletRemark:     fmt.Sprintf("修正金额：%.2f", req.ActualAmount),
	})
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeInternalError, err, "修改订单金额失败")
		return
	}
	_ = rechargeOrderService.CallBackOrderToUpstream(ctx, req.OrderNo)
	return
}
