//
//  TWOCNetwork.m
//  TWOCNetwork
//
//  Created by fishxiaou on 2022/7/20.
//

#import "TWOCNetwork.h"
#import <AFNetworking/AFNetworking.h>

@implementation TWOCNetwork

static TWOCNetManager* _netManager = nil;

// 用户服务器域名
#define K_BaseService_URL @"http://fwloginintf.5mall.com"

// 基础请求单例
+(TWOCNetManager *) shareNetManager{
    static dispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
        _netManager = [[TWOCNetManager alloc] init];
    }) ;
    return _netManager;
}

- (instancetype)init {
    if (self = [super init]) {
        [self configBaseData];
    }
    return self;
}

-(instancetype)initUrl:(NSString *)reqUrl andParam:(NSDictionary *)reqParam {
    if (self = [super init]) {
        [self configBaseData];
        self.requestUrl = reqUrl;
        self.parameters = reqParam;
    }
    return self;
}

-(instancetype)initUrl:(NSString *)reqUrl andParam:(NSDictionary *)reqParam formDataParam:(NSDictionary<NSString *, NSArray<NSString *> *> *)formDataParam {
    if (self = [super init]) {
        [self configBaseData];
        self.requestUrl = reqUrl;
        self.parameters = reqParam;
        self.formDataParameters = formDataParam;
    }
    return self;
}


-(void)configBaseData{
    self.token = _netManager.token;
    self.baseURL = _netManager.baseURL;
    self.filePath = _netManager.filePath;
    self.businessFilePath = _netManager.businessFilePath;
    self.jsonContentType = _netManager.isJsonContentType;
    self.log = _netManager.log;
    self.baseParameters = _netManager.baseParameters;
    self.HTTPHeaders = _netManager.HTTPHeaders;
    self.pageNo = 0;
    self.pageSize = 0;
}

// Post请求
-(void)postRequest{
    NSString *preferredLanguage = [NSLocale preferredLanguages].firstObject;
    NSString *language = @"";
    if ([preferredLanguage containsString:@"en"] ) {
        language = @"en";
    }else{
        language = @"zh-cn";
    }
    NSString *requestUrlStr = [self.baseURL stringByAppendingPathComponent:self.requestUrl];
    NSLog(@"-->>>%@%@",self.baseURL,self.requestUrl);
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    // 请求
    if (self.isJsonContentType) {
        sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
        [sessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [sessionManager.requestSerializer setValue:@"Mozilla/5.0 (compatible; mobile; ios;android; twkj;)" forHTTPHeaderField:@"User-Agent"];
        [sessionManager.requestSerializer setValue:language forHTTPHeaderField:@"language"];
    }else{
        sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
        [sessionManager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [sessionManager.requestSerializer setValue:@"Mozilla/5.0 (compatible; mobile; ios;android; twkj;)" forHTTPHeaderField:@"User-Agent"];
        [sessionManager.requestSerializer setValue:language forHTTPHeaderField:@"language"];
    }
    // 响应
    sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    // 入参
    NSMutableDictionary *sendParam = [NSMutableDictionary dictionaryWithCapacity:20];
    if (self.baseParameters) {
        sendParam = [NSMutableDictionary dictionaryWithDictionary:self.baseParameters];
    }
    if (self.parameters) {
        for (NSString *dictKey in self.parameters.allKeys) {
            [sendParam setValue:self.parameters[dictKey] forKey:dictKey];
        }
    }
    
    if (self.pageSize > 0 ) {
        if (sendParam[@"pageSize"] == nil) {
            sendParam[@"pageSize"] = [NSNumber numberWithInteger:self.pageSize];
        }
    }
    
    if (self.pageNo > 0 ) {
        if (sendParam[@"pageNumber"] == nil) {
            sendParam[@"pageNumber"] = [NSNumber numberWithInteger:self.pageNo];
        }
    }
    
    //打印
    NSLog(@"本次请求参数【");
    NSLog(@"%@", sendParam);
    NSLog(@"】");
    //    __weak typeof(self) weakSelf = self;
    [sessionManager POST:requestUrlStr parameters:sendParam headers:self.HTTPHeaders progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * responseDict = responseObject;
        //        __strong typeof(self) strongSelf = weakSelf;
        if (responseDict == nil) {
            if (self.failCall) {
                self.failCall(-99, @"网络请求失败");
            }
            return;
        }
        NSLog(@"本次请求返回报文【");
        NSLog(@"%@", responseDict);
        NSLog(@"】");
        NSString *resultTag = responseDict[@"type"];
        
        //守护一下
        if ([resultTag isEqual:[NSNull null]]){
            self.failCall(0, @"Server Error");
            return;
        }
        
        if ([resultTag isEqualToString:@"success"]) {
            if (self.successCall) {
                self.successCall(responseDict);
            }
        }else{
            
            NSNumber *code = responseDict[@"code"];
            if (code.intValue == 401) {
                if (self.failCall) {
                    self.failCall(0, @"您的账号在其他设备登录请重新登陆");
                }
                NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
                [nc postNotificationName:@"LoginTokenPostError" object:nil userInfo:@{@"message":@"您的账号在其他设备登录请重新登陆"}];
                
                return;
            }
            
            NSString * message = responseDict[@"msg"];
            if (![message isEqual:[NSNull null]]){
              if (self.failCall) {
                self.failCall(0, message);
              }
            }else{
                self.failCall(0, @"Server Error");
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (self.failCall) {
            self.failCall(-99, error.description);
        }
    }];
}

// Get请求
-(void)GetRequest {
    NSString *preferredLanguage = [NSLocale preferredLanguages].firstObject;
    NSString *language = @"";
    if ([preferredLanguage containsString:@"en"] ) {
        language = @"en";
    }else{
        language = @"zh-cn";
    }
    NSString *requestUrlStr = [self.baseURL stringByAppendingPathComponent:self.requestUrl];
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    // 请求
    if (self.isJsonContentType) {
        sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
        [sessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [sessionManager.requestSerializer setValue:@"Mozilla/5.0 (compatible; mobile; ios;android; twkj;)" forHTTPHeaderField:@"User-Agent"];
        [sessionManager.requestSerializer setValue:language forHTTPHeaderField:@"language"];
    }else{
        sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
        [sessionManager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [sessionManager.requestSerializer setValue:@"Mozilla/5.0 (compatible; mobile; ios;android; twkj;)" forHTTPHeaderField:@"User-Agent"];
        [sessionManager.requestSerializer setValue:language forHTTPHeaderField:@"language"];
    }
    // 响应
    sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    // 入参
    NSMutableDictionary *sendParam = [NSMutableDictionary dictionaryWithCapacity:20];
    if (self.baseParameters) {
        sendParam = [NSMutableDictionary dictionaryWithDictionary:self.baseParameters];
    }
    if (self.parameters) {
        for (NSString *dictKey in self.parameters.allKeys) {
            [sendParam setValue:self.parameters[dictKey] forKey:dictKey];
        }
    }
    if (self.pageSize > 0 ) {
        if (sendParam[@"pageSize"] == nil) {
            sendParam[@"pageSize"] = [NSNumber numberWithInteger:self.pageSize];
        }
    }
    
    if (self.pageNo > 0 ) {
        if (sendParam[@"pageNumber"] == nil) {
            sendParam[@"pageNumber"] = [NSNumber numberWithInteger:self.pageNo];
        }
    }
    //    __weak typeof(self) weakSelf = self;
    [sessionManager GET:requestUrlStr parameters:sendParam headers:self.HTTPHeaders progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * responseDict = responseObject;
        NSLog(@"本次请求返回报文【");
        NSLog(@"%@", responseDict);
        NSLog(@"】");
        
        if (responseDict == nil) {
            if (self.failCall) {
                self.failCall(-99, @"网络请求失败");
            }
            return;
        }
        NSString *resultTag = responseDict[@"type"];
        //守护一下
        if ([resultTag isEqual:[NSNull null]]){
            self.failCall(0, @"Server Error");
            return;
        }
        if ([resultTag isEqualToString:@"success"]) {
            if (self.successCall) {
                self.successCall(responseDict);
            }
        }else{

            NSNumber *code = responseDict[@"code"];
            if (code.intValue == 401) {
                if (self.failCall) {
                    self.failCall(0, @"您的账号在其他设备登录请重新登陆");
                }
                NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
                [nc postNotificationName:@"LoginTokenPostError" object:nil userInfo:@{@"message":@"您的账号在其他设备登录请重新登陆"}];
                
                return;
            }
            
            NSString * message = responseDict[@"msg"];
            if (![message isEqual:[NSNull null]]){
              if (self.failCall) {
                self.failCall(0, message);
              }
            }else{
                self.failCall(0, @"Server Error");
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (self.failCall) {
            self.failCall(-99, error.description);
        }
    }];
}

// 获取用户池信息
- (void)sendConfigRequest {
    [self setBaseURL:K_BaseService_URL];
    NSString *requestUrlStr = [self.baseURL stringByAppendingPathComponent:self.requestUrl];
    NSLog(@"-->>>%@%@",self.baseURL,self.requestUrl);
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    // 请求
    if (self.isJsonContentType) {
        sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
        [sessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [sessionManager.requestSerializer setValue:@"Mozilla/5.0 (compatible; mobile; ios;android; twkj;)" forHTTPHeaderField:@"User-Agent"];
    }else{
        sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
        [sessionManager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [sessionManager.requestSerializer setValue:@"Mozilla/5.0 (compatible; mobile; ios;android; twkj;)" forHTTPHeaderField:@"User-Agent"];
    }
    // 响应
    sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    // 入参
    NSMutableDictionary *sendParam = [NSMutableDictionary dictionaryWithCapacity:20];
    if (self.baseParameters) {
        sendParam = [NSMutableDictionary dictionaryWithDictionary:self.baseParameters];
    }
    if (self.parameters) {
        for (NSString *dictKey in self.parameters.allKeys) {
            [sendParam setValue:self.parameters[dictKey] forKey:dictKey];
        }
    }
    
    if (self.pageSize > 0 ) {
        if (sendParam[@"pageSize"] == nil) {
            sendParam[@"pageSize"] = [NSNumber numberWithInteger:self.pageSize];
        }
    }
    
    if (self.pageNo > 0 ) {
        if (sendParam[@"pageNumber"] == nil) {
            sendParam[@"pageNumber"] = [NSNumber numberWithInteger:self.pageNo];
        }
    }
    //    __weak typeof(self) weakSelf = self;
    [sessionManager POST:requestUrlStr parameters:sendParam headers:self.HTTPHeaders progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * responseDict = responseObject;
        
        NSLog(@"本次请求返回报文【");
        NSLog(@"%@", responseDict);
        NSLog(@"】");
        //        __strong typeof(self) strongSelf = weakSelf;
        if (responseDict == nil) {
            if (self.failCall) {
                self.failCall(-99, @"网络请求失败");
            }
            return;
        }
        NSNumber *resultTag = responseDict[@"success"];
        if (resultTag.intValue == 2) {
            if (self.successCall) {
                self.successCall(responseDict);
            }
        }else{
            NSString * message = responseDict[@"message"];
            if (![message isEqual:[NSNull null]]){
              if (self.failCall) {
                self.failCall(0, message);
              }
            }else{
                self.failCall(0, @"Server Error");
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (self.failCall) {
            self.failCall(-99, error.description);
        }
    }];
}


// 注册用户池
- (void)sendRegisterRequest {
    NSString *requestUrlStr = self.requestUrl;
    NSLog(@"-->>>%@",self.requestUrl);
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    // 请求
    if (self.isJsonContentType) {
        sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
        [sessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [sessionManager.requestSerializer setValue:@"Mozilla/5.0 (compatible; mobile; ios;android; twkj;)" forHTTPHeaderField:@"User-Agent"];
    }else{
        sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
        [sessionManager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [sessionManager.requestSerializer setValue:@"Mozilla/5.0 (compatible; mobile; ios;android; twkj;)" forHTTPHeaderField:@"User-Agent"];
    }
    // 响应
    sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    // 入参
    NSMutableDictionary *sendParam = [NSMutableDictionary dictionaryWithCapacity:20];
    if (self.baseParameters) {
        sendParam = [NSMutableDictionary dictionaryWithDictionary:self.baseParameters];
    }
    if (self.parameters) {
        for (NSString *dictKey in self.parameters.allKeys) {
            [sendParam setValue:self.parameters[dictKey] forKey:dictKey];
        }
    }
    
    if (self.pageSize > 0 ) {
        if (sendParam[@"pageSize"] == nil) {
            sendParam[@"pageSize"] = [NSNumber numberWithInteger:self.pageSize];
        }
    }
    
    if (self.pageNo > 0 ) {
        if (sendParam[@"pageNumber"] == nil) {
            sendParam[@"pageNumber"] = [NSNumber numberWithInteger:self.pageNo];
        }
    }
    //    __weak typeof(self) weakSelf = self;
    [sessionManager POST:requestUrlStr parameters:sendParam headers:self.HTTPHeaders progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * responseDict = responseObject;
        
        NSLog(@"本次请求返回报文【");
        NSLog(@"%@", responseDict);
        NSLog(@"】");
        //        __strong typeof(self) strongSelf = weakSelf;
        if (responseDict == nil) {
            if (self.failCall) {
                self.failCall(-99, @"网络请求失败");
            }
            return;
        }
        NSNumber *resultTag = responseDict[@"code"];
        if (resultTag.intValue == 0) {
            if (self.successCall) {
                self.successCall(responseDict);
            }
        }else{
            NSString * message = responseDict[@"message"];
            if (![message isEqual:[NSNull null]]){
              if (self.failCall) {
                self.failCall(0, message);
              }
            }else{
                self.failCall(0, @"Server Error");
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (self.failCall) {
            self.failCall(-99, error.description);
        }
    }];
}

// 文件 上传
-(void)upLoadFile:(NSString *)localPath {
    
}

// 文件 下载
-(void)downLoadFile:(NSString *)fileUrl {
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    NSURL *URL = [NSURL URLWithString:fileUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        if (self.progressCall) {
            CGFloat progress = 100.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
            self.progressCall(progress);
        }
    } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        
        NSString *fileName = [response suggestedFilename];
        NSString *savePath = [self getFileDownloadPath:fileName];
        return [NSURL fileURLWithPath:savePath];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        
        if (error != nil) {
            if (self.failCall) {
                self.failCall(-99, error.description);
            }
        }else{
            if (self.successCall) {
                self.successCall(@{@"filePath":filePath});
            }
        }
    }];
    [downloadTask resume];
}

// 图片
-(void)upLoadImage:(UIImage *)upImage{
  
    NSData * imageData = UIImageJPEGRepresentation(upImage, 0.2);
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [sessionManager.requestSerializer setValue:@"multipart/form-data;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [sessionManager.requestSerializer setValue:@"Mozilla/5.0 (compatible; mobile; ios;android; fwpt;)" forHTTPHeaderField:@"User-Agent"];
    sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    
    NSLog(@"-->>>%@",self.filePath);
    
    NSString *fileName = [NSString stringWithFormat:@"%f.jpg",[[NSDate date] timeIntervalSince1970]];
    [sessionManager POST:self.filePath parameters:nil headers:self.HTTPHeaders constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"ige/jpg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (self.progressCall) {
            CGFloat progress = 100.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
            self.progressCall(progress);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *result = responseObject;
        NSLog(@"本次请求返回报文【");
        NSLog(@"%@", result);
        NSLog(@"】");
        NSString *successTag = result[@"type"];
        if ([successTag isEqualToString:@"success"]) {
            if (self.successCall) {
                self.successCall(result);
            }
        }else{
            if (self.failCall) {
                NSString * error = result[@"error"];
                self.failCall(0, error);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (self.failCall) {
            self.failCall(-99, error.description);
            NSLog(@"%@", error.description);
        }
    }];
}

-(void)upLoadFile:(NSData *)data
         fileName:(NSString *)fileName
          isImage:(BOOL)isImage {
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [sessionManager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [sessionManager.requestSerializer setValue:@"Mozilla/5.0 (compatible; mobile; ios;android; fwpt;)" forHTTPHeaderField:@"User-Agent"];
    sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    [sessionManager POST:self.filePath parameters:nil headers:self.HTTPHeaders constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (isImage) {
            [formData appendPartWithFileData:data name:@"file" fileName:[NSString stringWithFormat:@"IMG_%@.jpg",fileName] mimeType:@"image/jpeg"];
        } else {
            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@""];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (self.progressCall) {
            CGFloat progress = 100.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
            self.progressCall(progress);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *result = responseObject;
        NSString *successTag = result[@"success"];
        if ([successTag isEqualToString:@"success"]) {
            if (self.successCall) {
                self.successCall(result);
            }
        }else{
            if (self.failCall) {
                NSString * error = result[@"error"];
                self.failCall(0, error);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (self.failCall) {
            self.failCall(-99, error.description);
        }
    }];
}

-(NSString *) getFileDownloadPath:(NSString *)fileName {
    // 本地文件目录
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    NSString *dictoryPath = [docDir stringByAppendingPathComponent:@"TWFile"];
    // 检查目录、不存在就新增
    NSFileManager *fileManage = [NSFileManager defaultManager];
    BOOL fileExist = [fileManage fileExistsAtPath:dictoryPath];
    if (!fileExist) {
        [fileManage createDirectoryAtPath:dictoryPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    // 获取完整路径
    NSString *fileComponent = [fileName lastPathComponent];
    NSString *trueName = [fileComponent stringByDeletingPathExtension];
    NSString *trueExten = [fileComponent pathExtension];
    NSString *newName = [trueName stringByAppendingPathExtension:trueExten];
    NSString *savePath = [dictoryPath stringByAppendingPathComponent:newName];
    // 判断命名是否重复
    int suffix = 0;
    while ([fileManage fileExistsAtPath:savePath]) {
        suffix += 1;
        NSString *nowName = [trueName stringByAppendingString:[NSString stringWithFormat:@"_%d",suffix]];
        newName = [nowName stringByAppendingPathExtension:trueExten];
        savePath = [dictoryPath stringByAppendingPathComponent:newName];
    }
    return  savePath;
}

@end
