//
//  GBaseNetApi.m
//  TUIContact
//
//  Created by gan on 2025/3/24.
//

#import <Foundation/Foundation.h>
#import "GBaseNetApi.h"
#import "AFNetworking.h"
#import "AFNetworkReachabilityManager.h"
#import "UDManager.h"

@implementation GBaseNetApi


+ (GBaseNetApi *_Nonnull)shareInstance{
    static id gShareInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
      gShareInstance = [[self alloc] init];
    });
    return gShareInstance;
}

- (instancetype)init {
    if (self = [super init]) {
        _uploadTanck = [NSMutableArray new];
        _downloadTanck =[NSMutableArray new];
    }
    return self;
}



-(void)httpGet:(nullable id)parameters url:(NSString *)url succ:(GSucc)succ fail:(GFail)fail{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    NSString *acUrl=@"";
    if([url containsString:@"http"]){
        acUrl =url;
    }
    else{
        acUrl=[NSString stringWithFormat:@"%@%@",host,url];
    }
    NSLog(@"%@",acUrl);
    [manager GET:acUrl parameters:parameters  headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //
        if (succ) {
            succ(200,responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //
        if (fail) {
            fail(error);
        }
    }];
}

-(void)httpPost:(nullable id)parameters url:(NSString *)url succ:(GSucc)succ fail:(GFail)fail{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    NSString *acUrl=@"";
    if([url containsString:@"http"]){
        acUrl =url;
    }
    else{
        acUrl=[NSString stringWithFormat:@"%@%@",host,url];
    }
//    NSLog(@"%@",acUrl);
//    NSLog(@"%@",parameters);
    [manager POST:acUrl parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (succ) {
            succ(200,responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (fail) {
            fail(error);
        }
    }];
}

-(void)httpGetToken:(nullable id)parameters url:(NSString *)url succ:(GSucc)succ fail:(GFail)fail{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    NSString *token = (NSString *)[UDManager.shareInstance getSDManager:gkeytoken];
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@",token] forHTTPHeaderField:@"Authorization"];
    
    NSString *acUrl=@"";
    if([url containsString:@"http"]){
        acUrl =url;
    }
    else{
        acUrl=[NSString stringWithFormat:@"%@%@",host,url];
    }
    NSLog(@"%@",acUrl);
    [manager GET:acUrl parameters:parameters  headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //
        if (succ) {
            succ(200,responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //
        if (fail) {
            fail(error);
        }
    }];
}

-(void)httpPostToken:(nullable id)parameters url:(NSString *)url succ:(GSucc)succ fail:(GFail)fail{
        
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    NSString *token = (NSString *)[UDManager.shareInstance getSDManager:gkeytoken];
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@",token] forHTTPHeaderField:@"Authorization"];
    
    NSString *acUrl=@"";
    if([url containsString:@"http"]){
        acUrl =url;
    }
    else{
        acUrl=[NSString stringWithFormat:@"%@%@",host,url];
    }
    NSLog(@"%@",acUrl);
    NSLog(@"%@",parameters);
    [manager POST:acUrl parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (succ) {
            succ(200,responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (fail) {
            fail(error);
        }
    }];
}


-(void)httpPutToken:(nullable id)parameters url:(NSString *_Nullable)url succ:(GSucc _Nullable )succ fail:(GFail _Nullable )fail{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    NSString *token = (NSString *)[UDManager.shareInstance getSDManager:gkeytoken];
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@",token] forHTTPHeaderField:@"Authorization"];
    
    NSString *acUrl=@"";
    if([url containsString:@"http"]){
        acUrl =url;
    }
    else{
        acUrl=[NSString stringWithFormat:@"%@%@",host,url];
    }
//    NSLog(@"%@",acUrl);
//    NSLog(@"%@",parameters);
//    
    [manager PUT:acUrl parameters:parameters headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (succ) {
            succ(200,responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (fail) {
            fail(error);
        }
    }];
}

-(void)httpPatchToken:(nullable id)parameters url:(NSString *_Nullable)url succ:(GSucc _Nullable )succ fail:(GFail _Nullable )fail{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    NSString *token = (NSString *)[UDManager.shareInstance getSDManager:gkeytoken];
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@",token] forHTTPHeaderField:@"Authorization"];
    
    NSString *acUrl=@"";
    if([url containsString:@"http"]){
        acUrl =url;
    }
    else{
        acUrl=[NSString stringWithFormat:@"%@%@",host,url];
    }
    NSLog(@"%@",acUrl);
    NSLog(@"%@",parameters);
    
    [manager PATCH:acUrl parameters:parameters headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (succ) {
            succ(200,responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (fail) {
            fail(error);
        }
    }];
}

-(void)httpDelToken:(nullable id)parameters url:(NSString *_Nullable)url succ:(GSucc _Nullable )succ fail:(GFail _Nullable )fail{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    NSString *token = (NSString *)[UDManager.shareInstance getSDManager:gkeytoken];
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@",token] forHTTPHeaderField:@"Authorization"];
    
    NSString *acUrl=@"";
    if([url containsString:@"http"]){
        acUrl =url;
    }
    else{
        acUrl=[NSString stringWithFormat:@"%@%@",host,url];
    }
    NSLog(@"%@",acUrl);
    NSLog(@"%@",parameters);

    [manager DELETE:acUrl parameters:parameters headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (succ) {
            succ(200,responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (fail) {
            fail(error);
        }
    }];
}

-(void)upLoadWToken:(NSURL *_Nonnull)filePath succ:(GSucc _Nullable )succ fail:(GFail _Nullable )fail{
    
    NSData *fileData = [NSData dataWithContentsOfURL:filePath];
    NSLog(@"fileData:%lu",(unsigned long)fileData.length);
    NSLog(@"filePath.lastPathComponent:%@",filePath.lastPathComponent);
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer]; // 确保服务器返回的是原始数据，而非自动解析为JSON等
    NSString *token = (NSString *)[UDManager.shareInstance getSDManager:gkeytoken];
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@",token] forHTTPHeaderField:@"Authorization"];
    //[manager.requestSerializer setValue:[NSString stringWithFormat:@"multipart/form-data"] forHTTPHeaderField:@"Content-Type"];
    
    NSString *acUrl=[NSString stringWithFormat:@"%@%@",filehost,@"/common/upload"];
    
    // 上传文件，使用multipart/form-data类型（通常用于文件上传）
    [manager POST:acUrl parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            // 参数名称，服务器用来识别是哪个文件被上传
            [formData appendPartWithFileData:fileData name:@"file" fileName:filePath.lastPathComponent mimeType:@"multipart/form-data"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            // 上传进度处理
            NSLog(@"Percent Done: %lld %@", 100 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount, @" %");
        } success:^(NSURLSessionTask * _Nonnull task, id  _Nullable responseObject) {
            // 上传成功处理
            
            NSString *str =[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"Success: %@", str);
            NSMutableDictionary *jsonDict = [NSMutableDictionary dictionaryWithDictionary:[NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil]];
            [jsonDict jk_setObj:[self calculateFileSizeFromData:fileData] forKey:@"size"];
            NSLog(@"jsonDict:%@",jsonDict);
            if (succ) {
                succ(200,jsonDict);
            }
        } failure:^(NSURLSessionTask * _Nullable task, NSError * _Nonnull error) {
            // 上传失败处理
            if (fail) {
                fail(error);
            }
            NSLog(@"Error: %@", error);
        }];
}

- (void)uploadWithFilePath:(NSURL * )filePath thrid:(NSString *_Nullable)thrid progress:(FUploadProgress _Nullable)progress succ:(FSucc _Nullable )succ fail:(FFail _Nullable )fail{
    NSData *fileData = [NSData dataWithContentsOfURL:filePath];
    
    if (!fileData) {
        NSLog(@"----------读不到文件---------");
        return;
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer]; // 确保服务器返回的是原始数据，而非自动解析为JSON等
    NSString *token = (NSString *)[UDManager.shareInstance getSDManager:gkeytoken];
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@",token] forHTTPHeaderField:@"Authorization"];
    //[manager.requestSerializer setValue:[NSString stringWithFormat:@"multipart/form-data"] forHTTPHeaderField:@"Content-Type"];
    
    NSString *acUrl=[NSString stringWithFormat:@"%@%@",filehost,@"/common/upload"];
    NSLog(@"acUrl:%@",acUrl);
    NSURLSessionDataTask *uploadTack;
    // 上传文件，使用multipart/form-data类型（通常用于文件上传）
    uploadTack = [manager POST:acUrl parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            // 参数名称，服务器用来识别是哪个文件被上传
            [formData appendPartWithFileData:fileData name:@"file" fileName:filePath.lastPathComponent mimeType:@"multipart/form-data"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            // 上传进度处理
            NSLog(@"Percent Done: %lld %@", 100 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount, @" %");
//            if (progress) {
//                progress(uploadProgress);
//            }
            progress(thrid,uploadProgress);
        } success:^(NSURLSessionTask * _Nonnull task, id  _Nullable responseObject) {
            // 上传成功处理
            [self removeUploadTanckobj:thrid];
            NSString *str =[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"Success: %@", str);
            NSMutableDictionary *jsonDict = [NSMutableDictionary dictionaryWithDictionary:[NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil]];
            [jsonDict jk_setObj:[self calculateFileSizeFromData:fileData] forKey:@"size"];
//            NSLog(@"jsonDict:%@",jsonDict);
            if (succ) {
                succ(200,thrid,jsonDict);
            }
        } failure:^(NSURLSessionTask * _Nullable task, NSError * _Nonnull error) {
            // 上传失败处理
            [self removeUploadTanckobj:thrid];
            if (fail) {
                fail(thrid,error);
            }
            NSLog(@"Error: %@", error);
        }];
    
    uploadTack.priority = NSURLSessionTaskPriorityLow;
    [self addUploadTanckobj:uploadTack thrid:thrid];
}


//OSS返回上传进度的上传方法
- (void)uploadWithFilePathOSS:(NSURL *_Nullable)filePath thrid:(NSString *_Nullable)thrid progress:(FUploadProgress _Nullable )progress succ:(FSucc _Nullable )succ fail:(FFail _Nullable )fail{
    
    
    if([self isuploadTanck:thrid]){
        NSLog(@"---------isuploadTanck:%@",filePath);
        return;
    }
    
    NSData *fileData = [NSData dataWithContentsOfURL:filePath];
    
    if (!fileData) {
        [MBProgressHUD showWithText:@"獲取本地檔案失敗，請重新選擇檔案"];
        return;
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer]; // 确保服务器返回的是原始数据，而非自动解析为JSON等
    NSString *token = (NSString *)[UDManager.shareInstance getSDManager:gkeytoken];
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@",token] forHTTPHeaderField:@"Authorization"];
    //[manager.requestSerializer setValue:[NSString stringWithFormat:@"multipart/form-data"] forHTTPHeaderField:@"Content-Type"];
    
    NSString *acUrl=OSSfilehost;
    NSLog(@"acUrl:%@",acUrl);
    NSURLSessionDataTask *uploadTack;
    // 上传文件，使用multipart/form-data类型（通常用于文件上传）
    uploadTack = [manager POST:acUrl parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            // 参数名称，服务器用来识别是哪个文件被上传
            [formData appendPartWithFileData:fileData name:@"file" fileName:filePath.lastPathComponent mimeType:@"multipart/form-data"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            // 上传进度处理
            NSLog(@"Percent Done: %lld %@", 100 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount, @" %");
            if (progress) {
                progress(thrid,uploadProgress);
            }
            
        } success:^(NSURLSessionTask * _Nonnull task, id  _Nullable responseObject) {
            // 上传成功处理
            [self removeUploadTanckobj:thrid];
            NSString *str =[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"Success: %@", str);
            NSMutableDictionary *jsonDict = [NSMutableDictionary dictionaryWithDictionary:[NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil]];
            [jsonDict jk_setObj:[self calculateFileSizeFromData:fileData] forKey:@"size"];
//            NSLog(@"jsonDict:%@",jsonDict);
            if (succ) {
                succ(200,thrid,jsonDict);
            }
        } failure:^(NSURLSessionTask * _Nullable task, NSError * _Nonnull error) {
            // 上传失败处理
            [self removeUploadTanckobj:thrid];
            if (fail) {
                fail(thrid,error);
            }
            NSLog(@"Error: %@", error);
        }];
    
    uploadTack.priority = NSURLSessionTaskPriorityLow;
    [self addUploadTanckobj:uploadTack thrid:thrid];
}

-(void)upLoaddataWToken:(NSData *_Nonnull)data fileName:(NSString *_Nullable)fileName succ:(GSucc _Nullable )succ fail:(GFail _Nullable )fail{
    
  
    NSLog(@"fileData:%lu",(unsigned long)data.length);
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer]; // 确保服务器返回的是原始数据，而非自动解析为JSON等
    NSString *token = (NSString *)[UDManager.shareInstance getSDManager:gkeytoken];
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@",token] forHTTPHeaderField:@"Authorization"];
    //[manager.requestSerializer setValue:[NSString stringWithFormat:@"multipart/form-data"] forHTTPHeaderField:@"Content-Type"];
    
    NSString *acUrl=[NSString stringWithFormat:@"%@%@",filehost,@"/common/upload"];
    
    // 上传文件，使用multipart/form-data类型（通常用于文件上传）
    [manager POST:acUrl parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            // 参数名称，服务器用来识别是哪个文件被上传
            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"multipart/form-data"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            // 上传进度处理
            NSLog(@"Percent Done: %lld %@", 100 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount, @" %");
        } success:^(NSURLSessionTask * _Nonnull task, id  _Nullable responseObject) {
            // 上传成功处理
            
            NSString *str =[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"Success: %@", str);
            NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
            NSLog(@"jsonDict:%@",jsonDict);
            if (succ) {
                succ(200,jsonDict);
            }
        } failure:^(NSURLSessionTask * _Nullable task, NSError * _Nonnull error) {
            // 上传失败处理
            if (fail) {
                fail(error);
            }
            NSLog(@"Error: %@", error);
        }];
}

- (void)uploadWithFilePath:(NSArray <NSURL *>*)filePaths thrid:(NSString *_Nullable)thrid succ:(FSucc _Nullable )succ fail:(FFail _Nullable )fail{
    // 1. 创建AFHTTPSessionManager实例
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    NSString *acUrl=[NSString stringWithFormat:@"%@%@",filehost,@"/common/uploads"];
    
    // 2. 创建NSMutableURLRequest
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST"
                                                                                              URLString:acUrl
                                                                                             parameters:nil
                                                                              constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        // 3. 遍历所有文件URL并添加到formData
        for (NSURL *fileURL in filePaths) {
            NSError *error;
            NSString *fileName = [fileURL lastPathComponent];
            NSString *mimeType = [self mimeTypeForFileAtURL:fileURL];
            
            [formData appendPartWithFileURL:fileURL
                                       name:@"file" // 根据服务器API调整name字段
                                   fileName:fileName
                                   mimeType:mimeType
                                      error:&error];
            
            if (error) {
                NSLog(@"Error appending file: %@", error.localizedDescription);
            }
        }
    } error:nil];
    
    // 4. 创建上传任务
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request
                                                                       progress:nil
                                                              completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            if (fail) {
                fail(thrid,error);
            }
        } else {
            NSDictionary * responseDict = (NSDictionary *)responseObject;
            NSLog(@"批量上传返回数据：%@",responseObject);
            NSLog(@"批量上传返回msg：%@",responseDict[@"msg"]);
        }
    }];
    
    // 5. 开始上传任务
    [uploadTask resume];
}

// 根据文件扩展名获取MIME类型
- (NSString *)mimeTypeForFileAtURL:(NSURL *)fileURL {
    NSString *extension = [[fileURL pathExtension] lowercaseString];
    
    if ([extension isEqualToString:@"jpg"] || [extension isEqualToString:@"jpeg"]) {
        return @"image/jpeg";
    } else if ([extension isEqualToString:@"png"]) {
        return @"image/png";
    } else if ([extension isEqualToString:@"gif"]) {
        return @"image/gif";
    } else if ([extension isEqualToString:@"pdf"]) {
        return @"application/pdf";
    } else if ([extension isEqualToString:@"doc"]) {
        return @"application/msword";
    } else if ([extension isEqualToString:@"docx"]) {
        return @"application/vnd.openxmlformats-officedocument.wordprocessingml.document";
    } else if ([extension isEqualToString:@"xls"]) {
        return @"application/vnd.ms-excel";
    } else if ([extension isEqualToString:@"xlsx"]) {
        return @"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    } else if ([extension isEqualToString:@"ppt"]) {
        return @"application/vnd.ms-powerpoint";
    } else if ([extension isEqualToString:@"pptx"]) {
        return @"application/vnd.openxmlformats-officedocument.presentationml.presentation";
    } else if ([extension isEqualToString:@"txt"]) {
        return @"text/plain";
    } else if ([extension isEqualToString:@"mp4"]) {
        return @"video/mp4";
    } else if ([extension isEqualToString:@"mov"]) {
        return @"video/quicktime";
    } else {
        return @"application/octet-stream";
    }
}

-(void)downLoadFileWToken:(NSURL *_Nonnull)url thrid:(NSString *_Nullable)thrid succ:(GSucc _Nullable )succ fail:(GFail _Nullable )fail{
    
    if([self isDownloadTanck:thrid]){
       
        return;
    }
    
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
//        NSLog(@"%lld:%lld",downloadProgress.completedUnitCount,downloadProgress.totalUnitCount);
        CGFloat progres = downloadProgress.completedUnitCount/(double)downloadProgress.totalUnitCount;
//        NSLog(@"1111:%f",progres);
        if(succ){
//            NSLog(@"222222:%f",progres);
            CGFloat Pcode =progres*100;
//            NSLog(@"222222:%d",(int)Pcode);
            succ(Pcode,nil);
        }
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        NSString *fileName = [response suggestedFilename];
        NSString *fileExtension = [fileName pathExtension];
        NSString *newfileName = [NSString stringWithFormat:@"%@.%@", thrid,fileExtension];
        documentsDirectoryURL = [documentsDirectoryURL URLByAppendingPathComponent:newfileName];
        return documentsDirectoryURL;
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
//        NSLog(@"333:%@",filePath);
        [self removeDownloadTanckobj:thrid];
        if(error){//失败
            if(fail){
                fail(error);
            }
        }
        else{//成功
            if(succ){
                NSMutableString *mutableString = [NSMutableString stringWithString:filePath.absoluteString];
                // 删除所有 "file://" 字符
                [mutableString replaceOccurrencesOfString:@"file://" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [mutableString length])];
                NSString *strp = [NSString stringWithString:mutableString];
                NSDictionary *dic = @{
                    @"filePath":strp
                };
                succ(200,dic);
            }
        }
    }];
    task.priority = NSURLSessionTaskPriorityLow;
    [self addDownloadTanckobj:task thrid:thrid];
    [task resume];
}


- (NSString *)calculateFileSizeFromData:(NSData *)data {
    if (!data) {
        return @"0 B";
    }
    long long bytes = (long long)data.length;
    if (bytes < 1024) {
        return [NSString stringWithFormat:@"%lld B", bytes];
    } else if (bytes < 1024 * 1024) {
        float sizeInKB = (float)bytes / 1024;
        return [NSString stringWithFormat:@"%.2f KB", sizeInKB];
    } else if (bytes < 1024 * 1024 * 1024) {
        float sizeInMB = (float)bytes / (1024 * 1024);
        return [NSString stringWithFormat:@"%.2f MB", sizeInMB];
    } else {
        float sizeInGB = (float)bytes / (1024 * 1024 * 1024);
        return [NSString stringWithFormat:@"%.2f GB", sizeInGB];
    }
}

-(void)addUploadTanckobj:(NSURLSessionDataTask *)task thrid:(NSString *)thrid{
    NSDictionary *item = @{
        @"task":task,
        @"thrid":thrid
    };
    [_uploadTanck addObject:item];
}



-(BOOL)isuploadTanck:(NSString *)thrid{
    NSLog(@"stopUploadTanck-------------2");
    if(_uploadTanck.count>0){
        for (NSDictionary *item in _uploadTanck) {
            NSString *th = item[@"thrid"];
            NSLog(@"stopUploadTanck-------------3");
            if([th isEqualToString:thrid]){
                NSLog(@"stopUploadTanck-------------4");
                return true;
            }
        }
    }
    return false;
}

-(void)removeUploadTanckobj:(NSString *)thrid{
    if(_uploadTanck.count>0){
        for (NSDictionary *item in _uploadTanck) {
            NSString *th = item[@"thrid"];
            if([th isEqualToString:thrid]){
                [_uploadTanck removeObject:item];
                return;
            }
        }
    }
}

-(void)stopUploadTanck:(NSString *)thrid{
    NSLog(@"stopUploadTanck-------------2");
    if(_uploadTanck.count>0){
        for (NSDictionary *item in _uploadTanck) {
            NSString *th = item[@"thrid"];
            NSLog(@"stopUploadTanck-------------3");
            if([th isEqualToString:thrid]){
                NSURLSessionDataTask *task = item[@"task"];
                NSLog(@"stopUploadTanck-------------4");
                [task cancel];
                NSLog(@"stopUploadTanck-------------5");
                return;
            }
        }
    }
}


-(void)addDownloadTanckobj:(NSURLSessionTask *)task thrid:(NSString *)thrid{
    NSDictionary *item = @{
        @"task":task,
        @"thrid":thrid
    };
    [_downloadTanck addObject:item];
}


-(void)removeDownloadTanckobj:(NSString *)thrid{
    if(_downloadTanck.count>0){
        for (NSDictionary *item in _downloadTanck) {
            NSString *th = item[@"thrid"];
            if([th isEqualToString:thrid]){
                [_downloadTanck removeObject:item];
                return;
            }
        }
    }
}



-(BOOL)isDownloadTanck:(NSString *)thrid{
    NSLog(@"stopUploadTanck-------------2");
    if(_downloadTanck.count>0){
        for (NSDictionary *item in _downloadTanck) {
            NSString *th = item[@"thrid"];
            NSLog(@"stopUploadTanck-------------3");
            if([th isEqualToString:thrid]){
                NSLog(@"stopUploadTanck-------------4");
                return true;
            }
        }
    }
    return false;
}

@end

