//
//  RCTQiYu.m
//  RCTQiYu
//
//  Created by JackYu on 16/8/30.
//  Copyright © 2016年 Netease. All rights reserved.
//

#import "RCTTongLianPay.h"
#import "RCTConvert.h"
#import "RCTBridge.h"
#import "RCTUIManager.h"
#import "RCTEventDispatcher.h"
#import "UIView+React.h"

#import <CommonCrypto/CommonCrypto.h>

@implementation RCTTongLianPay

@synthesize bridge = _bridge;

RCT_EXPORT_MODULE();

//RCT_EXPORT_METHOD(registerApp:(NSString*)appKey withSecret:(NSString*)appSecret) {
//    [SMSSDK registerApp:appKey withSecret:appSecret];
//}


//RCT_EXPORT_METHOD(getVerificationCodeByMethod:(NSInteger)method
//                  phoneNumber:(NSString *)phoneNumber
//                  zone:(NSString *)zone
//                  customIdentifier:(NSString *)customIdentifier
//                  //                  result:(RCTResponseErrorBlock)result) {
//                  callback:(RCTResponseErrorBlock)callback) {
//    
//    [SMSSDK getVerificationCodeByMethod:(SMSGetCodeMethod)method
//                            phoneNumber:phoneNumber
//                                   zone:zone
//                       customIdentifier:customIdentifier
//                                 result:^(NSError *error) {
//                                     NSMutableDictionary *body = [[NSMutableDictionary alloc] init];
//                                     if (error == NULL) {
//                                         body[@"code"] = @"0";
//                                     } else {
//                                         body[@"code"] = [NSString stringWithFormat: @"%ld", error.code];
//                                         NSDictionary *userInfo = [error userInfo];
//                                         body[@"message"] = [userInfo objectForKey:@"getVerificationCode"];
//                                     }
//                                     body[@"type"] = @"getVerificationCode.Resp";
//                                     
//                                     [self sendEventWithName:@"mobSMSEvent" body:body];
//                                     
//                                 }];
//}



//RCT_EXPORT_METHOD(commitVerificationCode:(NSString *)code
//                  phoneNumber:(NSString *)phoneNumber
//                  zone:(NSString *)zone
//                  //                  result:(SMSCommitCodeResultHandler)result) {
//                  callback:(RCTResponseErrorBlock)callback) {
//    
//    [SMSSDK commitVerificationCode:code
//                       phoneNumber:phoneNumber
//                              zone:zone
//                            result:^(SMSSDKUserInfo *userInfo, NSError *error) {
//                                NSMutableDictionary *body = [[NSMutableDictionary alloc] init];
//                                if (error == NULL) {
//                                    body[@"code"] = @"0";
//                                } else {
//                                    body[@"code"] = [NSString stringWithFormat: @"%ld", error.code];
//                                    NSDictionary *userInfo = [error userInfo];
//                                    body[@"message"] = [userInfo objectForKey:@"commitVerificationCode"];
//                                }
//                                body[@"type"] = @"commitVerificationCode.Resp";
//                                
//                                [self sendEventWithName:@"mobSMSEvent" body:body];
//                            }];
//}


//- (instancetype)init
//{
//    self = [super init];
//    if (self) {
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleOpenURL:) name:@"RCTOpenURLNotification" object:nil];
//    }
//    return self;
//}
//
//- (void)dealloc
//{
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
//}

- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}

//RCT_EXPORT_METHOD(getViewController:(nonnull NSNumber *)reactTag
//                  resolver:(RCTPromiseResolveBlock)resolve
//                  rejecter:(RCTPromiseRejectBlock)reject)
//{
//    RCTUIManager *uiManager = self.bridge.uiManager;
//    dispatch_async(uiManager.methodQueue, ^{
//        [uiManager addUIBlock:^(RCTUIManager *uiManager, NSDictionary<NSNumber *,UIView *> *viewRegistry) {
//            UIView *view = viewRegistry[reactTag];
//            UIViewController *viewController = (UIViewController *)view.reactViewController;
//            resolve(nil);
//        }];
//    });
//}
//         

RCT_EXPORT_METHOD(createPayment:(NSDictionary *)payData)
{
    
    NSString *paaStr = @"{\n  \"orderAmount\" : \"3500\",\n  \"orderDatetime\" : \"20170314142826\",\n  \"version\" : \"v1.0\",\n  \"merchantId\" : \"008310107420059\",\n  \"productName\" : \"二维码\",\n  \"inputCharset\" : \"1\",\n  \"ext1\" : \"<USER>201606221001455<\\/USER>\",\n  \"orderNo\" : \"201703141428260000\",\n  \"payType\" : \"33\",\n  \"receiveUrl\" : \"http:\\/\\/www.ququapp.com\\/p2pmoney\\/index.php?d=api&c=common_base&m=order_receive\",\n  \"language\" : \"1\",\n  \"signType\" : \"1\",\n  \"orderCurrency\" : \"0\",\n  \"signMsg\" : \"46DAF72E46055BE8B1073BAEAB8CA6A8\"\n}";
        //[RCTTongLianPay formatPaa:payData];
    
    UIViewController* rootViewController = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
    
    [APay startPay:paaStr viewController:rootViewController delegate:self mode:@"01"];
}

+ (NSString *)formatPaa:(NSDictionary *)dict {
    
    NSMutableDictionary *mdic = [NSMutableDictionary dictionary];
    
    NSMutableString *paaStr = [[NSMutableString alloc] init];
    
    for (id key in dict) {
        id obj = [dict objectForKey:key];
        [paaStr appendFormat:@"%@=%@&", key,obj];
        mdic[key] = obj;
    }
    
    NSString *signMsg = [self md5:[paaStr substringToIndex:paaStr.length - 1]];
    mdic[@"signMsg"] = signMsg.uppercaseString;
    
    //############################  卡号回显请参考以下部分  ##############################################//
    
    //卡号回显需要在订单信息中传入该字段
    //该字段不参与订单信息的签名计算
    //若不需要卡号回显的功能该字段可不传入
    //    NSString *cardNo = @"4391880000000004";//测试用信用卡
    //                       @"6225882120759623";//测试用借记卡
    //    mdic[@"cardNo"] = cardNo;
    
    //##################################################################################################//
    
    //############################  外卡支付订单添加扩展信息字段  ###########################################//
    
    //    [mdic addEntriesFromDictionary:[self extPart]];
    
    //##################################################################################################//
    
    if (mdic[@"key"]) {
        //商户私有签名密钥 通联后台持有不传入插件
        [mdic removeObjectForKey:@"key"];
    }
    
    NSError *error;
    NSData *data = [NSJSONSerialization dataWithJSONObject:mdic options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonStr = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
    
    [paaStr setString:jsonStr];
    
    return paaStr;
}

//计算字符串对应的md5值
+ (NSString *)md5:(NSString *)string {
    
    NSLog(@"%@", string);
    
    if (string == nil) { return nil; }
    
    const char *str = [string cStringUsingEncoding:NSUTF8StringEncoding];
    CC_LONG strLen = (CC_LONG)[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
    unsigned char *result = calloc(CC_MD5_DIGEST_LENGTH, sizeof(unsigned char));
    CC_MD5(str, strLen, result);
    
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; ++i) {
        [hash appendFormat:@"%02x", result[i]];
    }
    
    free(result);
    
    return hash;
}

- (void)APayResult:(NSString *)result {
    NSLog(@"%@", result);
    NSArray *parts = [result componentsSeparatedByString:@"="];
    NSError *error;
    NSData *data = [[parts lastObject] dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableDictionary *body = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    
    body[@"type"] = @"PayReq.Resp";
    
    NSInteger payResult = [body[@"payResult"] integerValue];
    NSString *format_string = @"支付结果::支付%@";
    if (payResult == APayResultSuccess) {
        NSLog(format_string,@"成功");
    } else if (payResult == APayResultFail) {
        NSLog(format_string,@"失败");
    } else if (payResult == APayResultCancel) {
        NSLog(format_string,@"取消");
    }
    [self.bridge.eventDispatcher sendDeviceEventWithName:RCTTLEventName body:body];
}

@end
