//
//  NetTool.m
//  EESBCardSDKTest
//
//  Created by 雷俊博 on 2019/5/20.
//  Copyright © 2019 雷俊博. All rights reserved.
//

#import "NetTool.h"
#import "AppDelegate.h"
#import "NSDictionary+JsonStr.h"

@implementation NetTool

+(void)getSignStringWithParam:(NSDictionary *)param response:(NetResultBlock)resultBlock {
    AppDelegate*delegate  = (AppDelegate *)[UIApplication sharedApplication].delegate;
    NSData* data = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:nil];
    NSMutableData* myRequestData = [data mutableCopy];
    NSString *url = [NSString stringWithFormat:@"%@portal/token/sign",delegate.hostUrl];
    
    NSMutableURLRequest* request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
    [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:myRequestData];
     NSLog(@"request.URL %@",request.URL);
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!error) {
                NSString* jsonStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                NSDictionary *dic = [NSDictionary dictionaryWithJsonStr:jsonStr];
                NSString* str = dic[@"result"];
                NSLog(@"accessKey 签名信息:%@",str);
                if (resultBlock) {
                    resultBlock(str);
                }
            }else {
                NSLog(@"error.userInfo:  %@",error.userInfo);
            }
        });
    } ];
    [dataTask resume];
}


+ (void)getUserInfoWithParam:(NSDictionary*)param responseBlock:(NetResultBlock)resultBlock {
    //1.确定请求路径
    NSString *url = [NSString stringWithFormat:@"%@?",RealURL];
    
    for (NSString* key in param.allKeys) {
        
        if ([key isEqualToString:param.allKeys[0]]) {
            url =[url stringByAppendingString:[NSString stringWithFormat:@"%@=%@",key,param[key]]];
        } else {
            url =[url stringByAppendingString:[NSString stringWithFormat:@"&%@=%@",key,param[key]]];
        }
    }
    
    NSLog(@"url:%@",url);
    //2.创建请求对象
    NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:[url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%<>[\\]^`{|}\"]+"].invertedSet]]];
    
    //3.获取会话对象
    NSURLSession* session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error == nil) {
                //6.解析服务器返回的数据
                //说明：（此处返回的数据是JSON格式的，因此使用NSJSONSerialization进行反序列化处理）
                
                NSString* jsonStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                
                
                //jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\/" withString:@""];
                NSData* newdata = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
                NSMutableDictionary* newDict = [NSJSONSerialization JSONObjectWithData:newdata options:NSJSONReadingAllowFragments error:nil];
                if (newDict != nil) {
                    NSNumber *msgCode = newDict[@"state"];
                    NSString *msgString = newDict[@"describe"];
                    if ([[msgCode stringValue] isEqualToString:@"200"]) {
                        //成功解析result
                        
                        
                        NSString* token = newDict[@"result"];
                        if (resultBlock && EmptyString(token)) {
                            resultBlock(token);
                        }
                    } else {
                        // 失败提示
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:msgString delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                        [alert show];
                    }
                } else {
                    NSLog(@"error.userInfo  %@",error.userInfo);
                }
            }
        });
        
    } ];
    
    [dataTask resume];
}
@end
