//
//  WXPay.m
//  JZPlus_RN
//
//  Created by 丁乐 on 2020/6/15.
//

#import "WXPay.h"
#import "WXApi.h"

@interface WXPay ()<WXApiDelegate>


//  成功的回调
@property (nonatomic,copy)RCTPromiseResolveBlock success;

//  失败的回调
@property (nonatomic,copy)RCTPromiseRejectBlock faild;

@end

@implementation WXPay

static WXPay *instance = nil;

+(instancetype)shareInstance{
    @synchronized(self) {
        if (instance == nil) {
            instance = [[WXPay alloc]init];
        }
    }
    return instance;
}


///  微信注册 appKey
/// @param appkey 开发平台注册的id
/// @param universalLink app相关的link
+(void)wechatRegister:(NSString *)appkey link:(NSString *)universalLink
{
  [WXApi registerApp:appkey universalLink:universalLink];
}

+(BOOL)applicationOpenUrl:(NSURL *)url{
    return [WXApi handleOpenURL:url delegate:[self shareInstance]];
}

/// 微信支付
/// @param data 微信支付的数据
/// @param success、faild 微信支付的回调
RCT_EXPORT_METHOD(wxpay:(NSDictionary *)data success:(RCTPromiseResolveBlock)success faild:(RCTPromiseRejectBlock)faild)
{
  self.success = success;
  self.faild = faild;
  
  if ([WXApi isWXAppInstalled] == NO){
    self.faild(@"未安装微信", @"未安装微信", nil);
    return;
  }
  
  //调起微信支付
  PayReq* req   = [[PayReq alloc] init];
  req.partnerId = [data objectForKey:@"partnerid"];
  req.prepayId  = [data objectForKey:@"prepayid"];
  req.nonceStr  = [data objectForKey:@"noncestr"];
  req.timeStamp = [[data objectForKey:@"timestamp"] intValue];
  req.package   = [data objectForKey:@"package"];
  req.sign      = [data objectForKey:@"sign"];
  
  if (req.partnerId == nil || req.prepayId == nil || req.nonceStr == nil || req.package == nil || req.sign == nil) {
    
    self.faild(@"参数错误", @"参数错误", nil);
    return;
  }
  
  [WXApi sendReq:req completion:^(BOOL success) {
    if (success == NO) {
      self.faild(@"调起微信支付失败", @"调起微信支付失败", nil);
    }
  }];
}


#pragma mark - WXApiDelegate
- (void)onResp:(BaseResp *)resp {
    
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去微信服务器端查询
        
        switch (resp.errCode) {
            case WXSuccess:
                self.success(@"支付成功");
                break;
                
            case WXErrCodeUserCancel:
                self.faild(@"用户取消！", @"用户取消！", nil);
                break;
                
            default:
                self.faild(@"支付失败！", @"支付失败！", nil);
                break;
        }
        
    }
}





@end
