//
//  uploadFileManager.m
//  隐私保护
//
//  Created by xd h on 2023/11/15.
//

#import "uploadFileManager.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "photosBackupsTaskModel.h"
@interface uploadFileManager ()
/**检测任务10s后 无反馈重新开始 */
@property (nonatomic, assign) NSInteger  taskRenewTime; //
@end

@implementation uploadFileManager
static uploadFileManager * cur_uploadFileShareInstance = nil;
+(uploadFileManager *)shareInstance;
{
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        cur_uploadFileShareInstance = [[uploadFileManager alloc] init];
        
    });
    
    return cur_uploadFileShareInstance;
}

- (id)init
{
    self = [super init];
    
    if (self) {
        //[self initManager];
    }
    
    return self;
}

#pragma mark 读取数据库数据
- (void)getDataInDatabaseFun:(BOOL)isReGet complete:(custom_complete_Arr)complete
{
    if(_databaseArr && _databaseArr.count == 3 && !isReGet){
        complete(_databaseArr);
        return;
    }
    
    if(!_databaseArr)
    {
        _databaseArr = [NSMutableArray new];
    }
    
    //KWeakSelf
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
        [uploadFileDataModel bg_findAsync:upLoadFile_image_tableName limit:0 orderBy:nil desc:NO complete:^(NSArray * _Nullable array) {
            NSMutableArray *failArr = [NSMutableArray new];
            NSMutableArray *doneArr = [NSMutableArray new];
            NSMutableArray *otherArr = [NSMutableArray new];
            
                for (uploadFileDataModel * curModel in array) {
                    
                    //图片 和视频 还原
                    if(curModel.curUploadFileType == uploadFileTypeImage){

                    }
                    else if(curModel.curUploadFileType == uploadFileTypeVideo){

                        if(curModel.curUploadStateType != uploadStateDone){
                    
                        }
                    }
                    
                    if(curModel.curUploadStateType == uploadStateFail){
                        [failArr addObject:curModel];
                    }
                    else if(curModel.curUploadStateType == uploadStateDone){
                        [doneArr addObject:curModel];
                    }
                    else{
                        [otherArr addObject:curModel];
                    }
                }
            
            NSLock *lock = [NSLock new];
            [lock lock];
            
            NSMutableArray *newArr = [NSMutableArray new];
            [newArr addObject:otherArr];
            [newArr addObject:doneArr];
            [newArr addObject:failArr];
            self->_databaseArr = newArr;
            
            [lock unlock];
            
            complete(self->_databaseArr);
        }];
    });

}

//把TZAssetModel 转成 我们需要上传的model
- (void)handlTZAssetModelToUploadFileDataFunBy:(NSMutableArray*)indexPathsForSelectedItems complete:(custom_complete_Arr)complete
{
    
    if(!indexPathsForSelectedItems && indexPathsForSelectedItems.count == 0){
        complete(nil);
        return;
    }
    
    if(!_fileModelDataArr){
        _fileModelDataArr = [NSMutableArray new];
    }
    
    _isNewAddTaskType = YES;
    
    self.curUploadModelNumbers = indexPathsForSelectedItems.count;
    
    NSMutableArray *newUploadTaskArr = [NSMutableArray new];
    
    NSLock *lock = [NSLock new];
    
    for (TZAssetModel * model in indexPathsForSelectedItems) {
        uploadFileDataModel * curModel = [uploadFileDataModel new];
        curModel.asset = model.asset;
        curModel.localIdentifier = model.asset.localIdentifier;
        
        BOOL isRepeatingTasksType = NO;
        [lock lock];
        //查询上传任务是否存在
        if(_databaseArr && _databaseArr.count == 3 ){
            NSMutableArray *uploadingArr = [[NSMutableArray alloc] initWithArray:_databaseArr[0]];
            for (uploadFileDataModel *preModel in uploadingArr) {
                if([preModel.localIdentifier isEqualToString:curModel.localIdentifier]){
                    isRepeatingTasksType = YES;
                    break;
                }
            }
        }
        [lock unlock];
        
        if(isRepeatingTasksType){
            continue;
        }
        
        curModel.imageData = model.imageData;
        curModel.videoData = model.videoData;
        curModel.filename = [model.asset valueForKey:@"filename"];
        //curModel.curUploadStateType = uploadStateWait;
        curModel.curUploadStateType = uploadStateUploading;
        
        if(model.type == TZAssetModelMediaTypeVideo){
            curModel.curUploadFileType = uploadFileTypeVideo;
            [cachesFileManager getFileNameWithContent:curModel.videoData fileName:curModel.filename type:uploadFileTypeVideo];
            
            
            //curModel.totalBytes = [model.videoData length];
            curModel.totalBytes = model.totalBytes;
            curModel.videoData = [NSData new];//视频文件存储到文件后内存清空
            
            NSString *imgName1 = [curModel.filename stringByReplacingOccurrencesOfString:@"." withString:@"_"];
            curModel.videoFirstImageName = [[NSString alloc] initWithFormat:@"%@.png",imgName1];
           
            //第一帧图片
            [[PHImageManager defaultManager] requestImageDataForAsset:curModel.asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
                    // 直接得到最终的 NSData 数据
                    if (imageData) {
                        curModel.imageData = imageData;
                        [cachesFileManager getFileNameWithContent:curModel.imageData fileName:curModel.videoFirstImageName type:uploadFileTypeImage];;
                    }
            }];

        }
        else{
            curModel.curUploadFileType = uploadFileTypeImage;
            curModel.totalBytes = model.totalBytes;
            
            if(curModel.imageData)
            {
                [cachesFileManager getFileNameWithContent:curModel.imageData fileName:curModel.filename type:uploadFileTypeImage];
            }
            else{
                
//                [[PHImageManager defaultManager] requestImageDataForAsset:curModel.asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
//                        // 直接得到最终的 NSData 数据
//                        if (imageData) {
//                            curModel.imageData = imageData;
//                            [cachesFileManager getFileNameWithContent:curModel.imageData fileName:curModel.filename type:uploadFileTypeImage];;
//                        }
//                }];
            }
           
        }
        
        //保存到数据库
        curModel.bg_tableName = upLoadFile_image_tableName;
        [newUploadTaskArr addObject:curModel];
        
    }
    
    KWeakSelf
    if(newUploadTaskArr.count == 0){
        [self getDataInDatabaseFun:YES complete:^(NSMutableArray * _Nonnull Arr) {
            complete(Arr);
            [weakSelf handleUploadFileModelBg_idFun:Arr];
        }];
    }
    else{
        [uploadFileDataModel bg_saveOrUpdateArrayAsync:newUploadTaskArr complete:^(BOOL isSuccess) {
            [weakSelf getDataInDatabaseFun:YES complete:^(NSMutableArray * _Nonnull Arr) {
                complete(Arr);
                [weakSelf handleUploadFileModelBg_idFun:Arr];
            }];
        }];
    }
}

#pragma mark 处理当前的model 加上bg_id
- (void)handleUploadFileModelBg_idFun:(NSMutableArray*)totalArr
{
    if(!totalArr || totalArr.count != 3){
        return;
    }
    
    _fileModelDataArr = totalArr[0];
    
    [self beginUploadFileFun];
}

- (void)beginUploadFileFun
{
//    if(_isUploadIngType && _reUploadIngSelectIndex <= 0){
//        return;
//    }
    
    if(_isSuspendType)
    {
        return;
    }
    
    _isUploadIngType = YES;
    
    
    _curUploadFileDataModel.imageData = nil;
    _curUploadFileDataModel.videoData = nil;
    _curUploadFileDataModel = nil;
    if(_reUploadIngSelectIndex > 0 && _reUploadIngSelectIndex < _fileModelDataArr.count){
        _curUploadFileDataModel = _fileModelDataArr[_reUploadIngSelectIndex];
    }
    else
    {
        _curUploadFileDataModel = _fileModelDataArr.firstObject;
        //_curUploadFileDataModel = _fileModelDataArr.lastObject;
    }
    
    //做个异常处理
    if(_databaseArr.count == 3 && _isNewAddTaskType){
        NSMutableArray *uploadIngArr = _databaseArr[0];
        if(_fileModelDataArr.count != uploadIngArr.count){
            _databaseArr[0] = _fileModelDataArr;
        }
    }
    
    
    if(!_curUploadFileDataModel){
        return;
    }
    
    
    if(_curUploadFileDataModel.curUploadFileType == uploadFileTypeImage){
        NSString*pathStr = [cachesFileManager getFilePathWithName:_curUploadFileDataModel.filename type:_curUploadFileDataModel.curUploadFileType];
        _curUploadFileDataModel.imageData = [NSData dataWithContentsOfFile:pathStr];
        
        if(_curUploadFileDataModel.imageData && _curUploadFileDataModel.imageData.length >0){
            if(_curUploadFileDataModel.totalBytes == 0){
                _curUploadFileDataModel.totalBytes = _curUploadFileDataModel.imageData.length;
            }
            
            [[NSNotificationCenter defaultCenter] postNotificationName:uploadFileBeginNotification object:_curUploadFileDataModel];
            return;
        }
        
    }
    else{
        //NSString*pathStr = [cachesFileManager getFilePathWithName:_curUploadFileDataModel.filename type:uploadFileTypeVideo];
        
        if([cachesFileManager checkFileIsSaveState:_curUploadFileDataModel.filename withType:uploadFileTypeVideo]){
        
            [[NSNotificationCenter defaultCenter] postNotificationName:uploadFileBeginNotification object:_curUploadFileDataModel];
            return;
        }
    }
    
    
    if(!_curUploadFileDataModel.asset){
        NSString *curLocalIdentifier = _curUploadFileDataModel.localIdentifier;
        PHFetchResult *fetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:@[curLocalIdentifier] options:nil];
        PHAsset *asset = fetchResult.firstObject;
        _curUploadFileDataModel.asset = asset;
    }
    
    if(!_curUploadFileDataModel.asset){
        [self getDataWrongToChangeFailFun];
        return;
    }
    
    KWeakSelf
    if(_curUploadFileDataModel.curUploadFileType == uploadFileTypeImage)
    {
        if(!_curUploadFileDataModel.imageData || _curUploadFileDataModel.imageData.length == 0){
            [[PHImageManager defaultManager] requestImageDataForAsset:_curUploadFileDataModel.asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
                    // 直接得到最终的 NSData 数据
                    if (imageData) {
                        self->_curUploadFileDataModel.imageData = imageData;
                        [weakSelf  afterGetImageDataFun];
                    }
                    else{
                        [weakSelf getDataWrongToChangeFailFun];
                    }
            }];
        }
    }
    else if(_curUploadFileDataModel.curUploadFileType == uploadFileTypeVideo){
        
        //第一帧图片
        [[PHImageManager defaultManager] requestImageDataForAsset:_curUploadFileDataModel.asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
                // 直接得到最终的 NSData 数据
                if (imageData) {
                    self->_curUploadFileDataModel.imageData = imageData;
                    [weakSelf  afterGetImageDataInVideoFun];
                }
        }];

        //真正的视频数据
        PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
        options.version = PHVideoRequestOptionsVersionOriginal;
        [[PHImageManager defaultManager] requestAVAssetForVideo:_curUploadFileDataModel.asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
            if ([asset isKindOfClass:[AVURLAsset class]]) {
                
                AVURLAsset* urlAsset = (AVURLAsset*)asset;
                
                BOOL isSuc = [cachesFileManager copyVideoItemAtPath:[urlAsset.URL path] fileName:_curUploadFileDataModel.filename error:nil];
                
                //NSData *videoData =  [NSData dataWithContentsOfURL:urlAsset.URL];
           
                if (isSuc) {
                    //self->_curUploadFileDataModel.videoData = videoData;
                    [weakSelf  afterGetVideoDataFun];
                }
                else{
                    [weakSelf getDataWrongToChangeFailFun];
                }
            }
            else{
                [weakSelf getDataWrongToChangeFailFun];
            }
        }];
    }
}

#pragma mark 获取数据失败 报错
- (void)getDataWrongToChangeFailFun
{
    [self changeUploadFileState:uploadStateFail withDidUploadBytes:_curUploadFileDataModel.didUploadBytes withModel:_curUploadFileDataModel complete:^(BOOL isSuccess) {
    }];
}

#pragma mark 根据 asset 获取到图片数据
- (void)afterGetImageDataFun
{
    [cachesFileManager getFileNameWithContent:_curUploadFileDataModel.imageData fileName:_curUploadFileDataModel.filename type:uploadFileTypeImage];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:uploadFileBeginNotification object:_curUploadFileDataModel];
}

- (void)afterGetImageDataInVideoFun
{
    [cachesFileManager getFileNameWithContent:_curUploadFileDataModel.imageData fileName:_curUploadFileDataModel.videoFirstImageName type:uploadFileTypeImage];
}

- (void)afterGetVideoDataFun
{
    [cachesFileManager getFileNameWithContent:_curUploadFileDataModel.videoData fileName:_curUploadFileDataModel.filename type:uploadFileTypeVideo];
    
    _curUploadFileDataModel.videoData = nil;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:uploadFileBeginNotification object:_curUploadFileDataModel];
}

//修改文件上传的状态
- (void)changeUploadFileState:(uploadStateType)curUploadStateType withDidUploadBytes:(long)didUpLoadBytes withModel:(uploadFileDataModel*)model  complete:(custom_complete_B)complete
{
    if(model.bg_id.integerValue != _curUploadFileDataModel.bg_id.integerValue){
        return;
    }
    
    self.taskRenewTime = [iTools getNowTimeStamp];
    
    _curUploadFileDataModel.curUploadStateType = curUploadStateType;
    _curUploadFileDataModel.didUploadBytes = didUpLoadBytes;
    
    if(curUploadStateType == uploadStateDone){
        
        NSString *uploadDefaultPath = [HWDataManager getStringWithKey:stringKeyAddSn(Const_photo_upload_default_path)];
        
        if([uploadDefaultPath containsString:@"mnt/media_rw"]){
            uploadDefaultPath = [uploadDefaultPath stringByReplacingOccurrencesOfString:@"mnt/media_rw" withString:NSLocalizedString(@"disk_Extra_default_tip",nil)];
        }
        else if([uploadDefaultPath containsString:@"storage/emulated/0"]){
            uploadDefaultPath = [uploadDefaultPath stringByReplacingOccurrencesOfString:@"storage/emulated/0" withString:NSLocalizedString(@"disk_phone_default_tip",nil)];
        }
        else if([uploadDefaultPath containsString:@"sdcard"]){
            uploadDefaultPath = [uploadDefaultPath stringByReplacingOccurrencesOfString:@"sdcard" withString:NSLocalizedString(@"disk_phone_default_tip",nil)];
        }
        
        _curUploadFileDataModel.savePath = uploadDefaultPath;
        
        _curUploadFileDataModel.videoData = [NSData new];
        
        if(_curUploadFileDataModel.curUploadFileType == uploadFileTypeVideo){
            [cachesFileManager removeItemAtPath:_curUploadFileDataModel.filename type:uploadFileTypeVideo error:nil];
        }
        
        [self->_fileModelDataArr removeObject:self->_curUploadFileDataModel];
        [self handleDatabaseArrDeteleInUploading:_curUploadFileDataModel];
        [self handleDatabaseArrByInDone:_curUploadFileDataModel];
    }
    else if(curUploadStateType == uploadStateFail){
        [self->_fileModelDataArr removeObject:self->_curUploadFileDataModel];
        [self handleDatabaseArrDeteleInUploading:_curUploadFileDataModel];
        [self handleDatabaseArrByInFail:_curUploadFileDataModel];
    }

    [_curUploadFileDataModel bg_saveOrUpdateAsync:^(BOOL isSuccess) {
        //HLog(@"%@ 写入 %@", model.filename, isSuccess ? @"成功":@"失败");
    }];
        
    
    if(!_isSuspendType || curUploadStateType != uploadStateSuspend){
        [[NSNotificationCenter defaultCenter] postNotificationName:uploadFileRefreshNotification object:model];
    }
    
    complete(YES);
    
    return;

//    NSString* where = nil;
//
//    where = [NSString stringWithFormat:@"where %@=%@ ",bg_sqlKey(@"bg_id"),bg_sqlValue(model.bg_id)];
//    //HLog(@"ffff:%@",_curUploadFileDataModel.bg_id);
//
//    KWeakSelf
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
//            [uploadFileDataModel bg_findAsync:upLoadFile_image_tableName where:where complete:^(NSArray * _Nullable array) {
//                for (uploadFileDataModel * curModel in array) {
//                    curModel.curUploadStateType = curUploadStateType;
//                    curModel.didUploadBytes = didUpLoadBytes;
//
//                    if(curUploadStateType == uploadStateDone){
//                        curModel.videoData = [NSData new];
//
//                        if(curModel.curUploadFileType == uploadFileTypeVideo){
//                            [cachesFileManager removeItemAtPath:curModel.filename type:uploadFileTypeVideo error:nil];
//                        }
//
//                        [weakSelf handleDatabaseArrByDelete:curModel];
//                        [weakSelf handleDatabaseArrByInDone:curModel];
//                    }
//                    else if(curUploadStateType == uploadStateFail){
//                        [weakSelf handleDatabaseArrByDelete:curModel];
//                        [weakSelf handleDatabaseArrByInFail:curModel];
//                    }
//
//                    [curModel bg_saveOrUpdateAsync:^(BOOL isSuccess) {
//                        //HLog(@"%@ 写入 %@", model.filename, isSuccess ? @"成功":@"失败");
//                    }];
//
//                }
//
//                complete(YES);
//            }];
//        });
//

}


- (void)handleDatabaseArrByDelete:(uploadFileDataModel*)delModel
{
    if(_databaseArr && _databaseArr.count == 3 ){
        
        NSMutableArray *uploadingArr = nil;
        
        if(delModel.curUploadStateType == uploadStateUploading
           ||delModel.curUploadStateType == uploadStateSuspend){
            uploadingArr = _databaseArr[0];
        }
        else if(delModel.curUploadStateType == uploadStateDone)
        {
            uploadingArr = _databaseArr[1];
        }
        else{
            uploadingArr = _databaseArr[2];
        }
        
        [uploadingArr removeObject:delModel];
    }
}

- (void)handleDatabaseArrDeteleInUploading:(uploadFileDataModel*)uploadmodel
{
    NSLock *lock = [NSLock new];
    [lock lock];
    if(!uploadmodel){
        [lock unlock];
        return;
    }
    
    if(_databaseArr && _databaseArr.count == 3 ){
        NSMutableArray *uploadingArr = _databaseArr[0];
        NSInteger count = uploadingArr.count;
        [uploadingArr removeObject:uploadmodel];
        
        NSInteger atferDelCount = uploadingArr.count;
        
        if(count == atferDelCount){
            for (uploadFileDataModel*model in uploadingArr) {
                if(model.bg_id.integerValue == uploadmodel.bg_id.integerValue){
                    [uploadingArr removeObject:model];
                    break;
                }
            }
        }
        
        NSInteger atferDelCount2 = uploadingArr.count;
        
        if(count == atferDelCount2){
            //HLog(@"\n\n\nerror:上传中的任务没有删除掉database\n\n\n\n");
        }
    }
    
    [lock unlock];
}

- (void)handleDatabaseArrByInDone:(uploadFileDataModel*)uploadmodel
{
    NSLock *lock = [NSLock new];
    [lock lock];
    if(_databaseArr && _databaseArr.count == 3 ){
        NSMutableArray *uploadDoneArr = _databaseArr[1];
        [uploadDoneArr insertObject:uploadmodel atIndex:0];
    }
    [lock unlock];
}

- (void)handleDatabaseArrByInFail:(uploadFileDataModel*)uploadmodel
{
    NSLock *lock = [NSLock new];
    [lock lock];
    if(_databaseArr && _databaseArr.count == 3 ){
        NSMutableArray *uploadFailArr = _databaseArr[2];
        [uploadFailArr insertObject:uploadmodel atIndex:0];
    }
    [lock unlock];
}

- (void)handleDatabaseArrAddModelInUploading:(uploadFileDataModel*)uploadmodel
{
    NSLock *lock = [NSLock new];
    [lock lock];
    if(_databaseArr && _databaseArr.count == 3 ){
        NSMutableArray *uploadlingArr = _databaseArr[0];
        [uploadlingArr insertObject:uploadmodel atIndex:0];
    }
    [lock unlock];
}

//暂停上传完成
- (void)suspendUploadFileFun:(BOOL)isSuspendAll
{
    
    if(!_fileModelDataArr || !_curUploadFileDataModel){
        return;
    }
    
    if(isSuspendAll){
        for (uploadFileDataModel*model in _fileModelDataArr) {
            model.curUploadStateType = uploadStateSuspend;
        }
    }
    
    _isSuspendType = YES;
    _isUploadIngType = NO;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:uploadFileSuspendNotification object:nil];
    
    NSEnumerator *curArr = [_fileModelDataArr reverseObjectEnumerator];
    for (uploadFileDataModel*model in curArr) {
        [self changeUploadFileState:uploadStateSuspend withDidUploadBytes:model.didUploadBytes withModel:model complete:^(BOOL isSuccess) {
            
        }];
    }
    
}

//某个文件重新上传
- (void)reUploadFileFunBy:(NSMutableArray*)Arr withAll:(BOOL)isAllType
{
    if(!_fileModelDataArr){
        _fileModelDataArr = [NSMutableArray new];
    }
    
    for (uploadFileDataModel*model in Arr) {
        model.curUploadStateType = uploadStateUploading;
    }
    
    _isSuspendType = NO;
    
    if(isAllType)
    {
        _isNewAddTaskType = YES;
        _fileModelDataArr = Arr;
        _reUploadIngSelectIndex = -1;
        [self beginUploadFileFun];
        return;
    }
    
    _isNewAddTaskType = NO;
    _reUploadIngSelectIndex = 0;
    
    NSMutableArray *curArr = [NSMutableArray arrayWithArray:Arr];
    _fileModelDataArr = curArr;
    
//    for (uploadFileDataModel*addModel in curArr) {
//
//        BOOL needAddModel = YES;
//
//        //for (uploadFileDataModel*preModel in _fileModelDataArr)
//        for (int i=0;i< _fileModelDataArr.count;i++)
//        {
//            uploadFileDataModel*preModel = _fileModelDataArr[i];
//
//            if(addModel.bg_id.integerValue == preModel.bg_id.integerValue
//               || [addModel.localIdentifier isEqualToString:preModel.localIdentifier])
//            {
//                needAddModel = NO;
//
//                if(_reUploadIngSelectIndex == 0){
//                    _reUploadIngSelectIndex = i;
//
//                    if(i==0){
//                        _reUploadIngSelectIndex = -1;
//                    }
//                }
//
//                break;
//            }
//        }
//
//        if(needAddModel){
//            [_fileModelDataArr addObject:addModel];
//            [self handleDatabaseArrAddModelInUploading:addModel];
//        }
//    }
    
    //[_fileModelDataArr addObjectsFromArray:Arr];
    [self beginUploadFileFun];
}

- (void)uploadFileDoneFun
{
    long totalSizeByte = _curUploadFileDataModel.totalBytes;
    
    [self changeUploadFileState:uploadStateDone withDidUploadBytes:totalSizeByte withModel:_curUploadFileDataModel complete:^(BOOL isSuccess) {

        self->_isUploadIngType = NO;
        if(self->_fileModelDataArr.count > 0){
            [self beginUploadFileFun];
        }
        else{
            [self didUploadAllTaskDoneFun];
        }
    }];
}

//文件上传失败
- (void)uploadFileFailFun
{
    [self changeUploadFileState:uploadStateFail withDidUploadBytes:_curUploadFileDataModel.didUploadBytes withModel:_curUploadFileDataModel complete:^(BOOL isSuccess) {
         
        if(self->_fileModelDataArr.count > 0){
            [self beginUploadFileFun];
        }
        else{
            self->_isUploadIngType = NO;
            self->_curUploadFileDataModel = nil;
            [self didUploadAllTaskDoneFun];
        }
    }];
    
    mainBlock(^{
        //[[iToast makeText:NSLocalizedString(@"File_upload_fail",nil)] show];
    });
}

//删除本地数据库记录
- (void)deleteUploadFileRecordBy:(NSMutableArray *)delArr withDelCache:(BOOL)isDelCache complete:(custom_complete_B)complete
{
    //逻辑待优化
    BOOL isSuc = NO;
    
    BOOL isDelUploadingModel = NO;
    
    NSMutableArray *curDelArr = [NSMutableArray arrayWithArray:delArr];
    for (uploadFileDataModel *uploadFileDataMod in curDelArr) {
        
        NSMutableString* where = [[NSMutableString alloc] initWithString:@"where "];
        
        NSString *curStr =  [NSString stringWithFormat:@"%@=%@ ",bg_sqlKey(@"bg_id"),bg_sqlValue(uploadFileDataMod.bg_id)];
        [where appendString:curStr];
        isSuc = [uploadFileDataModel bg_delete:upLoadFile_image_tableName where:where];
        
        [self handleDatabaseArrByDelete:uploadFileDataMod];

        //删除本地图片
        if(isSuc && isDelCache){
            //判断是否可以删除本地缓存
            if(_databaseArr && _databaseArr.count == 3 ){
                NSMutableArray *uploadingArr = _databaseArr[0];
                NSMutableArray *uploadDoneArr = _databaseArr[1];
                NSMutableArray *uploadFailArr = _databaseArr[2];
                
                
                BOOL isNeedDel = YES;
                for (uploadFileDataModel *baseUploadFileDataMod in uploadingArr) {
                    if([_curUploadFileDataModel.filename isEqualToString:baseUploadFileDataMod.filename] ){
                        isNeedDel = NO;
                        break;
                    }
                }
                
                if(!isNeedDel){
                    for (uploadFileDataModel *baseUploadFileDataMod in uploadDoneArr) {
                        if([_curUploadFileDataModel.filename isEqualToString:baseUploadFileDataMod.filename] ){
                            isNeedDel = NO;
                            break;
                        }
                    }
                }
                
                if(!isNeedDel){
                    for (uploadFileDataModel *baseUploadFileDataMod in uploadFailArr) {
                        if([_curUploadFileDataModel.filename isEqualToString:baseUploadFileDataMod.filename] ){
                            isNeedDel = NO;
                            break;
                        }
                    }
                }
                
                if(isNeedDel){
                    if(uploadFileDataMod.curUploadFileType == uploadFileTypeVideo){
                        [cachesFileManager removeItemAtPath:uploadFileDataMod.videoFirstImageName type:uploadFileTypeImage error:nil];
                        
                        [cachesFileManager removeItemAtPath:uploadFileDataMod.filename type:uploadFileTypeVideo error:nil];
                    }
                    else{
                        [cachesFileManager removeItemAtPath:uploadFileDataMod.filename type:uploadFileTypeImage error:nil];
                    }
                }
            }
        }
        
        if(isSuc && !isDelCache){//上传报云机已经存在文件了 查询本地是否有任务记录
            [self handleRetryUploadAndDelRecordFun:uploadFileDataMod];
        }
        
        //是否在删除上传中的任务
       if(_fileModelDataArr && _fileModelDataArr.count >0)
       {
           for (uploadFileDataModel *curUploadFileDataMod in _fileModelDataArr)
           {
               if(curUploadFileDataMod.bg_id.integerValue == uploadFileDataMod.bg_id.integerValue){
                   [_fileModelDataArr removeObject:curUploadFileDataMod];
                   //[self handleDatabaseArrDeteleInUploading:curUploadFileDataMod];
                   break;
               }
           }
       }
        
        if(!isDelUploadingModel){
            if(_curUploadFileDataModel.bg_id.integerValue == uploadFileDataMod.bg_id.integerValue){
                isDelUploadingModel = YES;
                
                [[NSNotificationCenter defaultCenter] postNotificationName:uploadFileSuspendNotification object:nil];
            }
        }
    }
    
    if(isDelUploadingModel){
        _isUploadIngType = NO;
        if(_fileModelDataArr.count >=1){
            [self beginUploadFileFun];
        }
        else{
            //_curUploadFileDataModel = nil;
            
            _isSuspendType = NO;
            _curUploadFileDataModel.curUploadStateType = uploadStateDone;
        }
    }
        
    [[NSNotificationCenter defaultCenter] postNotificationName:uploadFileRefreshNotification object:nil];
    
    complete(YES);
    
}

#pragma mark 处理重复上传文件的问题
- (void)handleRetryUploadAndDelRecordFun:(uploadFileDataModel *)uploadFileDataMod
{
    NSLock *lock = [NSLock new];
    [lock lock];
    
    if(!_databaseArr && _databaseArr.count != 3){
        return;
    }
    
    NSMutableArray * doneArr = _databaseArr[1];
    NSMutableArray * failArr = _databaseArr[2];
    
    BOOL isNeedDelType = YES;
    
    for (uploadFileDataModel *doneModel in doneArr) {
        if([doneModel.localIdentifier isEqualToString:uploadFileDataMod.localIdentifier]){
            isNeedDelType = NO;
            break;
        }
    }
    
    if(isNeedDelType){
        for (uploadFileDataModel *failModel in failArr) {
            if([failModel.localIdentifier isEqualToString:uploadFileDataMod.localIdentifier]){
                isNeedDelType = NO;
                break;
            }
        }
    }
    
    if(isNeedDelType){
        if(uploadFileDataMod.curUploadFileType == uploadFileTypeVideo){
            [cachesFileManager removeItemAtPath:uploadFileDataMod.videoFirstImageName type:uploadFileTypeImage error:nil];
            
            [cachesFileManager removeItemAtPath:uploadFileDataMod.filename type:uploadFileTypeVideo error:nil];
        }
        else{
            [cachesFileManager removeItemAtPath:uploadFileDataMod.filename type:uploadFileTypeImage error:nil];
        }
    }
    else{//视频文件是要删除的
        if(uploadFileDataMod.curUploadFileType == uploadFileTypeVideo){
            [cachesFileManager removeItemAtPath:uploadFileDataMod.filename type:uploadFileTypeVideo error:nil];
        }
    }
    
    [lock unlock];
}

//检查是否需要重新上传
- (void)checkReUploadFileFun
{
    if(!_curUploadFileDataModel
       || _curUploadFileDataModel.curUploadStateType == uploadStateDone
       || _curUploadFileDataModel.curUploadStateType == uploadStateSuspend){
        return;
    }
    
    if(_isSuspendType){
        return;
    }
    
    NSInteger curTime = [iTools getNowTimeStamp];
    
    if(self.taskRenewTime == 0){
        return;
    }
    
    if(curTime - self.taskRenewTime < 10){
        return;
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:uploadFileBeginNotification object:_curUploadFileDataModel];
}

- (void)checkHadUploadTaskWithComplete:(custom_complete_B)complete
{
    [self getDataInDatabaseFun:NO complete:^(NSMutableArray * _Nonnull Arr) {
        mainBlock(^{
            if(!Arr || Arr.count != 3){
                complete(NO);
            }
            else{
                NSArray *firstArr = Arr[0];
                if(firstArr.count >0){
                    complete(YES);
                }
                else{
                    complete(NO);
                }
            }
        });
        
    }];
}

- (void)didUploadAllTaskDoneFun
{
    [[NSNotificationCenter defaultCenter] postNotificationName:uploadFileAllTaskDoneNotification object:nil];
}
@end
