//
//  CloudStorageDB.m
//  zhuxun
//
//  Created by winsoft on 17/6/22.
//
//

#import "CloudStorageDB.h"
#import "DBOperation.h"
#import <MagicalRecord/MagicalRecord.h>
#import <MJExtension/MJExtension.h>
#import "DBConfigureCenter.h"
#import <objc/runtime.h>
@interface CloudStorageDB()
@property (nonatomic , strong) DBOperation *dbOperation;
@end
@implementation CloudStorageDB

static CloudStorageDB *cloudStorageDB;

+ (instancetype)shareInstance
{
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        cloudStorageDB = [[self alloc] init];
    });
    
    return cloudStorageDB;

}

- (instancetype)init
{
    if (self = [super init]) {
        
        
        NSString *localPath = [NSPersistentStore MR_defaultLocalStoreUrl].absoluteString.stringByDeletingLastPathComponent;
        
        NSString *path = [NSString stringWithFormat:@"%@/%@_cloudStorageDisk.sqlite",localPath,Login_Name];
        NSFileManager *filemanager = [NSFileManager defaultManager];
        
        NSString *libraryPathstr = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
        NSString *applicationsupportdir = [libraryPathstr stringByAppendingString:@"/Application Support"];
        
        NSError *error;
        BOOL resultlocalpath = [filemanager createDirectoryAtPath:applicationsupportdir withIntermediateDirectories:YES attributes:nil error:&error];
        NSString *dbpath =
        //创建表
        self.dbOperation = [DBOperation dbOperationWithPath:path];
        
        [self.dbOperation creatDBWithTableName:cacheFileList dbModelClass:[CSFileModel class] Path:path autoUpgrade:YES uniqueCloumName:@"sid"];
        
        [self.dbOperation creatDBWithTableName:downTransFileList dbModelClass:[CSFileDownUpModel class] Path:path autoUpgrade:YES uniqueCloumName:@"downUpUUID"];
        
        [self.dbOperation creatDBWithTableName:upTransFileList dbModelClass:[CSFileDownUpModel class] Path:path autoUpgrade:YES uniqueCloumName:@"downUpUUID"];

    }
    
    return self;
}

//建立索引
- (void)createIndexForTableName:(NSString *)name indexCloums:(NSArray<NSArray*> *)indexCloums
{
    for (NSString *cloum in indexCloums) {
        NSString *sql = [NSString stringWithFormat:@"create index %@_%@ on %@(%@)",name,cloum,name,cloum];
        [self.dbOperation addDataToDBWithSQL:sql];
    }
}

- (void)addcsFilestoDB:(NSArray *)csFilesArray
{
    [self.dbOperation addDatasDBWithTableName:cacheFileList models:csFilesArray];
}
//增加一条数据到数据库中
- (void)addcsFiletoDB:(CSFileModel *)csFile
{
    [self.dbOperation addDataDBWithTableName:cacheFileList model:csFile];
}

- (void)addCSDownUpFileToDB:(CSFileDownUpModel *)csDownUpFile
{
    if (!csDownUpFile.pid) {
        csDownUpFile.pid = @"0";
    }
  //外部调用前请自身判断是否由相同的数据存在.
    if (csDownUpFile.downUpType == DownUpModelDown) {
        [self.dbOperation addDataDBWithTableName:downTransFileList model:csDownUpFile];
    }else [self.dbOperation addDataDBWithTableName:upTransFileList model:csDownUpFile];
   
}

- (void)addCSDownUpFilesToDB:(NSArray *)csDownUpFileToDBArray downUpModel:(DownUpModel)downUpModel
{
    NSString *tableName = nil;
    
    if (downUpModel == DownUpModelDown) {
        
        tableName = downTransFileList;
        
    }else  tableName = upTransFileList;

    [self.dbOperation addDatasDBWithTableName:tableName models:csDownUpFileToDBArray];
}


- (void)updateCloudFileToDB:(CSFileModel *)csFile
{
    
}

#pragma mark -- 2017-07-26 文件迁移 serverFullPath未处理 --sql
- (void)updateCSFilestoDB:(NSArray *)csFileSids targetid:(NSString *)pid{
    NSMutableString * pidsstring = [NSMutableString string];
    NSUInteger idx = 0;
    NSUInteger arraycount = csFileSids.count;
    for (NSString *str in csFileSids) {
        [pidsstring appendString:[NSString stringWithFormat:@"'%@'",str]];
        idx++;
        if (idx<arraycount) {
            [pidsstring appendString:@","];
        }
    }
    //未处理 serverFullPath  
    NSString *sql = [NSString stringWithFormat:@"UPDATE cacheFileList set pid = %@ where sid in (%@)",pid,pidsstring];
    [self.dbOperation addDataToDBWithSQL:sql];
    

}
- (void)getAllCloudFilesWithPid:(NSString *)pid resultBlock:(void(^)(NSArray *result))resultBlock
{
     NSString *sql = [NSString stringWithFormat:@"select * from cacheFileList where pid = '%@'",pid];
    [self.dbOperation quaryDBbySQL:sql result:^(NSMutableArray *array) {
        
        //dict array;
       NSArray *modelArray = [CSFileModel mj_objectArrayWithKeyValuesArray:array];
        
        resultBlock(modelArray);
    }];
}

//isFile
- (void)getFileModelWithFileMD5:(NSString *)md5 resultBlock:(void(^)(CSFileModel *csFileModel))resultBlock
{
    NSString *sql = [NSString stringWithFormat:@"select * from cacheFileList where md5 = '%@'",md5];
    [self.dbOperation quaryDBbySQL:sql result:^(NSMutableArray *array) {
        
        //dict array;
        NSArray *modelArray = [CSFileModel mj_objectArrayWithKeyValuesArray:array];
        
        if (modelArray.count) {
            resultBlock(modelArray[0]);
        }else resultBlock(nil);
        
    }];
}

//isDir
- (void)getFileModelWithFileID:(NSString *)ID resultBlock:(void(^)(CSFileModel *csFileModel))resultBlock
{
    NSString *sql = [NSString stringWithFormat:@"select * from cacheFileList where sid = '%@'",ID];
    [self.dbOperation quaryDBbySQL:sql result:^(NSMutableArray *array) {
        
        //dict array;
        NSArray *modelArray = [CSFileModel mj_objectArrayWithKeyValuesArray:array];
        
        if (modelArray.count) {
            resultBlock(modelArray[0]);
        }else resultBlock(nil);
        
    }];
}

- (void)getCSDownUpFileWithMD5:(NSString *)md5 downUpModel:(DownUpModel)downUpModel resultBlock:(void(^)(NSArray *csFileModels))resultBlock
{
    NSString *sql = downUpModel == DownUpModelDown?[NSString stringWithFormat:@"select * from downTransFileList where md5 = '%@'",md5]:[NSString stringWithFormat:@"select * from upTransFileList where md5 = '%@'",md5];
    [self.dbOperation quaryDBbySQL:sql result:^(NSMutableArray *array) {
        
        //dict array;
        NSArray *modelArray = [CSFileDownUpModel mj_objectArrayWithKeyValuesArray:array];
        
        if (modelArray.count) {
            resultBlock(modelArray);
        }else resultBlock(nil);
        
    }];
}

- (void)getCSDownUpFileWithMD5:(NSString *)md5 pid:(NSString *)pid name:(NSString *)name downUpModel:(DownUpModel)downUpModel resultBlock:(void(^)(CSFileDownUpModel *csFileModel))resultBlock
{
    NSString *sql = downUpModel == DownUpModelDown?[NSString stringWithFormat:@"select * from downTransFileList where md5 = '%@' and pid = '%@' and name = '%@'",md5,pid,name]:[NSString stringWithFormat:@"select * from upTransFileList where md5 = '%@' and pid = '%@' and name = '%@'",md5,pid,name];
    [self.dbOperation quaryDBbySQL:sql result:^(NSMutableArray *array) {
        
        //dict array;
        NSArray *modelArray = [CSFileDownUpModel mj_objectArrayWithKeyValuesArray:array];
        
        if (modelArray.count) {
            resultBlock(modelArray[0]);
        }else resultBlock(nil);
        
    }];
}

- (void)getCSDownUpFileWithUUID:(NSString *)downUpUUID downUpModel:(DownUpModel)downUpModel resultBlock:(void(^)(CSFileDownUpModel *csFileModel))resultBlock
{
    NSString *tableName = nil;
    
    tableName = (downUpModel == DownUpModelDown)?downTransFileList:upTransFileList;
    
    NSString *sql = [NSString stringWithFormat:@"select * from %@ where downUpUUID = '%@'",tableName,downUpUUID];
    
    [self.dbOperation quaryDBbySQL:sql result:^(NSMutableArray *array) {
        //dict array;
        NSArray *modelArray = [CSFileDownUpModel mj_objectArrayWithKeyValuesArray:array];
        
        if (modelArray.count) {
            resultBlock(modelArray[0]);
        }else resultBlock(nil);
        
    }];
    
}

- (void)getCSDownUpFilesWithUUIDs:(NSArray *)downUpUUIDs downUpModel:(DownUpModel)downUpModel resultBlock:(void(^)(NSArray *csFileModels))resultBlock
{
    NSString *strUUIDs = [downUpUUIDs componentsJoinedByString:@","];
    
    NSString *tableName = (downUpModel == DownUpModelDown)?downTransFileList:upTransFileList;
    
    NSString *sql = [NSString stringWithFormat:@"select * from %@ where downUpUUID in (%@)",tableName,strUUIDs];
    
    [self.dbOperation quaryDBbySQL:sql result:^(NSMutableArray *array) {
        //dict array;
        NSArray *modelArray = [CSFileDownUpModel mj_objectArrayWithKeyValuesArray:array];
        
        if (modelArray.count) {
            resultBlock(modelArray);
        }else resultBlock(nil);
        
    }];
    
}



- (void)getCSDownUpFileSameNameDifMd5WithMD5:(NSString *)md5 name:(NSString *)name localPath:(NSString *)localPath downUpModel:(DownUpModel)downUpModel resultBlock:(void(^)(NSInteger sameNameFileCount))resultBlock
{
    
    NSString *tableName = nil;
    
    tableName = (downUpModel == DownUpModelDown)?downTransFileList:upTransFileList;
    // and localRootPath = '%@'   ,localPath
    NSString *sql = [NSString stringWithFormat:@"select * from %@ where md5 != '%@' and name = '%@' and localRootPath = '%@'",tableName ,md5,name,localPath];
    
    [self.dbOperation quaryDBbySQL:sql result:^(NSMutableArray *array) {
        
        //dict array;
        NSArray *modelArray = [CSFileDownUpModel mj_objectArrayWithKeyValuesArray:array];
        
        resultBlock(modelArray.count);
     
    }];
}

- (void)getProcessCSDownUpFileWithMD5:(NSString *)md5 name:(NSString *)name downUpModel:(DownUpModel)downUpModel resultBlock:(void(^)(NSArray *downUpModels))resultBlock
{
    NSString *sql = downUpModel == DownUpModelDown?[NSString stringWithFormat:@"select * from downTransFileList where md5 != '%@' and name = '%@' and (downUpStatus = %d OR downUpStatus = %d)",md5,name,DownUpStatusWait,DownUpStatusDoing]:[NSString stringWithFormat:@"select * from upTransFileList where md5 != '%@' and name = '%@' and (downUpStatus = %d OR downUpStatus = %d)",md5,name,DownUpStatusWait,DownUpStatusDoing];
    
    [self.dbOperation quaryDBbySQL:sql result:^(NSMutableArray *array) {
        
        //dict array;
        NSArray *modelArray = [CSFileDownUpModel mj_objectArrayWithKeyValuesArray:array];
        
        if (modelArray.count) {
            resultBlock(modelArray);
        }else resultBlock(nil);
        
    }];
}

- (void)getAllProcessOrWaitFileWithResultBlock:(void(^)(NSArray *downModels,NSArray *upModels))resultBlock;
{
    NSString *sql = [NSString stringWithFormat:@"select * from %@ where downUpStatus <= %d and isdir = 0 order by downUpStatus desc",upTransFileList,DownUpStatusDoing];
    NSString *sql2 =  [NSString stringWithFormat:@"select * from %@ where downUpStatus <= %d  and isdir = 0 order by downUpStatus desc",downTransFileList,DownUpStatusDoing];
    
    [self.dbOperation quaryDBbySQL:sql result:^(NSMutableArray *array) {
        
        //dict array;
        NSArray *upModels = [CSFileDownUpModel mj_objectArrayWithKeyValuesArray:array];
        
        [self.dbOperation quaryDBbySQL:sql2 result:^(NSMutableArray *array) {
            
            //dict array;
            NSArray *downModels = [CSFileDownUpModel mj_objectArrayWithKeyValuesArray:array];
            
        
            if (resultBlock) {
                resultBlock(downModels, upModels);
            }
           
            
        }];

        
    }];
}

- (void)getAllCSDownUpFilesFoldersWithPid:(NSString *)pid  isdir:(NSInteger)isDir downUpModel:(DownUpModel)downUpModel resultBlock:(void(^)(NSArray *downUpModels))resultBlock
{
    /*
     select * from downTransFileList where pid= 'pid'
     
     union all
     
     select a.sid,a.pid,a.downUpUUID as Level from downTransFileList a
     
     inner join downTransFileList b on a.sid=b.pid
     
     inner join
     
     (
     
     select ParentID from tblCity group by ParentID
     
     ) c on a.ParentID=c.ParentID
     */
    //@"WITH RECURSIVE result(pid,sid) AS(SELECT * FROM %@  WHERE pid='%@' UNION  SELECT a.sid,a.pid FROM %@ a,result b WHERE b.sid = a.pid)SELECT * from result"//[DBConfigureCenter getKeysArrayStrWithClassName:[CSFileDownUpModel class]]
    
    NSString *tableName = (downUpModel == DownUpModelDown?downTransFileList:upTransFileList);
    
    NSString *sql = [NSString stringWithFormat:@"WITH RECURSIVE result(%@) AS(SELECT * FROM %@  WHERE pid='%@' UNION  SELECT a.* FROM %@ a,result b WHERE b.sid = a.pid)SELECT * from result",[DBConfigureCenter getKeysArrayStrWithClassName:[CSFileDownUpModel class]],tableName,pid,tableName];


    [self.dbOperation quaryDBbySQL:sql result:^(NSMutableArray *array) {
        
        NSArray *modelArray = [CSFileDownUpModel mj_objectArrayWithKeyValuesArray:array];
        
        NSMutableArray *tempArray = [NSMutableArray array];
        
        for (CSFileDownUpModel *csFileDownUpModel in modelArray) {
            
            if (isDir == 0 && !csFileDownUpModel.isdir) {
                [tempArray addObject:csFileDownUpModel];
            }else if (isDir == 1 && csFileDownUpModel.isdir)
            {
                 [tempArray addObject:csFileDownUpModel];
            }else if(isDir == 2)
            {
                [tempArray addObject:csFileDownUpModel];
            }
        }
        
    
        
        if (tempArray.count) {
            resultBlock(tempArray);
        }else resultBlock(nil);
        
    }];

}

- (void)judgeFileFolderDownUpResultWithWithPid:(NSString *)pid downUpModel:(DownUpModel)downUpModel resultBlock:(void(^)(DownUpStatus downUpStatus, NSArray *totalDownUpFileModels))resultBlock
{
    NSString *tableName = (downUpModel == DownUpModelDown?downTransFileList:upTransFileList);
    
    NSString *sql = [NSString stringWithFormat:@"WITH RECURSIVE result(%@) AS(SELECT * FROM %@  WHERE pid='%@' UNION  SELECT a.* FROM %@ a,result b WHERE b.sid = a.pid)SELECT * from result",[DBConfigureCenter getKeysArrayStrWithClassName:[CSFileDownUpModel class]],tableName,pid,tableName];
  
    [self.dbOperation quaryDBbySQL:sql result:^(NSMutableArray *array) {
        
        NSArray *modelArray = [CSFileDownUpModel mj_objectArrayWithKeyValuesArray:array];
        
        DownUpStatus fileFolderStatus = DownUpStatusSuccess;
        
        NSArray *tempArray = [modelArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"isdir = 0"]];
    
        //还不如统计多个呢.
        NSInteger successNum = 0;
        NSInteger faiureNum = 0;
        NSInteger doingNum = 0;
        NSInteger waitNum = 0;
        NSInteger pauseNum = 0;
        
        //暂停条件,不存在doing和wating下,只有pause和success,faiure.
        
        for (CSFileDownUpModel *csFileDownUpModel in tempArray) {

            if (csFileDownUpModel.downUpStatus == DownUpStatusSuccess) {
                successNum ++;
            }else if (csFileDownUpModel.downUpStatus == DownUpStatusFailure)
            {
                faiureNum ++;
            }else if (csFileDownUpModel.downUpStatus == DownUpStatusDoing)
            {
                doingNum ++;
            }else if (csFileDownUpModel.downUpStatus == DownUpStatusWait)
            {
                waitNum ++;
            }else if (csFileDownUpModel.downUpStatus == DownUpStatusPause)
            {
                pauseNum ++;
            }
            
        }
        
        if (successNum == tempArray.count) {
            fileFolderStatus = DownUpStatusSuccess;
        }else if (faiureNum == tempArray.count)
        {
            fileFolderStatus = DownUpStatusFailure;
        }else if (pauseNum  && !doingNum && ! waitNum)
        {
            fileFolderStatus = DownUpStatusPause;
        }else if (waitNum == tempArray.count)
        {
            fileFolderStatus = DownUpStatusWait;
        }else fileFolderStatus = DownUpStatusDoing;
        
        resultBlock(fileFolderStatus,tempArray);
        
        
    }];

}

- (void)getFolderFilesDownUpStatusWithPid:(NSString *)pid downUpModel:(DownUpModel)downUpModel resultBlock:(void(^)(DownUpStatus downUpStatus))resultBlock
{
    NSString *tableName = (downUpModel == DownUpModelDown?downTransFileList:upTransFileList);
    
    NSString *sql =  sql = [NSString stringWithFormat:@"WITH RECURSIVE result(%@) AS(SELECT * FROM %@  WHERE pid='%@' and isdir = 0 UNION  SELECT a.* FROM %@ a,result b WHERE b.sid = a.pid)SELECT * from result",[DBConfigureCenter getKeysArrayStrWithClassName:[CSFileDownUpModel class]],tableName,pid,tableName];
    
    [self.dbOperation quaryDBbySQL:sql result:^(NSMutableArray *array) {
        
#warning 2017-07-06
        NSArray *modelArray = [CSFileDownUpModel mj_objectArrayWithKeyValuesArray:array];
        
        BOOL result = YES;
        for (CSFileDownUpModel *csFileDownUpModel in modelArray) {
            if (csFileDownUpModel.downUpStatus != DownUpStatusSuccess) {
                result  = NO;
            }
            
        }
        if (result) {
            resultBlock(DownUpStatusSuccess);
        }else resultBlock(DownUpStatusDoing);
        
    }];
}


- (void)getCSDownUpFolderWithID:(NSString *)sid isdir:(BOOL)isdir name:(NSString *)name category:(NSInteger)category  downUpModel:(DownUpModel)downUpModel  resultBlock:(void(^)(CSFileDownUpModel *csFileModel))resultBlock
{
    NSString *sql = downUpModel == DownUpModelDown?[NSString stringWithFormat:@"select * from downTransFileList where sid = '%@' and name = '%@' and isdir = %d and file_category = %ld",sid,name,isdir,category]:[NSString stringWithFormat:@"select * from upTransFileList where sid != '%@' and name = '%@' and isdir = %d and file_category = %ld",sid,name,isdir,category];
    
    [self.dbOperation quaryDBbySQL:sql result:^(NSMutableArray *array) {
        
        //dict array;
        NSArray *modelArray = [CSFileDownUpModel mj_objectArrayWithKeyValuesArray:array];
        
        if (modelArray.count) {
            resultBlock(modelArray[0]);
        }else resultBlock(nil);
        
    }];
}

- (void)getCSDownUpFolderAndSetSameStatusWithID:(NSString *)sid downUpModel:(DownUpModel)downUpModel
{
    NSString *sql = downUpModel == DownUpModelDown?[NSString stringWithFormat:@"select * from downTransFileList where sid = '%@' and downUpStatus = %d",sid,DownUpStatusSuccess]:[NSString stringWithFormat:@"select * from upTransFileList where sid != '%@' and downUpStatus = %d",sid,DownUpStatusSuccess];
    [self.dbOperation quaryDBbySQL:sql result:^(NSMutableArray *array) {
        
        //dict array;
        NSArray *modelArray = [CSFileDownUpModel mj_objectArrayWithKeyValuesArray:array];
        
        if (modelArray.count) {
         
            CSFileDownUpModel *csFileDownUpModel = modelArray[0];
            
            NSString *sql = [NSString stringWithFormat:@"update %@ set downUpStatus = %d where sid = '%@'",csFileDownUpModel.downUpType == DownUpModelDown?downTransFileList:upTransFileList,csFileDownUpModel.downUpStatus,csFileDownUpModel.sid];
            [self.dbOperation addDataToDBWithSQL:sql];
        }
        
    }];
}

//+ (void)getCSDownUpFileWithMD5:(NSString *)md5 filename:(NSString *)filename downUpModel:(DownUpModel)downUpModel resultBlock:(void(^)(CSFileDownUpModel *csFileModel))resultBlock
//{
//    NSString *sql = downUpModel == DownUpModelDown?[NSString stringWithFormat:@"select * from downTransFileList where md5 = '%@' and name = '%@'",md5,filename]:[NSString stringWithFormat:@"select * from upTransFileList where md5 = '%@' and name = '%@'",md5,filename];
//    [DBOperation quaryDBbySQL:sql result:^(NSMutableArray *array) {
//        
//        //dict array;
//        NSArray *modelArray = [CSFileDownUpModel mj_objectArrayWithKeyValuesArray:array];
//        
//        if (modelArray.count) {
//            resultBlock(modelArray[0]);
//        }else resultBlock(nil);
//        
//    }];
//}

- (void)getSubFileFolderDownFileWithPid:(NSString *)pid ResultBlock:(void(^)(NSArray *result))resultBlock
{
    NSString *sql = [NSString stringWithFormat:@"select * from %@ where pid = '%@'",downTransFileList,pid];
#warning 是否加入file_category != 0
    [self.dbOperation quaryDBbySQL:sql result:^(NSMutableArray *array) {
        
        //dict array;
        NSArray *modelArray = [CSFileDownUpModel mj_objectArrayWithKeyValuesArray:array];
        
        if (modelArray.count) {
            resultBlock(modelArray);
        }else resultBlock(nil);
        
    }];
    
}

- (void)getSubFileFolderDownSuccessFileWithPid:(NSString *)pid ResultBlock:(void(^)(NSArray *result))resultBlock
{
    //文件and 子文件都成功的文件夹
    
    //先获取所有目标的文件和文件夹,再进行文件夹的判断.
    NSString *sql = [NSString stringWithFormat:@"select * from %@ where (downUpStatus = %d and pid = '%@' and isdir = 0) or (pid = '%@' and isdir = 1)",downTransFileList,DownUpStatusSuccess,pid,pid];
  
    [self.dbOperation quaryDBbySQL:sql result:^(NSMutableArray *array) {
        
        //dict array;
        NSArray *modelArray = [CSFileDownUpModel mj_objectArrayWithKeyValuesArray:array];
        NSMutableArray *tempArray = [NSMutableArray array];
        
        for (CSFileDownUpModel *csFileDownUpModel in modelArray) {
            
            if (!csFileDownUpModel.isdir) {
                [tempArray addObject:csFileDownUpModel];
            }else{
            
                [self judgeFileFolderDownUpResultWithWithPid:csFileDownUpModel.sid downUpModel:csFileDownUpModel.downUpType resultBlock:^(DownUpStatus downUpStatus, NSArray *totalSubFileModels) {
                    
                    if (downUpStatus == DownUpStatusSuccess) {
                        csFileDownUpModel.subFileDownUpModels = totalSubFileModels;
                        //success 动态调整.
                        csFileDownUpModel.downUpStatus = DownUpStatusSuccess;
                        [tempArray addObject:csFileDownUpModel];
                    }
                }];
            }
        }
        
        if (tempArray.count) {
            resultBlock(tempArray);
        }else resultBlock(nil);
        
    }];
}
- (void)getSubFileFolderDownUnFinishedFileWithPid:(NSString *)pid ResultBlock:(void(^)(NSArray *result))resultBlock
{

    NSString * sql = [NSString stringWithFormat:@"select * from %@ where (downUpStatus != %d and pid = '%@' and isdir = 0) or (pid = '%@' and isdir = 1)",downTransFileList,DownUpStatusSuccess,pid,pid];;
    //[NSString stringWithFormat:@"select * from %@ where (downUpStatus != %d and pid = '%@')",downTransFileList,DownUpStatusSuccess,pid];
    
    [self.dbOperation quaryDBbySQL:sql result:^(NSMutableArray *array) {
        
        //dict array;
        NSArray *modelArray = [CSFileDownUpModel mj_objectArrayWithKeyValuesArray:array];
        
        NSMutableArray *tempArray = [NSMutableArray array];
        
        for (CSFileDownUpModel *csFileDownUpModel in modelArray) {
            
            if (!csFileDownUpModel.isdir) {
                [tempArray addObject:csFileDownUpModel];
            }else{
                
                [self judgeFileFolderDownUpResultWithWithPid:csFileDownUpModel.sid downUpModel:csFileDownUpModel.downUpType resultBlock:^(DownUpStatus downUpStatus,NSArray *totalSubFileModels) {
                
                    if (downUpStatus != DownUpStatusSuccess) {
                        csFileDownUpModel.subFileDownUpModels = totalSubFileModels;
                        csFileDownUpModel.downUpStatus = downUpStatus;
                        [tempArray addObject:csFileDownUpModel];
                    }
                }];
            }
        }
        
        if (tempArray.count) {
            resultBlock(tempArray);
        }else resultBlock(nil);
        
    }];
}



- (void)getSubFileFolderUpFileWithPid:(NSString *)pid ResultBlock:(void(^)(NSArray *result))resultBlock
{
    NSString *sql = nil;
    
    if (!pid || [pid isEqualToString:@"0"]) {
        
        sql = [NSString stringWithFormat:@"select * from %@ where file_category = 0",upTransFileList];
        
    }else sql = [NSString stringWithFormat:@"select * from %@ where pid = '%@'",upTransFileList,pid];
    
    [self.dbOperation quaryDBbySQL:sql result:^(NSMutableArray *array) {
        
        //dict array;
        NSArray *modelArray = [CSFileDownUpModel mj_objectArrayWithKeyValuesArray:array];
        
        if (modelArray.count) {
            resultBlock(modelArray);
        }else resultBlock(nil);
        
    }];
}

- (void)getSubFileFolderUpSuccessFileWithPid:(NSString *)pid ResultBlock:(void(^)(NSArray *result))resultBlock
{
     NSString *sql = nil;
    if (!pid || [pid isEqualToString:@"0"]) {
        
        sql = [NSString stringWithFormat:@"select * from %@ where downUpStatus = %d and file_category = 0",upTransFileList,DownUpStatusSuccess];
        
    }else sql = [NSString stringWithFormat:@"select * from %@ where downUpStatus = %d and pid = '%@'",upTransFileList,DownUpStatusSuccess,pid];
   
  
    [self.dbOperation quaryDBbySQL:sql result:^(NSMutableArray *array) {
        
        //dict array;
        NSArray *modelArray = [CSFileDownUpModel mj_objectArrayWithKeyValuesArray:array];
        
        if (modelArray.count) {
            resultBlock(modelArray);
        }else resultBlock(nil);
        
    }];
    
}

- (void)getSubFileFolderUpUnFinishedFileWithPid:(NSString *)pid ResultBlock:(void(^)(NSArray *result))resultBlock
{
    NSString *sql = nil;
    if (!pid || [pid isEqualToString:@"0"]) {
        
        sql = [NSString stringWithFormat:@"select * from %@ where downUpStatus != %d and file_category = 0",upTransFileList,DownUpStatusSuccess];
        
    }else sql = [NSString stringWithFormat:@"select * from %@ where downUpStatus != %d and pid = '%@'",upTransFileList,DownUpStatusSuccess,pid];
        
    [self.dbOperation quaryDBbySQL:sql result:^(NSMutableArray *array) {
        
        // 排序doing的在前.
        //dict array;
        NSArray *modelArray = [CSFileDownUpModel mj_objectArrayWithKeyValuesArray:array];
        
        if (modelArray.count) {
            resultBlock(modelArray);
        }else resultBlock(nil);
        
    }];
}


- (void)deleteCSFileToDB:(CSFileModel *)csFile
{
    
}

- (void)deleteCSDownUpFiles:(NSArray *)csFiles downUpType:(DownUpModel)downUpModel ResultBlock:(void(^)(NSArray *fileResult))resultBlock;
{
    NSMutableArray *tempAllFilesArray = [NSMutableArray array];
    
    NSMutableArray *tempUUIDsSqlArray =[NSMutableArray array];
    
    NSString *tableName = (downUpModel == DownUpModelDown?downTransFileList:upTransFileList);
    
    for (CSFileDownUpModel *downUpFileModel in csFiles) {
        
        
        [tempAllFilesArray addObject:downUpFileModel];
        
        if (downUpFileModel.isdir) {
            
            [self getAllCSDownUpFilesFoldersWithPid:downUpFileModel.sid isdir:2 downUpModel:downUpFileModel.downUpType resultBlock:^(NSArray *downUpModels) {
                
                [tempAllFilesArray addObjectsFromArray:downUpModels];
                
            }];
            
            
        }
   
    }
    
    for (CSFileDownUpModel *csFileDownUpModel in tempAllFilesArray) {
        
        NSString *sql = [NSString stringWithFormat:@"delete from %@ where downUpUUID = '%@'",tableName,csFileDownUpModel.downUpUUID];
        
        [tempUUIDsSqlArray addObject:sql];
    }
    
    [self.dbOperation addDatasToDBWithSQLs:tempUUIDsSqlArray];
    
    if (resultBlock) {
        resultBlock(tempAllFilesArray);
    }
    
    
    
}

- (void)updateCSFiletoDB:(CSFileModel *)csFile
{
    
}

- (void)updateCSDownUpFileStatusWithCSFileDownUpModel:(CSFileDownUpModel *)csFileDownUpModel
{
#warning md5 和name相同的文件,则会全部更新
    NSString *sql = nil;
    if (!csFileDownUpModel.isdir) {
        if (csFileDownUpModel.localRootPath) {
            sql = [NSString stringWithFormat:@"update %@ set downUpStatus = %d,downUpSize = %ld, localRootPath = '%@' where md5 = '%@' and name = '%@';",csFileDownUpModel.downUpType == DownUpModelDown?downTransFileList:upTransFileList,csFileDownUpModel.downUpStatus,csFileDownUpModel.downUpSize,csFileDownUpModel.localRootPath,csFileDownUpModel.md5,csFileDownUpModel.name];
        }else sql = [NSString stringWithFormat:@"update %@ set downUpStatus = %d,downUpSize = %ld where md5 = '%@' and name = '%@';",csFileDownUpModel.downUpType == DownUpModelDown?downTransFileList:upTransFileList,csFileDownUpModel.downUpStatus,csFileDownUpModel.downUpSize,csFileDownUpModel.md5,csFileDownUpModel.name];
    }else{
    
        sql = [NSString stringWithFormat:@"update %@ set downUpStatus = %d where sid = '%@'",csFileDownUpModel.downUpType == DownUpModelDown?downTransFileList:upTransFileList,csFileDownUpModel.downUpStatus,csFileDownUpModel.sid];
    }
   
    [self.dbOperation addDataToDBWithSQL:sql];
    
    //同时更新relationlist,如果downupsize不断累加=size-> 累加到父节点上.

    //获取父节点,如果父节点
    
    
    
}

- (void)updateCSDownUpFileStatusWithCSFileDownUpModels:(NSArray *)csFileDownUpModels downUpType:(DownUpModel)downUpType downUpStatus:(DownUpStatus)downUpStatus
{
    NSString *tableName = (downUpType == DownUpModelDown?downTransFileList:upTransFileList);
    
    NSMutableArray *sqlsArray = [NSMutableArray array];
    for (CSFileDownUpModel *csFileDownUpModel in csFileDownUpModels) {
        
        NSString *sql = nil;
        if (csFileDownUpModel.isdir) {
            sql = [NSString stringWithFormat:@"UPDATE %@ set downUpStatus = %d where downUpUUID = '%@'",tableName,downUpStatus,csFileDownUpModel.downUpUUID];
        }else{
        
            sql = [NSString stringWithFormat:@"UPDATE %@ set downUpStatus = %d where md5 = '%@' and name = '%@'",tableName,downUpStatus,csFileDownUpModel.md5,csFileDownUpModel.name];
        }
        
        [sqlsArray addObject:sql];
        

    }

    [self.dbOperation addDatasToDBWithSQLs:sqlsArray];
    
}

- (void)updateCSDownUpFileIDWithCSFileDownUpModel:(CSFileDownUpModel *)csFileDownUpModel sid:(NSString *)sid
{
    NSString *sql = [NSString stringWithFormat:@"update %@ set sid = '%@' where downUpUUID = '%@';",csFileDownUpModel.downUpType == DownUpModelDown?downTransFileList:upTransFileList,sid,csFileDownUpModel.downUpUUID];
    
    [self.dbOperation addDataToDBWithSQL:sql];
}

- (void)updateCSDownUpFileLocalPathWithCSFileDownUpModel:(CSFileDownUpModel *)csFileDownUpModel newLocalPath:(NSString *)newLocalPath
{
    NSString *sql = [NSString stringWithFormat:@"update %@ set localRootPath = '%@' where downUpUUID = '%@';",csFileDownUpModel.downUpType == DownUpModelDown?downTransFileList:upTransFileList,newLocalPath,csFileDownUpModel.downUpUUID];
    
    [self.dbOperation addDataToDBWithSQL:sql];
}


- (void)updateDataDBWithTableName:(NSString *)tableName model:(id)model whereSql:(NSString *)whereSql
{
    /*
     UPDATE table_name
     SET column1 = value1, column2 = value2...., columnN = valueN
     WHERE [condition];
     */
    
    //    sqlite> UPDATE COMPANY SET ADDRESS = 'Texas' WHERE ID = 6;
}

- (void)deleteDataDBWIthTableName:(NSString *)tableName whereSql:(NSString *)whereSql
{
    //if wheresql = nil, clear all table
    
    //    sqlite> DELETE FROM COMPANY WHERE SQL;
}
@end
