//
//  AMapNavHttpUtil.m
//  AMapNavIOSSDK
//
//  Created by admin on 2026/2/11.
//

#import "AMapNavHttpUtil.h"

#define AMapRequestMethod_POST @"POST"

@interface AMapNavHttpUtil ()
@property (nonatomic , copy) NSString * baseURL;
@end

@implementation AMapNavHttpUtil

+ (instancetype)sharedInstance {
    static AMapNavHttpUtil *sharedInstance = nil;
    static dispatch_once_t onceToken;
    
    // dispatch_once确保下面的代码块只被执行一次
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
        // 可以在这里进行一些初始化操作
        
    });
    return sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        
//        if (sdk.config.developmentModel) {
//            _baseURL = kYTOTPAnalyticsSDKTestHost;
//        }else {
//            _baseURL = kYTOTPAnalyticsSDKProductionHost;
//        }
    }
    
    return self;
}


+ (void)postRequestWithURL:(NSString *)urlString parameters:(id)parameters requestHeader:(NSDictionary *)headParam  successHandler:(void (^)(NSDictionary *data, NSURLResponse *response))successHandler failureHandler:(void (    ^)(NSError *error))failureHandler {
    [self requestWithMethod:AMapRequestMethod_POST URL:urlString parameters:parameters requestHeader:headParam successHandler:successHandler failureHandler:failureHandler];
}


// 使用NSURLSession发起网络请求
+ (void)requestWithMethod:(NSString *)method URL:(NSString *)urlString parameters:(id)parameters requestHeader:(NSDictionary *)headParam successHandler:(void (^)(NSDictionary *data, NSURLResponse *response))successHandler failureHandler:(void (^)(NSError *error))failureHandler {
    if (!urlString) {
        return;
    }
    
    // 创建URL
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@" ,  urlString]];
    
    // 创建请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = method;
    request.timeoutInterval = 30.0;
    
    // 设置请求头，指定数据通讯格式为json
    if (headParam) {
        for (NSString *key in headParam.allKeys) {
            if (headParam[key]) {
                [request setValue:[NSString stringWithFormat:@"%@",headParam[key]] forHTTPHeaderField:key];
            }
        }
    }
    
    // 将参数转换为JSON数据
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error];
    if (!jsonData) {}
    
    if ([method isEqualToString: AMapRequestMethod_POST]) {
        // 设置请求体
        request.HTTPBody = jsonData;
    }
    
   __block  NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"request error:%@" , error);
            if (failureHandler) {
                failureHandler(error);
            }
        } else {
            if (successHandler) {
                NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
                if(dic){
                    NSLog(@"url: %@ , response data:%@",  url , dic);
                }
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    successHandler(dic, response);
                });
//                successHandler(dic, response);
            }
        }
        
        [session finishTasksAndInvalidate];
        session = nil;
    }];
    
    // 开始任务
    [task resume];
}


@end
