package card_info_t_mall_game

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

	"github.com/gogf/gf/v2/text/gstr"

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

	"kami/api/card_info_t_mall_game/v1"
)

func (c *ControllerV1) TMallGameOrderModifyStatusSucceed(ctx context.Context, req *v1.TMallGameOrderModifyStatusSucceedReq) (res *v1.TMallGameOrderModifyStatusSucceedRes, 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
	}
	//查找订单
	orderService := service.RechargeTMallGameOrder()
	orderInfo, err := orderService.GetById(ctx, req.OrderNo, nil)
	err = utils.HandleNoRowsError(err)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeNotFound, err, "订单不存在")
		return
	}
	if !gstr.InArray([]string{
		string(consts.RechargeTMallGameOrderStatusFinishedWithWrongAmount),
		string(consts.RechargeTMallGameOrderStatusFinishedWithWrongStatus),
		string(consts.RechargeTMallGameOrderStatusDeliveryFailed),
	}, orderInfo.Status) {
		err = errHandler.WrapError(ctx, gcode.CodeInvalidRequest, gerror.New("当前状态不能回调"))
		return
	}
	err = orderService.UpdateOrderStatusByTBOrderNo(ctx, &model.UpdateOrderStatusByTBOrderNoInput{
		OrderNo: req.OrderNo,
		Status:  consts.RechargeTMallGameOrderStatusFinished,
		Remark:  "手动处理成功",
	}, nil)
	err = errHandler.WrapError(ctx, gcode.CodeInternalError, err, "更新状态失败")
	return
}
