package card_info_apple

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

	"github.com/duke-git/lancet/v2/pointer"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/os/gmlock"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/util/gconv"

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

	v1 "kami/api/card_info_apple/v1"
)

const lock = "card_info_apple_recharge_submit_lock"

func (c *ControllerV1) RechargeSubmit(ctx context.Context, req *v1.RechargeSubmitReq) (res *v1.RechargeSubmitRes, err error) {
	//两个id同一段时间只能提交一次
	gmlock.LockFunc(lock, func() {
		result, _ := cache.NewCache().Get(ctx, cache.PrefixAppleDuplicatedOrder.Key(req.MerchantId))
		if !pointer.IsNil(result) && !result.IsNil() {
			glog.Error(ctx, "订单正在处理，请勿重复推送", req)
			err = errHandler.WrapError(ctx, gcode.CodeOperationFailed, gerror.New("订单正在处理，请勿重复推送"), "订单正在处理，请勿重复推送")
		}
		//写入缓存
		_ = cache.NewCache().Set(ctx, cache.PrefixAppleDuplicatedOrder.Key(req.MerchantId), req.MerchantId, gtime.S*10)
	})
	if err != nil {
		return
	}
	sign := utils.TmpEncrypt(req.Attach + req.CardPass + gconv.String(req.TimeStamp))
	if sign != req.Sign {
		glog.Info(ctx, "校验错误", "原始签名", req.Sign, "计算签名", sign)
		err = errHandler.WrapError(ctx, gcode.CodeValidationFailed, gerror.New("校验错误"), "校验错误，请重新拉单填写")
		return
	}
	if !service.AppleOrder().ValidateCardPass(ctx, req.CardPass) {
		err = errHandler.WrapError(ctx, gcode.CodeValidationFailed, gerror.New("卡密校验错误"), "卡密校验错误，请检查卡密填写是否正确")
		return
	}
	//isDuplicated, msg := appleRechargeService.QueryDuplicatedCardPass(ctx, req.CardPass)
	//if isDuplicated {
	//	err = errHandler.WrapError(ctx, gcode.CodeValidationFailed, gerror.New(""), msg)
	//	return
	//}
	orderNo, err := service.AppleOrder().AddRechargeOrder(ctx, &model.AppleCardRechargeInput{
		Amount:            req.FaceValue,
		Balance:           req.FaceValue,
		RechargeSubmitReq: req,
	})
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeDbOperationError, err, "订单提交失败")
		return
	}
	return &v1.RechargeSubmitRes{
		Message: "订单提交成功，请等待充值",
		Status:  consts.AppleRechargeOrderSuccess,
		OrderNo: orderNo,
	}, err
}
