//
//  XXGIAPHelpManager.m
//  XXGIAPHelp
//
//  Created by kane on 2018/8/7.
//  Copyright © 2018年 kane. All rights reserved.
//

#import "XXGIAPHelpManager.h"
#import "XXGIAPConfig.h"
#import "NSError+XXGIAPError.h"
#import "XXGPlayKitConfig.h"
#import "ZBObjectiveCBeaver.h"

typedef void(^ReceiptBlock)(NSString *receipt);
@interface XXGIAPHelpManager()<SKPaymentTransactionObserver,SKProductsRequestDelegate,XXGIAPVerifyManagerDelegate>
{
    NSString *_appOrderID;
    NSString *_productIdentifier;
    NSString * _userId;
    XXGIAPTransactionModel *_currentModel;// StatePurchasing后才有
    BOOL _isBuyProdutTofetchList;
    SKReceiptRefreshRequest *_refreshRequest;
    ReceiptBlock _receiptBlock;
    BOOL _isUserAction;// 主动触发检测订单
}

/// 当前loading状态
@property (nonatomic, assign) XXGIAPLoadingStatus currentStatus;

/**
 * 获取商品列表请求.
 */
@property(nonatomic, weak) SKProductsRequest *currentProductRequest;

@end

static  XXGIAPHelpManager *manager = nil;
@implementation XXGIAPHelpManager

/**
 * 单例方法.
 */
+ (instancetype)sharedManager{

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [XXGIAPHelpManager new];
        [manager addNotificationObserver];
    });

    return manager;
}

/// 将本地模型转换成XXGIAPTransactionModel
/// @param models XXGIAPTransactionModel
- (void)resetKeychainService:( NSString * _Nullable )keychainService
             keychainAccount:( NSString * _Nullable )keychainAccount XXGIAPTransactionModels:(NSArray<XXGIAPTransactionModel *>*)models{
    if (!self.verifyManager) {
           self.verifyManager = [[XXGIAPVerifyManager alloc] initWithKeychainService:keychainService keychainAccount:keychainAccount];
           self.verifyManager.delegate = self;
       }
    [self.verifyManager savePaymentTransactionModels:models];

}

/**
 * 注册支付事务监听, 并且开始支付凭证验证队列.
 *
 * @warning ⚠️ 请在用户登录时和用户重新启动 APP 时调用.
 */
- (void)registerPay{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnonnull"
    [self registerPayWithKeychainService:nil keychainAccount:nil];
#pragma clang diagnostic pop
}
- (void)registerPayWithKeychainService:(NSString *)keychainService
              keychainAccount:(NSString *)keychainAccount{
    if (!self.verifyManager) {
        self.verifyManager = [[XXGIAPVerifyManager alloc] initWithKeychainService:keychainService keychainAccount:keychainAccount];
        self.verifyManager.delegate = self;
    }

    SKPaymentQueue *defaultQueue = [SKPaymentQueue defaultQueue];

    BOOL processExistingTransactions = false;
       if (defaultQueue != nil && defaultQueue.transactions != nil)
       {
           if ([[defaultQueue transactions] count] > 0) {
               processExistingTransactions = true;
           }
       }

       [defaultQueue addTransactionObserver:self];
       if (processExistingTransactions) {
           [self paymentQueue:defaultQueue updatedTransactions:defaultQueue.transactions];
       }

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
          [self checkUnfinishedTransaction:NO];
    });

    NSArray *keychainSet =[self.verifyManager fetchAllPaymentTransactionModel];
    [keychainSet enumerateObjectsUsingBlock:^(XXGIAPTransactionModel  * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        ZBLogInfo(__data_core.xxpk_log_iap_restore,idx+1,keychainSet.count,obj.xxpk_transactionStatus, obj.xxpk_toDic);
    }];
}

#pragma mark - IAP
/**
 * 获取产品信息.
 *
 * @param productIdentifier 产品标识.
 */
- (void)fetchProductInfoWithProductIdentifier:(NSString *)productIdentifier{
    NSError *error = nil;
    if (!_verifyManager) {
        error = [NSError errorWithXXGIAPCode:XXGIAPErrorCodeNotRegistered];

    }else if ([self hasUnfinishedTransaction]) {
        error = [NSError errorWithXXGIAPCode:XXGIAPErrorCodeHasUnfinishedTransaction];

    }else if (self.currentStatus != XXGIAPLoadingStatus_None) {
        error = [NSError errorWithXXGIAPCode:XXGIAPErrorCodePaying];

    }else if (!productIdentifier) {
        error = [NSError errorWithXXGIAPCode:XXGIAPErrorCodeProductId];
    }

    if (error) {
       if (_isBuyProdutTofetchList) {
           [self sendDelegateErrorMethod:@selector(onIAPPayFailue:withError:) error:error];
        }else{
           [self sendDelegateErrorMethod:@selector(onLaunProductListFinish:withError:) error:error];
            }
        return;
       }

    if (self.currentProductRequest) {
        [self.currentProductRequest cancel];
        self.currentProductRequest = nil;
    }

    _productIdentifier = productIdentifier;
    _isUserAction = YES;
        self.currentStatus = XXGIAPLoadingStatus_CheckingProduct;

        SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:productIdentifier]];
        self.currentProductRequest = request;
        request.delegate = self;
        [request start];

}

/**
 恢复购买
 */
- (void)restoreProducts{

    NSError *error = nil;
    if (!_verifyManager) {
     error = [NSError errorWithXXGIAPCode:XXGIAPErrorCodeNotRegistered];
    }else  if ([self hasUnfinishedTransaction]) {
              error = [NSError errorWithXXGIAPCode:XXGIAPErrorCodeHasUnfinishedTransaction];
    }else if (self.currentStatus != XXGIAPLoadingStatus_None) {
         error = [NSError errorWithXXGIAPCode:XXGIAPErrorCodePaying];
    }

    if (error) {
        [self sendDelegateErrorMethod:@selector(onIAPRestoreResult:withError:) error:error];
        return;
    }
    _isUserAction = YES;
        self.currentStatus = XXGIAPLoadingStatus_Restoring;
         [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];

}

- (void)buyProductWithUserID:(NSString *)userid
           productIdentifier:(NSString *)productIdentifier
                xxpk_orderId:(NSString *)xxpk_orderId{

      NSError *error = nil;


      if (!_verifyManager) {
       error = [NSError errorWithXXGIAPCode:XXGIAPErrorCodeNotRegistered];

      }else  if ([self hasUnfinishedTransaction]) {
              error = [NSError errorWithXXGIAPCode:XXGIAPErrorCodeHasUnfinishedTransaction];

          }else  if (self.currentStatus != XXGIAPLoadingStatus_None) {
           error = [NSError errorWithXXGIAPCode:XXGIAPErrorCodePaying];
          }else if (!productIdentifier || ! xxpk_orderId) {
        error = [NSError errorWithXXGIAPCode:XXGIAPErrorCodeParameter];

    }

    if (error) {
        [self sendDelegateErrorMethod:@selector(onIAPPayFailue:withError:) error:error];
        return;
    }
    _userId = userid;
    _productIdentifier =productIdentifier;
    _appOrderID = xxpk_orderId;
    _isBuyProdutTofetchList = YES;
    _isUserAction = YES;
    [self fetchProductInfoWithProductIdentifier:productIdentifier];


}

/**
 购买物品
@param payment SKPayment
 */
- (void)buyProductWithSKPayment:(SKPayment  *)payment{
    NSError *error = nil;
      if (!_verifyManager) {
       error = [NSError errorWithXXGIAPCode:XXGIAPErrorCodeNotRegistered];

      }else if ([self hasUnfinishedTransaction]) {
              error = [NSError errorWithXXGIAPCode:XXGIAPErrorCodeHasUnfinishedTransaction];

    }else if (self.currentStatus != XXGIAPLoadingStatus_None) {
           error = [NSError errorWithXXGIAPCode:XXGIAPErrorCodePaying];

     }

    if (error) {
        [self sendDelegateErrorMethod:@selector(onIAPPayFailue:withError:) error:error];
        return;
    }
     _isUserAction = YES;
    self.currentStatus = XXGIAPLoadingStatus_Paying;
        [[SKPaymentQueue defaultQueue] addPayment:payment];
}

- (BOOL)hasUnfinishedTransaction{
      NSArray *keychainSet =[self.verifyManager fetchAllPaymentTransactionModel];

    if (keychainSet.count > 0) {
        BOOL hasUnfinished = NO;
        for (XXGIAPTransactionModel *model in keychainSet) {
            // 只有以下状态被认为是"已完成"，不会阻止新支付：
            // - TransactionStatusAppleCancel (1): 苹果取消
            // - TransactionStatusWaitApple (0): 等待苹果
            // - TransactionStatusSeriverSucc (6): 服务器验证成功
            // - TransactionStatusSeriverFailed (5): 服务器验证失败（已处理完毕）
            if (model.xxpk_transactionStatus != TransactionStatusAppleCancel &&
                model.xxpk_transactionStatus != TransactionStatusWaitApple &&
                model.xxpk_transactionStatus != TransactionStatusSeriverSucc &&
                model.xxpk_transactionStatus != TransactionStatusSeriverFailed) {
                hasUnfinished = YES;
                break;
            }
        }
        return hasUnfinished;
    }else{
        return NO;
    }

}
- (NSArray *)getUnfinishTransactions{
      NSArray *keychainSet =[self.verifyManager fetchAllPaymentTransactionModel];
    return keychainSet;
}
-(void)checkUnfinishTransaction{
    [self checkUnfinishedTransaction:YES];
}
-(void)checkUnfinishedTransaction:(BOOL)userAction{

    if (self.verifyManager.isVerifing) {
        self.currentStatus = XXGIAPLoadingStatus_Verifying;
        return ;
    }
     _isUserAction = userAction;
    NSMutableArray *keychainSet =[self.verifyManager fetchAllPaymentTransactionModel];

    for (XXGIAPTransactionModel *model in keychainSet) {
        if (model.xxpk_transactionStatus == TransactionStatusSeriverSucc) {
            if (self.delegate &&[self.delegate respondsToSelector:@selector(onRedistributeGoodsFinish:)]) {
                    [self.delegate onRedistributeGoodsFinish:model];
                 [self finishTransationWithModel:model];
            }
        }else if (model.xxpk_transactionStatus == TransactionStatusSeriverError || model.xxpk_transactionStatus == TransactionStatusAppleSucc){
            // 验证订单
                self.currentStatus = XXGIAPLoadingStatus_Verifying;

            if (!model.xxpk_appStoreReceipt) {
                __weak  __typeof(self)  weakSelf = self;
                [self fetchTransactionReceiptData:^(NSString *receipt) {
                    model.xxpk_appStoreReceipt = receipt;
                    [weakSelf.verifyManager startPaymentTransactionVerifingModel:model];
                }];
            }else{
                    [self.verifyManager startPaymentTransactionVerifingModel :model];
            }

        }else if (model.xxpk_transactionStatus == TransactionStatusSeriverFailed){
            if (self.delegate &&[self.delegate respondsToSelector:@selector(onRedistributeGoodsFailue:withError:)]) {
                [self.delegate onRedistributeGoodsFailue:model withError:model.xxpk_error];
                [self.verifyManager deletePaymentTransactionModel:model];
            }
        }else if (model.xxpk_transactionStatus == TransactionStatusAppleFailed){

                if (self.delegate &&[self.delegate respondsToSelector:@selector(onIAPPayFailue:withError:)]) {
                             [self.delegate onIAPPayFailue:model withError:model.xxpk_error];
                             [self.verifyManager deletePaymentTransactionModel:model];
                         }
        }else if (model.xxpk_transactionStatus == TransactionStatusAppleCancel){

            if (model.xxpk_cancelStatusCheckCount == 3) {
                  [self.verifyManager deletePaymentTransactionModel:model];
            }else{
                  model.xxpk_cancelStatusCheckCount += 1;
                [self.verifyManager updatePaymentTransactionCheckCount:model];
            }

        }
    }
}

#pragma mark - SKProductsRequestDelegate
-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    ZBLogInfo(__data_core.xxpk_log_iap_product_feedback);
    NSArray *products =response.products;

    ZBLogInfo(__data_core.xxpk_log_iap_product_count, (int)[products count]);

    SKMutablePayment *payment = nil;
    NSString * price = nil;
    SKProduct *product = nil;
    NSString *code = nil;
    for (SKProduct *p in products) {
        ZBLogInfo(__data_core.xxpk_log_iap_product_title , p.localizedTitle);
        ZBLogInfo(__data_core.xxpk_log_iap_product_desc , p.localizedDescription);
        ZBLogInfo(__data_core.xxpk_log_iap_product_price , p.price);
        ZBLogInfo(__data_core.xxpk_log_iap_product_id , p.productIdentifier);


        NSString* currencySymbol = [p.priceLocale objectForKey:NSLocaleCurrencySymbol];// 这里获取到的就是货币符号，例如：￥、$等等
        NSString *currencyCode = [p.priceLocale objectForKey:NSLocaleCurrencyCode];// Code
//        NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc]init];
//        [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
//        [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
//        [numberFormatter setLocale:p.priceLocale];
//        NSString* formattedPrice = [numberFormatter stringFromNumber:p.price];// 这里获取到的就是货币符合和金额，例如：￥6.00，$0.99

        ZBLogInfo(__data_core.xxpk_log_iap_currency_info,currencyCode,currencySymbol);

        price =p.price.stringValue;
        code = [p.priceLocale objectForKey:NSLocaleCurrencyCode];
        if ([p.productIdentifier isEqualToString:_productIdentifier]) {
            payment = [SKMutablePayment paymentWithProduct:p];
            product = p;
        }
    }

    if (!_isBuyProdutTofetchList) {

        NSError *error = nil;
        self.currentStatus = XXGIAPLoadingStatus_None;
        if (self.delegate && [self.delegate respondsToSelector:@selector(onLaunProductListFinish:withError:)]) {
               if (!product) {
                     error = [NSError errorWithXXGIAPCode:XXGIAPErrorCodeProductId];

                      }
            dispatch_async(dispatch_get_main_queue(), ^{
                 [self.delegate onLaunProductListFinish:product withError:error];
            });

        }

        return;
    }


    if (payment) {

        NSDictionary *XXGIAPInfo = @{__data_core.xxpk_tools_iap_priceString:price,
                                     __data_core.xxpk_tools_iap_seriverOrder:_appOrderID,
                                     __data_core.xxpk_tools_iap_userId:_userId,
                                     __data_core.xxpk_tools_iap_codeString:code
        };

        payment.applicationUsername = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:XXGIAPInfo options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
          ZBLogInfo(__data_core.xxpk_log_iap_start_purchase , payment.productIdentifier,payment.applicationUsername);

        self.currentStatus = XXGIAPLoadingStatus_Paying;
       [[SKPaymentQueue defaultQueue] addPayment:payment];

    }else{
        NSError *error = [NSError errorWithXXGIAPCode:XXGIAPErrorCodeProductId];

        dispatch_async(dispatch_get_main_queue(), ^{
            [self sendDelegateErrorMethod:@selector(onIAPPayFailue:withError:) error:error];
            self.currentStatus = XXGIAPLoadingStatus_None;
        });
    }


}
#pragma mark - SKPaymentTransactionObserver



//监听购买结果
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transaction{
    for(SKPaymentTransaction *tran in transaction){
        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased:{

                [self verifyTransaction:tran];

            }
                break;
            case SKPaymentTransactionStatePurchasing:{

                   [self saveTransaction:tran];
            }
                break;
            case SKPaymentTransactionStateRestored:{
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
            }
                break;
            case SKPaymentTransactionStateFailed:{

                    [self endFailedTransaction:tran];

            }
                break;

            case SKPaymentTransactionStateDeferred:
            {
                ZBLogInfo(__data_core.xxpk_log_iap_transaction_deferred);
            }

                break;
            default:
                break;
        }
    }
}


- (void)verifyTransaction:(SKPaymentTransaction *)tran{

    NSString *order = tran.payment.applicationUsername;


    NSString *transactionIdentifier = tran.transactionIdentifier;
    if (!transactionIdentifier) {
        ZBLogInfo(__data_core.xxpk_log_iap_lost_transaction_id);
        transactionIdentifier = [NSUUID UUID].UUIDString;
    }
    ZBLogInfo(__data_core.xxpk_log_iap_purchase_complete,tran.payment.productIdentifier, order,(unsigned long)self.currentStatus);
  __weak  __typeof(self)  weakSelf = self;
       if (_currentModel ) {
           [self fetchTransactionReceiptData:^(NSString *receipt) {
               __strong  __typeof(self)  strongSelf = weakSelf;
               if (receipt == nil) {
                   strongSelf.currentStatus = XXGIAPLoadingStatus_None;
                   [strongSelf.verifyManager finishPaymentTransactionVerifingModel:self->_currentModel];
                   if (strongSelf.delegate && [strongSelf.delegate respondsToSelector:@selector(onIAPPayFailue:withError:)]) {
                                        [strongSelf.delegate onIAPPayFailue:strongSelf->_currentModel withError:tran.error];
                                 }
                   return ;
               }

               strongSelf->_currentModel.xxpk_appStoreReceipt = receipt;
               strongSelf->_currentModel.xxpk_transactionIdentifier =transactionIdentifier;

               if (strongSelf.delegate && [strongSelf.delegate respondsToSelector:@selector(onIAPPaymentSucess:)]) {
                                                                        [strongSelf.delegate onIAPPaymentSucess:strongSelf->_currentModel];
                                                                 }
               [strongSelf.verifyManager startPaymentTransactionVerifingModel:strongSelf->_currentModel];
           }];

        }else{
            ///以前未结束订单苹果返回处理
            XXGIAPTransactionModel *model = [XXGIAPTransactionModel xxpk_modelWithProductIdentifier:tran.payment.productIdentifier applicationUsername:order];
            [self fetchTransactionReceiptData:^(NSString *receipt) {
                    __strong  __typeof(self)  strongSelf = weakSelf;


                model.xxpk_appStoreReceipt = receipt;
                model.xxpk_transactionIdentifier = transactionIdentifier;
             if (strongSelf.delegate && [strongSelf.delegate respondsToSelector:@selector(onIAPPaymentSucess:)]) {
                                                                                     [strongSelf.delegate onIAPPaymentSucess:model];
            }
                [strongSelf.verifyManager startPaymentTransactionVerifingModel:model];
            }];

    }
}



- (void)saveTransaction:(SKPaymentTransaction *)tran{

    NSString *order = tran.payment.applicationUsername;
    ZBLogInfo(__data_core.xxpk_log_iap_add_products,tran.payment.productIdentifier,order);

    if (!order) {
        ZBLogInfo(__data_core.xxpk_log_iap_order_missing);
        return;
    }

    _currentModel =  [XXGIAPTransactionModel xxpk_modelWithProductIdentifier:tran.payment.productIdentifier applicationUsername:order];
    _currentModel.xxpk_transactionStatus = TransactionStatusWaitApple;
    [self.verifyManager appendPaymentTransactionModel:_currentModel];

}

- (void)endFailedTransaction:(SKPaymentTransaction *)tran{
    NSString *order = tran.payment.applicationUsername;
    ZBLogInfo(__data_core.xxpk_log_iap_transaction_failed, tran.payment.productIdentifier,order,tran.error);

    XXGIAPTransactionModel *currentModel= _currentModel;
    if (!_currentModel) {
        currentModel = [XXGIAPTransactionModel xxpk_modelWithProductIdentifier:tran.payment.productIdentifier applicationUsername:order];
    }
    currentModel.xxpk_error = tran.error;
    // 内购巨坑(如果用户是支付宝并且有验证码时,苹果会先取消订单然后再完成订单)
    if (tran.error.code == SKErrorPaymentCancelled) {
        currentModel.xxpk_transactionStatus = TransactionStatusAppleCancel;
         [self.verifyManager updatePaymentTransactionModelStatus:currentModel];
    }else{
        currentModel.xxpk_transactionStatus = TransactionStatusAppleFailed;
          [self.verifyManager deletePaymentTransactionModel:currentModel];
    }

    if (self.delegate && [self.delegate respondsToSelector:@selector(onIAPPayFailue:withError:)]) {
        [self.delegate onIAPPayFailue:currentModel withError:tran.error];
    }
    [[SKPaymentQueue defaultQueue] finishTransaction:tran];

    if (self.currentStatus != XXGIAPLoadingStatus_None && _currentModel) {
        self.currentStatus = XXGIAPLoadingStatus_None;
        _currentModel = nil;
    }

}
#pragma mark - IAPRestore

- (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue
{

        ZBLogInfo(__data_core.xxpk_log_iap_restore_received, (unsigned long)queue.transactions.count);

        NSMutableArray *storeResult= [NSMutableArray new];


        [queue.transactions enumerateObjectsUsingBlock:^(SKPaymentTransaction * _Nonnull transaction, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString *productID = transaction.payment.productIdentifier;
            [storeResult addObject:productID];
            ZBLogInfo(__data_core.xxpk_log_iap_restore_product_id,productID);
        }];
    self.currentStatus = XXGIAPLoadingStatus_None;
    if (self.delegate && [self.delegate respondsToSelector:@selector(onIAPRestoreResult:withError:)]) {
        [self.delegate onIAPRestoreResult:storeResult withError:nil];
    }

}
- (void)paymentQueue:(SKPaymentQueue *)queue restoreCompletedTransactionsFailedWithError:(NSError *)error{
     ZBLogInfo(__data_core.xxpk_log_iap_restore_error,error);
    self.currentStatus = XXGIAPLoadingStatus_None;
    if (self.delegate && [self.delegate respondsToSelector:@selector(onIAPRestoreResult:withError:)]) {
       [ self.delegate onIAPRestoreResult:nil withError:error];
    }
}



#pragma mark - Transation related

- (void)finishTransationWithModel:(XXGIAPTransactionModel *)model {

    NSString *transactionIdentifier = model.xxpk_transactionIdentifier;
    if (!transactionIdentifier) {
           [self.verifyManager deletePaymentTransactionModel:model];
        return;
    }
    // 未完成的列表.
    NSArray<SKPaymentTransaction *> *transactionsWaitingForVerifing = [[SKPaymentQueue defaultQueue] transactions];
    SKPaymentTransaction *targetTransaction = nil;
    for (SKPaymentTransaction *transaction in transactionsWaitingForVerifing) {
        if ([transactionIdentifier isEqualToString:transaction.transactionIdentifier]) {
            targetTransaction = transaction;
            break;
        }
    }

    ///如果没有找到对应的单据,并且只有一个未完成物品的productIdentifier与之匹配就能肯定是这个订单.
    if (transactionsWaitingForVerifing.count == 1) {
        SKPaymentTransaction *firstTransaction = transactionsWaitingForVerifing.firstObject;
        if ([firstTransaction.payment.productIdentifier isEqualToString:model.xxpk_productIdentifier]) {
            targetTransaction = firstTransaction;
        }
    }

    // 可能会出现明明有未成功的交易, 但是 transactionsWaitingForVerifing 就是没有值.
    // 此时应该将这笔已经完成的订单状态存起来, 等待之后苹果返回这笔订单的时候在进行处理.
    if (!targetTransaction) {

        ZBLogInfo(__data_core.xxpk_log_iap_order_verify_success, transactionIdentifier);
        [self.verifyManager updatePaymentTransactionModelStatus:model];
    }else {
        ZBLogInfo(__data_core.xxpk_log_iap_prepare_delete_order,model);
        [[SKPaymentQueue defaultQueue] finishTransaction:targetTransaction];
         [self.verifyManager deletePaymentTransactionModel:model];

    }
}

#pragma mark - XXGIAPVerifyManagerDelegate

- (void)startPaymentTransactionVerifingModel:(XXGIAPTransactionModel *)transactionModel{

      self.currentStatus = XXGIAPLoadingStatus_Verifying;
    // 发送到苹果服务器验证凭证
    __weak typeof(self) weakSelf = self;
    if (self.delegate && [self.delegate respondsToSelector:@selector(verifyWithModel:resultAction:)]) {
        [self.delegate verifyWithModel:transactionModel resultAction:^(XXGIAPVerifyResult result) {
            __strong  __typeof(self)  strongSelf = weakSelf;
            dispatch_async(dispatch_get_main_queue(), ^{

                ZBLogInfo(__data_core.xxpk_log_iap_verify_callback,transactionModel.xxpk_toDic);

            switch (result) {
                case XXGIAPVerifyValid:
                {
                    transactionModel.xxpk_transactionStatus = TransactionStatusSeriverSucc;
                    [strongSelf finishTransationWithModel:transactionModel];
                    strongSelf.currentStatus = XXGIAPLoadingStatus_None;

                    if (strongSelf->_currentModel && [strongSelf.delegate respondsToSelector:@selector(onDistributeGoodsFinish:)]) {


                            strongSelf->_currentModel = nil;

                        [strongSelf.delegate onDistributeGoodsFinish:transactionModel];

                    }else if ([strongSelf.delegate respondsToSelector:@selector(onRedistributeGoodsFinish:)]) {

                              [strongSelf.delegate onRedistributeGoodsFinish:transactionModel];

                    }

                }
                    break;
                case XXGIAPVerifyInvalid:
                {
                    transactionModel.xxpk_transactionStatus = TransactionStatusSeriverFailed;
                     [strongSelf finishTransationWithModel:transactionModel];
                    NSError *error = [NSError errorWithXXGIAPCode:XXGIAPErrorCodeVerifyInvalid];

                    if (strongSelf->_currentModel && [strongSelf.delegate respondsToSelector:@selector(onDistributeGoodsFailue:withError:)]) {

                            strongSelf.currentStatus = XXGIAPLoadingStatus_None;
                            strongSelf->_currentModel = nil;
                            [strongSelf.delegate onDistributeGoodsFailue:transactionModel withError:error];
                    }else  if ([strongSelf.delegate respondsToSelector:@selector(onRedistributeGoodsFailue:withError:)]) {

                                [strongSelf.delegate onRedistributeGoodsFailue:transactionModel withError:error];
                    }
                }
                    break;
                    case XXGIAPVerifyNeedRefreshReceipt:
                    {
                        transactionModel.xxpk_transactionStatus = TransactionStatusSeriverError;
                        NSError *error = [NSError errorWithXXGIAPCode:XXGIAPErrorCodeVerifyInvalid];
                        transactionModel.xxpk_appStoreReceipt = nil;
                        [self.verifyManager updatePaymentTransactionModelStatus:transactionModel];
                        if (strongSelf->_currentModel && [strongSelf.delegate respondsToSelector:@selector(onDistributeGoodsFailue:withError:)]) {

                                strongSelf.currentStatus = XXGIAPLoadingStatus_None;
                                strongSelf->_currentModel = nil;
                                [strongSelf.delegate onDistributeGoodsFailue:transactionModel withError:error];
                        }else  if ([strongSelf.delegate respondsToSelector:@selector(onRedistributeGoodsFailue:withError:)]) {

                                    [strongSelf.delegate onRedistributeGoodsFailue:transactionModel withError:error];
                        }
                    }
                        break;

                default:
                {
                    transactionModel.xxpk_transactionStatus = TransactionStatusSeriverError;
                    NSError *error = [NSError errorWithXXGIAPCode:XXGIAPErrorCodeVerifyInvalid];
                    if (strongSelf->_currentModel  && [strongSelf.delegate respondsToSelector:@selector(onDistributeGoodsFailue:withError:)]) {
                            strongSelf->_currentModel = nil;
                              [strongSelf.delegate onDistributeGoodsFailue:transactionModel withError:error];

                    }else  if ( [strongSelf.delegate respondsToSelector:@selector(onRedistributeGoodsFailue:withError:)]) {
                                [strongSelf.delegate onRedistributeGoodsFailue:transactionModel withError:error];
                    }
                }
            }
                [self.verifyManager finishPaymentTransactionVerifingModel:transactionModel];

                   self.currentStatus = XXGIAPLoadingStatus_None;
                self->_isUserAction = NO;
            });
        }];
    }
}

#pragma mark -  FetchTransactionReceipt

/**
 获取当前票据

 */
- (void)fetchTransactionReceiptData:(ReceiptBlock)result{

    NSURL *appStoreReceiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData = [NSData dataWithContentsOfURL:appStoreReceiptURL];
    NSString *receiptString=[receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    if(!receiptString){
        _refreshRequest= [[SKReceiptRefreshRequest alloc] initWithReceiptProperties:nil];
        _refreshRequest.delegate = self;
        _receiptBlock = result;
        [self->_refreshRequest start];
    }else{
        result(receiptString);
        if (_receiptBlock) {
            _receiptBlock = nil;
        }
    }
}

#pragma mark -  SKRequestDelegate
- (void)requestDidFinish:(SKRequest *)request {

        if ([request isKindOfClass:[SKReceiptRefreshRequest class]]) {
            ZBLogInfo(__data_core.xxpk_log_iap_receipt_refresh_success);
            if (_receiptBlock) {
                [self fetchTransactionReceiptData:_receiptBlock];
            }
        }


}
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    if ([request isKindOfClass:[SKReceiptRefreshRequest class]]) {
        ZBLogInfo(__data_core.xxpk_log_iap_receipt_refresh_error,error.localizedDescription);

        if (_receiptBlock) {
            if (_currentModel && error.code == 16) {
                _receiptBlock(nil);
                _receiptBlock = nil;
            }else{
                [self fetchTransactionReceiptData:_receiptBlock];
            }

        }
    }else if ([request isKindOfClass:[SKProductsRequest class]]){
        NSError *errorr = [NSError errorWithXXGIAPCode:XXGIAPErrorCodeNet];
               [self sendDelegateErrorMethod:@selector(onIAPPayFailue:withError:) error:errorr];
               self.currentStatus = XXGIAPLoadingStatus_None;
    }
}

#pragma mark - privateMethods


- (void)sendDelegateErrorMethod:(SEL)sel error:(NSError *)error{
    if (self.delegate && [self.delegate respondsToSelector:sel]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
           [self.delegate performSelector:sel withObject:nil withObject:error];
#pragma clang diagnostic pop
    }

}

- (void)changLoadingStatus:(XXGIAPLoadingStatus)status{
    if (XXGIAPConfig.enableLoading && _isUserAction) {
        // TODO:
    }
}

#pragma mark - Notification

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)addNotificationObserver {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForegroundNotification:) name:UIApplicationWillEnterForegroundNotification object:nil];

    [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(didReceiveApplicationWillTerminateNotification) name:UIApplicationWillTerminateNotification object:nil];
}

- (void)applicationWillEnterForegroundNotification:(NSNotification *)note {
    // 检查沙盒中没有持久化的交易.
    [self checkUnfinishedTransaction:NO];
}

- (void)didReceiveApplicationWillTerminateNotification {
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}


#pragma mark -  Getter && Setter

- (void)setCurrentStatus:(XXGIAPLoadingStatus)currentStatus{
    _currentStatus = currentStatus;
    if (_delegate && [_delegate respondsToSelector:@selector(currentStatus:)]) {
        [_delegate currentStatus:currentStatus];
    }
    [self changLoadingStatus:currentStatus];
}

/**
⚠️ 删除所有已储存订单
 */
- (void)cleanAllModels {
    [self.verifyManager cleanAllModels];
}
@end
