#import "IAPManager.h"
#import "GameHelper.h"
#import "CrossPlatformCmd.h"

@implementation IAPManager

static IAPManager *instance;

+ (instancetype) Instance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[IAPManager alloc] init];
    });
    return instance;
}

-(void) Init{
    NSLog(@"AttachObserver");
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
}

-(BOOL) CanMakePayment{
    return [SKPaymentQueue canMakePayments];
}

-(void) BuyProduct:(NSString *)productIdentifier{
    NSArray *idArray = [productIdentifier componentsSeparatedByString:@"\t"];    NSSet *idSet = [NSSet setWithArray:idArray];
    [self sendRequest:idSet];
}

-(void) sendRequest:(NSSet *)idSet{
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:idSet];
    request.delegate = self;
    [request start];
}

-(void) productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    
    NSLog(@"-----------收到产品反馈信息--------------");
    NSArray *products = response.products;
    NSLog(@"产品Product ID:%@",response.invalidProductIdentifiers);
    NSLog(@"产品付费数量: %d", (int)[products count]);
    // populate UI
    
    for (SKProduct *p in products) {
        NSLog(@"product info");
        NSLog(@"SKProduct 描述信息%@", [products description]);
        NSLog(@"产品标题 %@" , p.localizedTitle);
        NSLog(@"产品描述信息: %@" , p.localizedDescription);
        NSLog(@"价格: %@" , p.price);
        NSLog(@"Product id: %@" , p.productIdentifier);
        
        NSString *productInfo = [NSString stringWithUTF8String:[[self productInfo:p] UTF8String]];
        SendPlatformMsgToUnity(UNITY_MSG_APPLE_SHOW_PRODUCT_CALLBACK, 0, 0, 0, productInfo, @"", @"");
    }
    
    for(NSString *invalidProductId in response.invalidProductIdentifiers){
        NSLog(@"Invalid product id:%@",invalidProductId);
    }
    
    SKProduct *pament = products.firstObject;
    SKPayment *payment = [SKPayment paymentWithProduct:pament];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}

-(NSString *)productInfo:(SKProduct *)product{
    NSArray *info = [NSArray arrayWithObjects:product.localizedTitle,product.localizedDescription,product.price,product.productIdentifier, nil];
    
    return [info componentsJoinedByString:@"\t"];
}

-(NSString *)transactionInfo:(SKPaymentTransaction *)transaction{
    //return [self encode:(uint8_t *)transaction.transactionReceipt.bytes length:transaction.transactionReceipt.length];
    //return [[NSString alloc] initWithData:transaction.transactionReceipt encoding:NSASCIIStringEncoding];
    NSURL *receiptUrl = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptUrl];
    NSString *receiptString = [receiptData base64EncodedStringWithOptions:0];
    return receiptString;
}

-(NSString *)encode:(const uint8_t *)input length:(NSInteger) length{
    static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    
    NSMutableData *data = [NSMutableData dataWithLength:((length+2)/3)*4];
    uint8_t *output = (uint8_t *)data.mutableBytes;
    
    for(NSInteger i=0; i<length; i+=3){
        NSInteger value = 0;
        for (NSInteger j= i; j<(i+3); j++) {
            value<<=8;
            
            if(j<length){
                value |=(0xff & input[j]);
            }
        }
        
        NSInteger index = (i/3)*4;
        output[index + 0] = table[(value>>18) & 0x3f];
        output[index + 1] = table[(value>>12) & 0x3f];
        output[index + 2] = (i+1)<length ? table[(value>>6) & 0x3f] : '=';
        output[index + 3] = (i+2)<length ? table[(value>>0) & 0x3f] : '=';
    }
    
    return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}

//沙盒测试环境验证
#define SANDBOX @"https://sandbox.itunes.apple.com/verifyReceipt"
//正式环境验证
#define AppStore @"https://buy.itunes.apple.com/verifyReceipt"
/**
 *  验证购买，避免越狱软件模拟苹果请求达到非法购买问题
 *
 */
-(void)verifyPurchaseWithPaymentTransaction{
    //从沙盒中获取交易凭证并且拼接成请求体数据
    NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl];
    
    NSString *receiptString=[receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];//转化为base64字符串
    
    NSString *bodyString = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", receiptString];//拼接请求数据
    NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    
    
    //测试的时候填写沙盒路径，上APPStore的时候填写正式环境路径
    NSURL *url=[NSURL URLWithString:SANDBOX];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod=@"POST";
    request.HTTPBody=bodyData;
    
    //使用 NSURLSession 发送异步请求
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
        if (error) {
            NSLog(@"验证购买过程中发生错误，错误信息：%@",error.localizedDescription);
            return;
        }
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",dic);
        if([dic[@"status"] intValue]==0){
            NSLog(@"购买成功！");
            NSDictionary *dicReceipt= dic[@"receipt"];
            
            NSLog(@"--------------%@",dicReceipt);
            //NSDictionary *dicInApp=[dicReceipt[@"in_app"] firstObject];
            for(NSDictionary  *tmp in dicReceipt[@"in_app"])
            {
                // NSLog(@"+++++++++++%@",dicInApp);
                NSString *productIdentifier = tmp[@"product_id"];//读取产品标识
                NSLog(@"+++++++++++++++++++++++++++++++++++++%@", productIdentifier);
                NSLog(@"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%@", self->productIndentify);
                //如果是消耗品则记录购买数量，非消耗品则记录是否购买过
                NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
                if ([productIdentifier isEqualToString:self->productIndentify]) {
                    NSInteger purchasedCount=[defaults integerForKey:productIdentifier];//已购买数量
                    [[NSUserDefaults standardUserDefaults] setInteger:(purchasedCount+1) forKey:productIdentifier];
                    UnitySendMessage("IOSIAPMgr", "BuyProcuctSucessCallBack",productIdentifier.UTF8String);
                    break;
                }else{
                    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:productIdentifier];
                    UnitySendMessage("IOSIAPMgr", "BuyProcuctSucessCallBack",productIdentifier.UTF8String);
                    break;
                }
                
            }
        }else{
            NSLog(@"购买失败，未通过验证！");
        }
    }];
    
    // 启动任务
    [task resume];
}

//监听购买结果
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transaction{
    for(SKPaymentTransaction *tran in transaction){
        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased:
                {
                    NSLog(@"交易完成");
                    NSURL *receiptUrl = [[NSBundle mainBundle] appStoreReceiptURL];
                    NSData *receiptData = [NSData dataWithContentsOfURL:receiptUrl];
                    NSString *receiptString = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];//转化为base64字符串
                    
                    SendPlatformMsgToUnity(UNITY_MSG_APPLE_PAY_CALLBACK, 1, 0, 0, receiptString, @"", @"");
                    
                    // 发送到苹果服务器验证凭证
                    //[self verifyPurchaseWithPaymentTransaction];
                    [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                }
                break;
            case SKPaymentTransactionStatePurchasing:
                {
                    NSLog(@"商品添加进列表");
                }
                break;
            case SKPaymentTransactionStateRestored:
                {
                    NSLog(@"已经购买过商品");
                    
                    [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                }
                break;
            case SKPaymentTransactionStateFailed:
                {
                    NSLog(@"交易失败");
                    SendPlatformMsgToUnity(UNITY_MSG_APPLE_PAY_CALLBACK, 0, 0, 0, @"", @"", @"");
                    [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                }
                break;
            default:
                {
                    [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                }
                break;
        }
    }
}

-(void) completeTransaction:(SKPaymentTransaction *)transaction{
    NSLog(@"Comblete transaction : %@",transaction.transactionIdentifier);
    NSString *transactionInfo = [NSString stringWithUTF8String:[[self transactionInfo:transaction] UTF8String]];
    SendPlatformMsgToUnity(UNITY_MSG_APPLE_COMPLETE_TRANSACTION_CALLBACK, 0, 0, 0, transactionInfo, @"", @"");
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

-(void) failedTransaction:(SKPaymentTransaction *)transaction{
    NSLog(@"Failed transaction : %@",transaction.transactionIdentifier);
    int errorCode = (int)transaction.error.code;
    SendPlatformMsgToUnity(UNITY_MSG_APPLE_FAILED_TRANSACTION_CALLBACK, errorCode, 0, 0, @"", @"", @"");
//    if (transaction.error.code != SKErrorPaymentCancelled) {
//        NSLog(@"!Cancelled");
//    }
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

-(void) restoreTransaction:(SKPaymentTransaction *)transaction{
    NSLog(@"Restore transaction : %@",transaction.transactionIdentifier);
    NSString *transactionIdentifier = transaction.transactionIdentifier;
    SendPlatformMsgToUnity(UNITY_MSG_APPLE_RESTORE_TRANSACTION_CALLBACK, 0, 0, 0, transactionIdentifier, @"", @"");
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

@end
