//
//  AFNetworkingClient.m
//  fastservice
//
//  Created by xuning on 5/5/25.
//  Copyright © 2025 FastService. All rights reserved.
//

#import "AFNetworkingClient.h"
#import "Header.h"

static NSString * const AFAppDotNetAPIBaseURLString = @"http://api.kfw.net";
static NSString * const AFAppDotNetAPIBaseURLString1 = @"http://apitest.kfw.net";

static NSString * const AFAppDotNetAPIBaseURLStringAPI1 = @"http://api1.kfw.net";
static NSString * const AFAppDotNetAPIBaseURLStringAPI2  = @"http://api2.kfw.net";
static NSString * const AFAppDotNetAPIBaseURLStringAPI3  = @"http://api3.kfw.net";


static BOOL _isUseableServer = YES;
static int sto_count = 0;   //超时计数
static int snu_count = 0;   //正常请求成功计数
static NSString * sg_privateNetworkBaseUrl = nil;
@implementation AFNetworkingClient


+ (instancetype)sharedClient {
    static AFNetworkingClient *_sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        //#warning - HuiDu SET 切换完成后 需要重启app
        _sharedClient = [[AFNetworkingClient alloc] init];
        
        _sharedClient.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
        
        _sharedClient.requestSerializer = [ AFHTTPRequestSerializer serializer ];
        //请求超时
        _sharedClient.requestSerializer.timeoutInterval = 30 * 1;
        [_sharedClient.requestSerializer setValue:[AppConfig cookie]  forHTTPHeaderField:@"Cookie"];
        _sharedClient. responseSerializer = [ AFHTTPResponseSerializer serializer ];
        
        //         _sharedClient.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
        [_sharedClient.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            switch (status) {
                case AFNetworkReachabilityStatusReachableViaWWAN:
                    DebugLog(@"-------AFNetworkReachabilityStatusReachableViaWWAN------");
                    [[NSNotificationCenter defaultCenter] postNotificationName:kAFNReloadData object:nil];
                    break;
                case AFNetworkReachabilityStatusReachableViaWiFi:
                    DebugLog(@"-------AFNetworkReachabilityStatusReachableViaWiFi------");
                    [[NSNotificationCenter defaultCenter] postNotificationName:kAFNReloadData object:nil];
                    break;
                case AFNetworkReachabilityStatusNotReachable:
                {
                    DebugLog(@"-------AFNetworkReachabilityStatusNotReachable------");
//                    [MBProgressHUD showMessage:@"无网络连接，请检查网络设置"];
                    [[NSNotificationCenter defaultCenter] postNotificationName:kAFNReloadData object:nil];
                    [[NSNotificationCenter defaultCenter] postNotificationName:kAFNNotReachable object:nil];
                }
                    break;
                default:
                    break;
            }
            
        }];
        [_sharedClient.reachabilityManager startMonitoring];
        
    });
    return _sharedClient;
}

#pragma mark
#pragma mark -服务器域名
+ (NSString *) baseURLString{
    NSString *url = AFAppDotNetAPIBaseURLString;
 
    if ([AppConfig getEnvironmentType] == 0) {
//        url = SERVER_ADDRESS ?  SERVER_ADDRESS : AFAppDotNetAPIBaseURLString;//正式环境
        url = AFAppDotNetAPIBaseURLString;//正式环境
    }
    else if ([AppConfig getEnvironmentType] == 1) {
        url = AFAppDotNetAPIBaseURLString1;//灰度环境
    }
    else if([AppConfig getEnvironmentType] == 2){
        url = AFAppDotNetAPIBaseURLStringAPI1;//api环境
    }
    else if([AppConfig getEnvironmentType] == 3){
        url = AFAppDotNetAPIBaseURLStringAPI2;//api环境
    }
    else if([AppConfig getEnvironmentType] == 4){
        url = AFAppDotNetAPIBaseURLStringAPI3;//api环境
    }
    else if([AppConfig getEnvironmentType] == 5){
        url = [AppConfig getLocalCache].sserver_address;//api环境
        
        if (StringIsNullOrEmpty(url)) {
            url = AFAppDotNetAPIBaseURLString;
            [AppConfig setEnvironmentType:0];
        }
    }else{
        url =  AFAppDotNetAPIBaseURLString;//正式环境
    }
    DebugLog(@"服务器域名：%@",sg_privateNetworkBaseUrl ? sg_privateNetworkBaseUrl : url);
    return sg_privateNetworkBaseUrl ? sg_privateNetworkBaseUrl : url;
}

#pragma mark
#pragma mark -GET 请求
- (NSURLSessionTask * )runGET:(NSString *)URLString
                   parameters:(NSMutableDictionary *)parameters
                      success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                      failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure{
    if (!parameters) {
        parameters = [[NSMutableDictionary alloc] init];
    }
    NSString *encoded = [self getParameters:parameters url:URLString method:@"GET"];
    
    return [self GET:encoded parameters:parameters headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [AFNetworkingClient successWithParameters:parameters encoded:encoded task:task responseObject:responseObject success:success];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [AFNetworkingClient failureWithParameters:parameters URLString:URLString task:task error:error failure:failure];
    }];
  
}

#pragma mark
#pragma mark -Post 请求
- (NSURLSessionTask * )runPost:(NSString *)URLString
                    parameters:(NSMutableDictionary *)parameters
                       success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                       failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure{
    if (!parameters) {
        parameters = [[NSMutableDictionary alloc] init];
    }
    NSString *encoded = [self getParameters:parameters url:URLString method:@"Post"];
    
    return [self POST:encoded parameters:parameters headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        [AFNetworkingClient successWithParameters:parameters encoded:encoded task:task responseObject:responseObject success:success];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        DebugLog(@"ddd----->%ld",error.code);
        [AFNetworkingClient failureWithParameters:parameters URLString:URLString task:task error:error failure:failure];
    }];
}

#pragma mark
#pragma mark -Post 请求
- (NSURLSessionTask * )runPut:(NSString *)URLString
                    parameters:(NSMutableDictionary *)parameters
                       success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                      failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure{
    if (!parameters) {
        parameters = [[NSMutableDictionary alloc] init];
    }
    NSString *encoded = [self getParameters:parameters url:URLString method:@"Put"];
    
    return [self PUT:encoded parameters:parameters headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [AFNetworkingClient successWithParameters:parameters encoded:encoded task:task responseObject:responseObject success:success];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [AFNetworkingClient failureWithParameters:parameters URLString:URLString task:task error:error failure:failure];
        
    }];
    
}

#pragma mark
#pragma mark DELETE请求
- (NSURLSessionTask *)runDELETE:(NSString *)URLString
                  parameters:(id)parameters
                     success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                     failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure {
    if (!parameters) {
        parameters = [[NSMutableDictionary alloc] init];
    }
   
    NSString *encoded = [self getParameters:parameters url:URLString method:@"DELETE"];

    return [self DELETE:encoded parameters:parameters headers:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        [AFNetworkingClient successWithParameters:parameters encoded:encoded task:task responseObject:responseObject success:success];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
       [AFNetworkingClient failureWithParameters:parameters URLString:URLString task:task error:error failure:failure];
    }];
}

//获取扩展后的参数
- (NSString *)getParameters:(NSMutableDictionary *)parameters url:(NSString *)URLString method:(NSString *)method{
    NSString *cookie = [AppConfig cookie];
    if (StringNotNullAndEmpty(cookie)) {
        [self.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
    }
    
    //设备类型
    [parameters setObject:@"ios_knight" forKey:@"device"];
    
    //设备版本
    int version = [[AppTools sharedAppTools] versionToIntValue];;
    [parameters setObject:@(version) forKey:@"version"];
    
    //设备device_token
    if (StringNotNullAndEmpty(theApp().token)) {
        [parameters setObject:theApp().token forKey:@"device_token"];
    }
    

    
    NSString *encoded = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    if (![encoded hasPrefix:@"http"]) {
        encoded = S(@"%@%@",[AFNetworkingClient baseURLString],URLString);
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [AFNetworkingClient appServerLow:parameters andAPI:URLString];
        });
    }
    
    //转码打印
    DebugLog(@"%@ ---请求参数：%@",encoded,[AppTools replaceUnicode:[parameters description]]);
    return encoded;
}

#pragma mark
#pragma mark -Post 请求如果慢 发送通知
+ (void)appServerLow:(NSMutableDictionary *)parameters andAPI:(NSString *)api {
    int inter_count =  3;
    if (!parameters[@"_isTimeOut"]) {
        sto_count = sto_count + (sto_count >= inter_count ? 0 : 1);
    }else if([parameters[@"_isTimeOut"] intValue]  == 1){
        snu_count = snu_count + (snu_count >= inter_count ? 0 : 1);
    }
    if ((sto_count >= inter_count || snu_count >= inter_count) && _isUseableServer) {
        NSString *isTimeOut = sto_count >= inter_count ? @"1" : snu_count >= inter_count ? @"0" : @"";
        [[NSNotificationCenter defaultCenter] postNotificationName:kAppServerLow object:nil userInfo:@{@"isTimeOut":S(@"%@",isTimeOut)}];
        sto_count = 0;
        snu_count = 0;
    }
}


#pragma mark
#pragma mark - 请求成功
+ (void)successWithParameters:(NSMutableDictionary *)parameters encoded:(NSString *)encoded task:(NSURLSessionDataTask *)task responseObject:(id) responseObject success:(void (^)(NSURLSessionDataTask *task, id responseObject))success{
    NSError *error;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
    
    NSDictionary *pDic = [[NSDictionary alloc] initWithDictionary:jsonObject];
    //转码打印
    DebugLog(@"%@\n%@ \n返回参数：%@ ",error ? error : @"", encoded,[AppTools replaceUnicode:[jsonObject description]]);
    
    if ([pDic[@"respcd"] isEqualToString:@"2100"] && ![AppConfig needLogin] && ![AFNetworkingClient noMessageAlert:encoded error:error]) {
        [TestClient dicMobClickStatistics:@"respcd2100" url:encoded];
        showAlertMessage(@"登录已经过期,请重新登录!");
        [[GlobalNetManager sharedGlobalNetManager] logout:nil];
    }
    
    if (success) {
        success(task,jsonObject);
    }
    _isUseableServer = YES;
    [parameters setObject:@(1) forKey:@"_isTimeOut"];
}

#pragma mark
#pragma mark - 失败
+ (void)failureWithParameters:(NSMutableDictionary *)parameters URLString:(NSString *)URLString task:(NSURLSessionDataTask *)task error:(NSError *)error failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure{
    NSString *error_info = [[NSString alloc] initWithData:error.userInfo[@"com.alamofire.serialization.response.error.data"] encoding:NSUTF8StringEncoding];
    DebugLog(@"\n服务器请求异常 %@ \nerror_info: %@ \nerror_code:%ld",URLString,error_info,(long)error.code);
    
    if ([AFNetworkingClient noMessageAlert:URLString error:error]) {
        DebugLog(@"-999 / geo.update");
    }else if (error.code == -1003){
//        [MBProgressHUD showMessage:@"线路繁忙，请重试！"];
        // TODO ! Warning
//        [AFNetworkingClient updateBaseURL:BACKUP_ADDRESS];
    }
    else{
        if (_isUseableServer) {
            sto_count = 0;
            snu_count = 0;
            _isUseableServer = NO;
            [[NSNotificationCenter defaultCenter] postNotificationName:kAppServerError object:nil];
        }
        [task cancel];
    #if DEBUG
        
    #else
//        [MBProgressHUD showMessage:S(@"网络出了点小状况，请稍后~ %ld",(long)error.code)];
    #endif
    }
    showIndicator(NO, nil, nil);
    if (failure) {
        failure(task,error);
    }
}

#pragma mark
#pragma mark - 更新域名
+ (void)updateBaseURL:(NSString *)baseURL{
    if (![baseURL isEqualToString:sg_privateNetworkBaseUrl] && baseURL && baseURL.length) {
        sg_privateNetworkBaseUrl = baseURL;
    }
}

//不提醒用户的接口 或者 错误码
+ (BOOL)noMessageAlert:(NSString *)url error:(NSError *)error{
    DebugLog(@"noMessageAlert:%@",url);
    if (error.code == -999 || [url hasSuffix:SS_GEO_UPDATE] || [url hasSuffix:SS_40_INDEX]  || [url hasPrefix:SS_BAIDU]) {
        return YES;
    }
    return NO;
}


@end
