//
//  OJAPayWXService.m
//  HiSports
//
//  Created by luxiaoming on 16/10/14.
//  Copyright © 2016年 com.ouj. All rights reserved.
//

#import "OJAPayWXService.h"
#import <WXApi.h>
#import "OJAPayManager.h"

@interface OJAPayWXService ()<WXApiDelegate>

@property (nonatomic, copy) OJAPayCompletion payCompletionBlock;

@end

@implementation OJAPayWXService

- (instancetype)init {
    self = [super init];
    if (self) {
        [WXApi registerApp:[OJAPayManager defaultManager].kWeChatAppKey];
    }
    return self;
}

- (BOOL)handleOpenUrl:(NSURL *)url {
    return [WXApi handleOpenURL:url delegate:self];
}

- (void)payForPreOrder:(OJAPayPreOrderModel *)preOrderModel completion:(OJAPayCompletion)completion {
    self.payCompletionBlock = completion;
    
    PayReq *request = [[PayReq alloc] init];
    request.partnerId = preOrderModel.partnerid;
    request.prepayId = preOrderModel.prepayid;
    request.package = preOrderModel.package;
    request.nonceStr = preOrderModel.noncestr;
    request.timeStamp = preOrderModel.timestamp;
    request.sign = preOrderModel.sign;
    [WXApi sendReq:request];
}


#pragma mark - WXApiDelegate

- (void)onResp:(BaseResp *)resp {
    if ([resp isKindOfClass:[PayResp class]]) {
        PayResp *payResponse = (PayResp *)resp;
        if (payResponse.errCode == WXSuccess) {
            if (self.payCompletionBlock) {
                self.payCompletionBlock(OJAPayTypeWeXin, nil);
            }
        } else {
            NSString *errorString = [NSString stringWithFormat:@"%@: %@", @(payResponse.errCode), payResponse.errStr];
            if (self.payCompletionBlock) {
                self.payCompletionBlock(OJAPayTypeWeXin, errorString);
            }
        }
        
    }
}

@end
