package card_info_apple

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

	"github.com/gogf/gf/v2/database/gdb"

	v1 "kami/api/card_info_apple/v1"

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

func (c *ControllerV1) RechargeOrderResetStatus(ctx context.Context, req *v1.RechargeOrderResetStatusReq) (res *v1.RechargeOrderResetStatusRes, err error) {
	err = config.GetDatabaseV1().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		rechargeService := service.AppleOrder()
		orderInfo, err2 := rechargeService.GetOneByOrderNo(ctx, req.OrderNo, nil)
		if err2 != nil {
			return err2
		}
		if orderInfo.Status != int(consts.AppleRechargeOrderFreeze) {
			return gerror.NewCode(gcode.CodeInternalError, "只有冻结订单才可以重置")
		}
		if err2 = rechargeService.ModifyOrderStatus(ctx, req.OrderNo, consts.AppleRechargeOrderWaiting, fmt.Sprintf("人工重置订单：%s", req.Remark), tx); err2 != nil {
			return err2
		}
		if err2 = rechargeService.ResetDistributionCount(ctx, req.OrderNo, tx); err2 != nil {
			return err2
		}
		err2 = rechargeService.AddHistory(ctx, &model.AppleCardRechargeHistoryInput{
			RechargeId:  int(orderInfo.Id),
			OrderNo:     req.OrderNo,
			AccountID:   orderInfo.AccountId,
			AccountName: orderInfo.AccountName,
			Operation:   consts.AppleRechargeOperationResetStatus,
			Remark:      req.Remark,
		}, tx)
		return err2
	})
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeInternalError, err, "重置订单状态失败")
	}
	return
}
