//
//  ApplePay.m
//  dsgdfhdfh
//
//  Created by 看看智能 on 2017/12/12.
//  Copyright © 2017年 peter. All rights reserved.
//

#import "ApplePay.h"

@implementation ApplePay


+ (ApplePay *)manager{
    static ApplePay *p = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        p =[[ApplePay alloc]init];
        
    });
    return p;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        [self removeOldTransaction];
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    }
    return self;
}
- (void)removeOldTransaction {
    
    NSArray *tansactions = [SKPaymentQueue defaultQueue].transactions;
    BOOL result = NO;
    
    if ( ![[NSUserDefaults standardUserDefaults] boolForKey:@"hasFinishOldTransaction"] && tansactions.count > 0) {
        for (SKPaymentTransaction *transaction in tansactions) {
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
        }
        result = YES;
    }
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"hasFinishOldTransaction"];
    if (result) {
        return;
    }
}
- (void)launch {
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    

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



-(void)buyProductsWithId:(NSString *)productsId and:(NSString*)ID andList:(NSString*)listID
{
    self.ID =ID;
    self.productID =productsId;
    self.ListID  =listID;
    
    [self launch];
    [self kaishi:productsId];
}
-(void)kaishi:(NSString*)productID{
    
    if([SKPaymentQueue canMakePayments]){
        
   
        [self requestProductID:[NSString stringWithFormat:@"%@",productID]];
        
    }else{
        [SVProgressHUD doneShow];
        [SVProgressHUD dismiss];
        UIAlertView *alertError = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                             message:@"请先开启应用内付费购买功能。"
                                                            delegate:nil
                                                   cancelButtonTitle:@"确定"
                                                   otherButtonTitles: nil];
        [alertError show];
        
    }
}
-(void)requestProductID:(NSString *)productID{
    
    NSArray *productIDArray = [[NSArray alloc]initWithObjects:productID, nil];
    NSSet *sets = [[NSSet alloc]initWithArray:productIDArray];
    

    SKProductsRequest *sKProductsRequest = [[SKProductsRequest alloc]initWithProductIdentifiers:sets];
    sKProductsRequest.delegate = self;
    [sKProductsRequest start];
    
}
-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    
    
    NSArray *product = response.products;
    if([product count] == 0){
        
        return;
    }
    
    for (SKProduct *sKProduct in product) {
       
        
        
        if([sKProduct.productIdentifier isEqualToString:self.productID]){
            
            [self buyProduct:sKProduct];
            
            break;
            
        }else{
            
        }
    }
    
}

-(void)buyProduct:(SKProduct *)product{
    
    SKPayment *skpayment = [SKPayment paymentWithProduct:product];
    
    [[SKPaymentQueue defaultQueue] addPayment:skpayment];
}

-(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions{
    


    
   
    for (SKPaymentTransaction *transaction in transactions) {
        switch (transaction.transactionState) {
            case SKPaymentTransactionStatePurchasing:{
                

                
                
      
            }break;
            case SKPaymentTransactionStatePurchased:{
           
         
                [queue finishTransaction:transaction];
                [self buyAppleStoreProductSucceedWithPaymentTransactionp:transaction];
                
            }break;
            case SKPaymentTransactionStateFailed:{
                
                [queue finishTransaction:transaction];
                [SVProgressHUD doneShow];
                [SVProgressHUD dismiss];
                UIAlertView *alertError = [[UIAlertView alloc] initWithTitle:@"已取消购买"
                                                                     message:@"已取消购买.无法连接到iTunes Store"
                                                                    delegate:nil
                                                           cancelButtonTitle:@"确定"
                                                           otherButtonTitles: nil];
                [alertError show];
            }break;
            case SKPaymentTransactionStateRestored:{
                [queue finishTransaction:transaction];
               
                [SVProgressHUD doneShow];
                [SVProgressHUD dismiss];
            }break;
            case SKPaymentTransactionStateDeferred:{
                
            }break;
            default:
                break;
        }
    }
}
- (void)removeTransaction {
    
    [[SKPaymentQueue defaultQueue] finishTransaction:self.currentTransaction];
}
- (void)buyAppleStoreProductSucceedWithPaymentTransactionp:(SKPaymentTransaction *)paymentTransactionp {
    
//    NSString * productIdentifier = paymentTransactionp.payment.productIdentifier;
    NSString *transactionReceiptString= nil;
    
    NSString *version = [UIDevice currentDevice].systemVersion;
    if([version intValue] >= 7.0){
        NSURLRequest * appstoreRequest = [NSURLRequest requestWithURL:[[NSBundle mainBundle]appStoreReceiptURL]];
        NSError *error = nil;
        NSData * receiptData = [NSURLConnection sendSynchronousRequest:appstoreRequest returningResponse:nil error:&error];
        transactionReceiptString = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    }else{

        NSData * receiptData = paymentTransactionp.transactionReceipt;
        transactionReceiptString = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    }
    [self checkAppStorePayResultWithBase64String:transactionReceiptString];
    
}

- (void)checkAppStorePayResultWithBase64String:(NSString *)base64String {
    

    NSString *sandbox;
#if (defined(APPSTORE_ASK_TO_BUY_IN_SANDBOX) && defined(DEBUG))
    //sandbox = @(0);
    sandbox = @"0";
#else
    //sandbox = @(1);
    sandbox = @"1";
#endif
    
    NSMutableDictionary *prgam = [[NSMutableDictionary alloc] init];;
    [prgam setValue:sandbox forKey:@"sandbox"];
    [prgam setValue:base64String forKey:@"reciept"];
    
 
    [self verifyTransactionResult:nil];
}

- (void)verifyTransactionResult:(NSDictionary*)dicts
{
 
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
    NSLog(@"%@",receiptURL);
    NSData *receipt = [NSData dataWithContentsOfURL:receiptURL];

    
    if ([self.ListID isEqualToString:@""]) {
        self.ListID =[NSNull null];
    }
    
    
    [getAppleyPayGeogle  get:nil abd:self.ListID andBase64:[receipt base64EncodedStringWithOptions:0] andID:self.ID completionHandle:^(ApplePays *model, NSError *error) {
        if (error) {
            return;
        }
        if (model.code == 1018) {
        //成功
            [SVProgressHUD doneShow];
            [SVProgressHUD dismiss];
                 [[NSNotificationCenter defaultCenter]postNotificationName:@"KankanApplePay" object:@"success"];
            
        }else{
             [[NSNotificationCenter defaultCenter]postNotificationName:@"KankanApplePay" object:@"failure"];
            //失败
            [SVProgressHUD doneShow];
              [SVProgressHUD dismiss];
            NSString *str1 =@"";
            
            if (model.code == 1000) {
                str1 =@"参数为空,支付失败请联系客服4000021799";
            }else if(model.code == 1021){
                str1 =@"未找到订单,支付失败请联系客服4000021799";
            }else if(model.code == 1023){
                
                str1 =@"非法订单,支付失败请联系客服4000021799";
            }else if(model.code == 1025){
                
                str1 =@"订单查询失败,支付失败请联系客服4000021799";
            }else if(model.code == 9999){
                
                str1 =@"支付失败请联系客服4000021799";
            }else{
                str1 =@"支付失败请联系客服4000021799";
                
            }
            
            UIAlertView *alertError = [[UIAlertView alloc] initWithTitle:@"错误"
                                                                 message:str1
                                                                delegate:nil
                                                       cancelButtonTitle:@"确定"
                                                       otherButtonTitles: nil];
            [alertError show];
            
        }
        
        
        
    }];
    
    

}






@end
