//
//  IAPVerifyTransactionObj.m
//

#import "IAPVerifyTransactionObj.h"
#import "PayVM.h"
#import "KBAuthManager.h"
#import "KBHUD.h"
#import "KBLoginSheetViewController.h"

@interface IAPVerifyTransactionObj ()
@property (nonatomic, strong) PayVM *payVM;
@end

@implementation IAPVerifyTransactionObj

- (instancetype)init {
    if (self = [super init]) {
        _payVM = [PayVM new];
    }
    return self;
}

#pragma mark - FGIAPVerifyTransaction

- (void)pushSuccessTradeReultToServer:(NSString *)receipt
                           transaction:(SKPaymentTransaction *)transaction
                              complete:(FGIAPVerifyTransactionPushCallBack)handler {
    if (![self checkLogin]) { return; }

    NSLog(@"receipt = %@", receipt);

    NSInteger type = 0;
#if DEBUG
    type = 0;
#else
    type = 1;
#endif

    NSDictionary *params = @{ @"payment": @{ @"receipt": receipt ?: @"", @"type": @(type) } };

    __weak typeof(self) weakSelf = self;
    [self.payVM applePayReqWithParams:params needShow:NO completion:^(NSInteger sta, NSString * _Nullable msg) {
        [KBHUD dismiss];
        [KBHUD showInfo:(sta == KB_PAY_ERROR_CODE ? @"支付失败" : @"支付成功")];
        if (sta == KB_PAY_SUCC_CODE) {
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
            if (handler) handler(@"成功", nil);
        } else {
            if (handler) handler(@"失败", nil);
        }
        (void)weakSelf; // keep self during block life if needed
    }];
}

#pragma mark - Helpers

- (BOOL)checkLogin {
    BOOL loggedIn = [[KBAuthManager shared] isLoggedIn];
    if (!loggedIn) {
        dispatch_async(dispatch_get_main_queue(), ^{
            UIViewController *top = [UIViewController kb_topMostViewController];
            if (top) { [KBLoginSheetViewController presentIfNeededFrom:top]; }
        });
        return NO;
    }
    return YES;
}

@end

