//
//  SPHttpCenter.m
//  SharedParking
//
//  Created by gui_huan on 2018/3/26.
//  Copyright © 2018年 gui_huan. All rights reserved.
//

#import "SLHttpCenter.h"
#import "AFNetworking.h"
#import "SPRequestError.h"
#import <CoreTelephony/CTCellularData.h>
#define KTimeoutInterval 60;
static NSString *const kNOConnect = @"检测到没有网络";

@interface SLHttpCenter ()

@end

@implementation SLHttpCenter

static SLHttpCenter *handle;

- (void)getWithUrl:(NSString *)url
         parameter:(id)parameter
           success:(SuccessWithResult)success
           failure:(FailuerWithReason)failure{
    if (!handle.NetWorkIsOK) {
        [self netWorkConnectFailure:failure];
        return;
    }
    url = [url hasPrefix:@"http"] ? url : [NSString stringWithFormat:@"%@%@",self.serverUrl,url];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:parameter];
    NSString *userId = [SLGlobalInfo SharedInstance].loginInfo.user.userId;
    if (userId.length && ![dict objectForKey:@"userId"]) {
        [dict addEntriesFromDictionary:@{@"userId" : userId}];
    }
    [handle GET:url parameters:dict headers:@{} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self responseObjectEncodingWithJSONSerialization:responseObject success:success failure:failure url:url hub:nil];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self responseObjectEncodingWithJSONSerialization:error failure:failure url:url hub:nil];
    }];
}

- (void)postWithUrl:(NSString *)url
          parameter:(id)parameter
            success:(SuccessWithResult)success
            failure:(FailuerWithReason)failure{
    if (!handle.NetWorkIsOK) {
        [self netWorkConnectFailure:failure];
        return;
    }
    MBProgressHUD *hud = [self progressHUDHideWith:url];
    ///拼接
    url = [url hasPrefix:@"http"] ? url : [NSString stringWithFormat:@"%@%@",self.serverUrl,url];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:parameter];
    NSString *userId = [SLGlobalInfo SharedInstance].loginInfo.user.userId;
    if (userId.length && ![dict objectForKey:@"userId"]) {
        [dict addEntriesFromDictionary:@{@"userId" : userId}];
    }
    [handle POST:url parameters:dict headers:@{} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self responseObjectEncodingWithJSONSerialization:responseObject success:success failure:failure url:url hub:hud];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self responseObjectEncodingWithJSONSerialization:error failure:failure url:url hub:hud];
    }];
}

- (void)postWithUrl:(NSString *)url
               body:(id)body
            success:(SuccessWithResult)success
            failure:(FailuerWithReason)failure{
    if (!handle.NetWorkIsOK) {
        [self netWorkConnectFailure:failure];
        return;
    }
    MBProgressHUD *hud = [self progressHUDHideWith:url];
    ///拼接
    url = [url hasPrefix:@"http"] ? url : [NSString stringWithFormat:@"%@%@",self.serverUrl,url];
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:nil error:nil];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    // 设置body
    [request setHTTPBody:body];
    [[handle dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
        
    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
        
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            [self responseObjectEncodingWithJSONSerialization:responseObject success:success failure:failure url:url hub:hud];
        }else{
            [self responseObjectEncodingWithJSONSerialization:error failure:failure url:url hub:hud];
        }
    }] resume];
}

- (void)postWithSubmitUrl:(NSString *)url
                parameter:(NSDictionary *)parameter
           formDataHandel:(FormDataHandel)formDataHandel
                  success:(SuccessWithResult)success
                  failure:(FailuerWithReason)failure {
    if (!handle.NetWorkIsOK) {
        [self netWorkConnectFailure:failure];
        return;
    }
    MBProgressHUD *hud = [self progressHUDHideWith:url];
    ///拼接
    url = [url hasPrefix:@"http"] ? url : [NSString stringWithFormat:@"%@%@",self.serverUrl,url];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:parameter];
    [handle POST:url parameters:dict headers:@{} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (formDataHandel) {
            formDataHandel(formData);
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self responseObjectEncodingWithJSONSerialization:responseObject success:success failure:failure url:url hub:hud];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self responseObjectEncodingWithJSONSerialization:error failure:failure url:url hub:hud];
    }];
}


- (void)netWorkConnectFailure:(FailuerWithReason)failure{
    [ZFToast ShowWithMessage:@"网络无连接,请检查网络"];
    if (failure) {
        SPRequestError *errorCode = [SPRequestError errorWithReason:@"网络无连接"];
        failure(errorCode);
    }
    return;
}

- (void)responseObjectEncodingWithJSONSerialization:(NSError * _Nonnull)error
                                            failure:(FailuerWithReason)failure
                                                url:(NSString *)url
                                                hub:(MBProgressHUD *)hub{
    [self hideHudAnimateWith:hub];
    if (failure) {
        [ZFToast ShowWithMessage:@"网络请求失败"];
        NSString *decription = error.userInfo[@"NSLocalizedDescription"];
        NSLog(@"url:%@---%@",url,decription);
        SPRequestError *myError = [SPRequestError errorWithReason:decription errorCode:SPErrorCode_ConnectionError];
        failure(myError);
    }
}

- (void)responseObjectEncodingWithJSONSerialization:(id)responseObject
                                            success:(SuccessWithResult)success
                                            failure:(FailuerWithReason)failure
                                            url:(NSString *)url
                                            hub:(MBProgressHUD *)hub{
    
    
    [self hideHudAnimateWith:hub];

    NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
    NSLog(@"%@---->>>%@",url,str);
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    id resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSInteger status = [[resultDic objectForKey:kRequest_Status] integerValue];
    if (status != SPErrorCode_Success && [url containsString:self.serverUrl]) {
        if (failure) {
            NSString *errorMsg = [resultDic objectForKey:kRequest_Message];
            if (!errorMsg.length) {
                id data = [resultDic objectForKey:kRequest_Data];
                if (data && [data isKindOfClass:NSString.class]) {
                    errorMsg = data;
                }
            }
            [ZFToast ShowWithMessage: errorMsg ?: @"网络请求失败"];
//            SPRequestError *requestError = [SPRequestError errorWithReason:errorMsg errorCode:status];
            failure(resultDic);
            return ;
        }
    }
    if (success) {
        success(resultDic);
        return ;
    }
}

#pragma mark ---------检测网络
- (void)startMonitorNetWork
{
    CTCellularData *celluarData = [[CTCellularData alloc]init];
    celluarData.cellularDataRestrictionDidUpdateNotifier = ^(CTCellularDataRestrictedState state) {
        switch (state) {
            case kCTCellularDataRestrictedStateUnknown:
                NSLog(@"Restricrted Unknown");
                break;
            case kCTCellularDataRestricted:
                NSLog(@"Restricrted");
                break;
            case kCTCellularDataNotRestricted:
                NSLog(@"Not Restricrted");
                break;
                
            default:
                break;
        }
    };
    WEAKSELF
    
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        StrongWeakSelf;
        NetConnection connect = SPNoConnect;
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
            case AFNetworkReachabilityStatusNotReachable:
                connect =  SPNoConnect;
                stSelf.NetWorkIsOK = NO;
                //                挂起网络
                [handle.operationQueue setSuspended:YES];
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                //                恢复网络
                stSelf.NetWorkIsOK = YES;
                [handle.operationQueue setSuspended:NO];
                connect = SPPhoneConnect;
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                stSelf.NetWorkIsOK = YES;
                [handle.operationQueue setSuspended:NO];
                connect = SPWifiConnect;
                break;
            default:
                break;
        }
        if (connect == SPNoConnect) {
            [ZFToast ShowWithMessage:kNOConnect];
        }
        if (stSelf.ConnectStatusBlock) {
            stSelf.ConnectStatusBlock(connect);
        }
    }];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}

#pragma mark-----PropertyList
+(instancetype)SharedInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        handle = [SLHttpCenter manager];
        handle.responseSerializer = [AFHTTPResponseSerializer serializer];
        handle.requestSerializer = [AFJSONRequestSerializer serializer];
        handle.requestSerializer.timeoutInterval = KTimeoutInterval;
        [handle.requestSerializer setValue:@"IOS" forHTTPHeaderField:@"OS"];
        handle.NetWorkIsOK = YES;
        [handle startMonitorNetWork];
        handle.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png",@"application/octet-stream", @"text/json",@"application/x-www-form-urlencoded", nil];
    });
    return handle;
}

- (MBProgressHUD *)progressHUDHideWith:(NSString *)urlStr{
    MBProgressHUD *hud;
    if ([UIViewController getCurrentShowVC].view != nil) {
        hud  = [MBProgressHUD showHUDAddedTo:[UIViewController getCurrentShowVC].view animated:YES];
        return hud;
    }
    return nil;
}

- (void)hideHudAnimateWith:(MBProgressHUD *)hub{
    if (hub) {
        [hub hideAnimated:YES];
    }
}

- (void)dealloc {
    
}

@end
