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

#import "CSFileTransListController.h"

#import "IWNavigationController.h"

#import "CSTabBarController.h"

//#import "NewMessageTransController.h"

#import "CSFileDownUpCell.h"

#import "CloudStorageDB.h"

#import "CloudStorageUploadCenter.h"

#import "CloudStorageDownloadCenter.h"

#import "FileUtils.h"

#import "UIBarButtonItem+Addition.h"

/**
 *  单某个文件夹下的文件(夹)操作后(上传下载成功,暂停,开始上传下载),通知上层文件夹更新状态,支持递归
 *
 *  @param selfFileDownUpModels  实际操作的文件
 *  @param parentFileDownUpModel 当前操作的父文件夹
 *  @param downUpStatus          实际操作
 */
typedef void (^ParentFileResponseSubFilesBlock)(NSArray <CSFileDownUpModel *> *selfFileDownUpModels,CSFileDownUpModel *parentFileDownUpModel, DownUpStatus downUpStatus);
#define KSegmentH 40
@interface CSFileTransListController()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic , weak) UISegmentedControl *segmentControl;
@property (nonatomic , weak) UITableView *mainTableView;
@property (nonatomic , weak) CSFileExtensionViewForCell *extensionView;

@property (nonatomic , copy) NSString *pid;

//父节点.
@property (nonatomic , strong) CSFileDownUpModel *parentCSFileDownUpModel;

@property (nonatomic , assign) DownUpModel downUpModel;

@property (nonatomic , strong) ParentFileResponseSubFilesBlock parentFileResponseSubFilesBlock;

@property (nonatomic , strong) NSMutableArray *processDataArray;
@property (nonatomic , strong) NSMutableArray *finishDataArray;

@property (nonatomic , strong) NSMutableArray *uploadProcessDataArray;
@property (nonatomic , strong) NSMutableArray *uploadFinishDataArray;


@property (nonatomic , strong) NSMutableArray *downloadProcessDataArray;
@property (nonatomic , strong) NSMutableArray *downloadFinishDataArray;

@property (nonatomic , strong) NSMutableArray *muiltSelectFilesArray;
@end
@implementation CSFileTransListController


- (NSMutableArray *)processDataArray
{
    if (self.downUpModel == DownUpModelUp) {
        return self.uploadProcessDataArray;
    }else return self.downloadProcessDataArray;
}

- (NSMutableArray *)finishDataArray
{
    if (self.downUpModel == DownUpModelDown) {
        return self.downloadFinishDataArray;
    }else return self.uploadFinishDataArray;
}

- (NSMutableArray *)uploadProcessDataArray
{
    if (!_uploadProcessDataArray) {
        _uploadProcessDataArray = [NSMutableArray array];
    }
    return _uploadProcessDataArray;
}

- (NSMutableArray *)uploadFinishDataArray
{
    if (!_uploadFinishDataArray) {
        _uploadFinishDataArray = [NSMutableArray array];
    }
    return _uploadFinishDataArray;
}

- (NSMutableArray *)downloadProcessDataArray
{
    if (!_downloadProcessDataArray) {
        _downloadProcessDataArray = [NSMutableArray array];
    }
    
    return _downloadProcessDataArray;
}

- (NSMutableArray *)downloadFinishDataArray
{
    if (!_downloadFinishDataArray) {
        _downloadFinishDataArray = [NSMutableArray array];
    }
    
    return _downloadFinishDataArray;
}

- (NSMutableArray *)muiltSelectFilesArray
{
    if (!_muiltSelectFilesArray) {
        _muiltSelectFilesArray = [NSMutableArray array];
    }
    
    return _muiltSelectFilesArray;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    if([self respondsToSelector:@selector(setEdgesForExtendedLayout:)])
    {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    if (!self.pid) {
        self.pid = @"0";
    }
    
    if ([self.pid isEqualToString:@"0"]) {
        self.title = @"传输列表";
    }

    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(muiltSelect) icon:@"navbar_muiltSel" highlightedIcon:@"navbar_muiltSel_press" title:nil iconSize:CGSizeMake(20, 20) fontSize:0 titleColor:nil];
    
    [self initSubviews];
    
    //待取消.使用reload并判断文件状态,是否需要移动.
    [self initData];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self registeUploadCenter];
    
    [self registeDownloadCenter];
    
    if ([self.pid isEqualToString:@"0"]) {
        [self registerFileFolderDownloadNotoice];
    }
    

    //待取消.使用reload并判断文件状态,是否需要移动.
//   [self initData];
}

- (void)muiltSelect
{
    [self.muiltSelectFilesArray removeAllObjects];
    
    self.mainTableView.allowsMultipleSelection = !self.mainTableView.allowsMultipleSelection;
    
    [self.mainTableView reloadData];
    
   
    __weak typeof(self)weakself = self;
    __weak typeof(self.mainTableView)weakTableView = self.mainTableView;
    
    if (self.mainTableView.allowsMultipleSelection) {
        CSFileExtensionViewForCell *extensionView = [[CSFileExtensionViewForCell alloc]initWithItmes:@[@{@"icon":@"file_share_normal",@"title":@"分享",@"opType":@(ExtensionOPShare)},@{@"icon":@"file_delete_normal",@"title":@"删除",@"opType":@(ExtensionOPDelete)}]];
        
        
        extensionView.extensionOpBlock = ^(ExtensionOP extensionOP, CSFileDownUpFrameModel *csFileDownUpFrameModel){
            
            switch (extensionOP) {
                case ExtensionOPDelete:
                    [weakself deleteFiles:self.muiltSelectFilesArray];
                    break;
                    
                case ExtensionOPShare:
                    //yidong 文件夹;
                    [weakself shareFiles:self.muiltSelectFilesArray];
                    break;
                    
                default:
                    break;
            }
        };
        
        extensionView.disable = YES;
        
        extensionView.frame = CGRectMake(0, self.view.frame.size.height -  FileExtensionViewH, SCREEN_WIDTH, FileExtensionViewH);
        
        [self.view addSubview:extensionView];
        
        self.extensionView = extensionView;
        
        self.segmentControl.enabled = NO;
    }else{
    
        [self.extensionView removeFromSuperview];
        self.extensionView = nil;
        self.segmentControl.enabled = YES;
    }
    
    //调整tableview.frame
    self.mainTableView.frame = CGRectMake(0, CGRectGetMaxY(self.segmentControl.frame), SCREEN_WIDTH, SCREEN_HEIGHT - self.segmentControl.frame.size.height - NavBarHeight - STATUSBAR_HEIGHT -(self.hidesBottomBarWhenPushed?0:self.tabBarController.tabBar.frame.size.height) -(self.extensionView?self.extensionView.frame.size.height:0));
}



- (void)initSubviews{

    
    NSArray *segtitiles = segtitiles = @[@"下载列表",@"上传列表"];

    UISegmentedControl *segmentControl = [[UISegmentedControl alloc]initWithItems:segtitiles];
    segmentControl.apportionsSegmentWidthsByContent = NO;
    segmentControl.tintColor = [UIColor clearColor];//去掉颜色,现在整个segment都看不见
    segmentControl.backgroundColor = [UIColor colorWithRed:0.969 green:0.969 blue:0.961 alpha:1.000];
    NSDictionary* selectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:14],
                                             NSForegroundColorAttributeName: [UIColor colorWithRed:0.000 green:0.475 blue:1.000 alpha:1.000]};
    [segmentControl setTitleTextAttributes:selectedTextAttributes forState:UIControlStateSelected];//设置文字属性
    NSDictionary* unselectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:14],
                                               NSForegroundColorAttributeName: [UIColor colorWithWhite:0.510 alpha:1.000]};
    [segmentControl setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];
    segmentControl.segmentedControlStyle = UISegmentedControlStyleBar;
    [segmentControl addTarget:self action:@selector(segmentaction:) forControlEvents:UIControlEventValueChanged];
    segmentControl.layer.borderColor = LineForSubLineViewColor.CGColor;
    segmentControl.layer.borderWidth = 0.5;
    segmentControl.selectedSegmentIndex = 0;
    
    if ([self.pid isEqualToString:@"0"]) {
        segmentControl.frame = CGRectMake(0, 0, self.view.frame.size.width, KSegmentH);
    }else segmentControl.frame = CGRectZero;
    
    [self.view addSubview:segmentControl];
    self.segmentControl = segmentControl;
    
    
    UITableView *mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(segmentControl.frame), self.view.frame.size.width, SCREEN_HEIGHT - segmentControl.frame.size.height - NavBarHeight - STATUSBAR_HEIGHT - (![self.pid isEqualToString:@"0"]?0:self.tabBarController.tabBar.frame.size.height)) style:UITableViewStylePlain];
    mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    mainTableView.delegate = self;
    mainTableView.dataSource = self;
    mainTableView.tableFooterView = [[UIView alloc]init];
    mainTableView.tableFooterView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:mainTableView];
    self.mainTableView = mainTableView;
    
}

#warning 2017-06-30 获取doing和waiting的数据,加入center进行任务, pause的手动处理.
- (void)initData
{
    [self.downloadProcessDataArray removeAllObjects];
    [self.downloadFinishDataArray removeAllObjects];
    [self.uploadProcessDataArray removeAllObjects];
    [self.uploadFinishDataArray removeAllObjects];

    __weak typeof(self)weakSelf = self;
    
    __weak typeof(self.mainTableView)weakTableView = self.mainTableView;
        
    [kCloudStorageDB getSubFileFolderUpSuccessFileWithPid:self.pid ResultBlock:^(NSArray *result) {
        
        for (CSFileDownUpModel *csFileDownUpModel in result) {
            CSFileDownUpFrameModel *frameModel = [[CSFileDownUpFrameModel alloc]initWithCSFileDownUpModel:csFileDownUpModel];
            [weakSelf.uploadFinishDataArray addObject:frameModel];
            
        }

        [weakTableView reloadData];
    }];
    
#warning list根据cagegory =0 及 pid来.首次如果pid不存在, 则使用cagegory =0 , 然后点击后,pid赋值..
    [kCloudStorageDB getSubFileFolderUpUnFinishedFileWithPid:self.pid ResultBlock:^(NSArray *result) {
        
        for (CSFileDownUpModel *csFileDownUpModel in result) {
            
            CSFileDownUpFrameModel *frameModel = [[CSFileDownUpFrameModel alloc]initWithCSFileDownUpModel:csFileDownUpModel];
            [weakSelf.uploadProcessDataArray addObject:frameModel];
            
        }
        
        [weakTableView reloadData];
    }];
    
    
    //下载成功的条件: 符合条件pid的文件,以及文件夹且子文件都成功.

    [kCloudStorageDB getSubFileFolderDownSuccessFileWithPid:self.pid ResultBlock:^(NSArray *result) {
       
        for (CSFileDownUpModel *csFileDownUpModel in result) {
            CSFileDownUpFrameModel *frameModel = [[CSFileDownUpFrameModel alloc]initWithCSFileDownUpModel:csFileDownUpModel];
            [weakSelf.downloadFinishDataArray addObject:frameModel];
            
        }
        
         [weakTableView reloadData];
    }];
    
    //文件夹单独放出来进行判断.
    
    [kCloudStorageDB getSubFileFolderDownUnFinishedFileWithPid:self.pid ResultBlock:^(NSArray *result) {
        
        for (CSFileDownUpModel *csFileDownUpModel in result) {
            
            CSFileDownUpFrameModel *frameModel = [[CSFileDownUpFrameModel alloc]initWithCSFileDownUpModel:csFileDownUpModel];
            
            [weakSelf.downloadProcessDataArray addObject:frameModel];
           
        }
      
         [weakTableView reloadData];
    }];
    
    
}


//间隔一秒种.防止和上一个成功的ui刷新冲突
- (void)registeUploadCenter
{

    __weak typeof(self)weakself = self;
    __weak typeof(self.mainTableView)weakTableView = self.mainTableView;

    //上传暂不考虑文件夹
    [CloudStorageUploadCenter sharedInstance].fileUpStatusChangeBlock = ^(CSFileDownUpModel *csFileDownUpModel){
    
       
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"csFileDownUpModel.downUpUUID = %@", csFileDownUpModel.downUpUUID]; //过滤条件
        
//        NSMutableArray *tempArray = [NSMutableArray array];
        
        NSArray *filteredArray= [weakself.uploadProcessDataArray filteredArrayUsingPredicate:predicate]; //最终结果filteredArray
        
        if (filteredArray.count) {
            CSFileDownUpFrameModel *uploadingFrameModel = filteredArray[0];
            uploadingFrameModel.csFileDownUpModel.downUpStatus = csFileDownUpModel.downUpStatus;
            
            if (weakself.downUpModel == DownUpModelUp) {
                
                 NSInteger index = [weakself.uploadProcessDataArray indexOfObject:uploadingFrameModel];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                     [weakTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
                });
               
            }
            
           
            
            
        }else{
        
            //是否可能不存在需要新增的情况>?
        }
        
    };
    
    //cell register ui process block.
}

- (void)registeDownloadCenter
{
    //先判断文件是否存在,没有,则判断上层(递归)文件夹是否存在.,或则反过来,判断所有的文件夹是否包含通知过来的文件,有则开始更新该文件夹cell.,同文件不同位置的情况?不管ifelase,都判断?,先文件,再文件夹.
    __weak typeof(self)weakself = self;
    __weak typeof(self.mainTableView)weakTableView = self.mainTableView;
    //文件开始下载的通知

    [CloudStorageDownloadCenter sharedInstance].fileDownStatusChangeBlock = ^(CSFileDownUpModel *fileDownUpModel){
    
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"csFileDownUpModel.downUpUUID = %@", fileDownUpModel.downUpUUID]; //过滤条件
        NSArray *filteredArray= [weakself.downloadProcessDataArray filteredArrayUsingPredicate:predicate]; //最终结果filteredArray
        
        if (filteredArray.count) {
            CSFileDownUpFrameModel *downloaddingFrameModel = filteredArray[0];
            downloaddingFrameModel.csFileDownUpModel.downUpStatus = fileDownUpModel.downUpStatus;
            
            if (weakself.downUpModel == DownUpModelDown) {
                
                NSInteger index = [weakself.downloadProcessDataArray indexOfObject:downloaddingFrameModel];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
                  
                });
                
            }
            
        } else if(!filteredArray.count){

#warning 2017-07-20 同一文件不同位置的.情况是否已考虑?
//            //开始文件夹判断.
//            //获取当前所有文件夹
            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"csFileDownUpModel.isdir = 1"]; //过滤条件
            NSArray *filteredArray= [weakself.downloadProcessDataArray filteredArrayUsingPredicate:predicate]; //最终结果filteredArray
            for (CSFileDownUpFrameModel *downloaddingFolderFrameModel in filteredArray) {

                //md5,name.
                //判断是否有同文件.
                NSPredicate *subPredicate = [NSPredicate predicateWithFormat:@"md5 = %@ AND name = %@",fileDownUpModel.md5,fileDownUpModel.name]; //过滤条件
                NSArray *subfilteredArray= [downloaddingFolderFrameModel.csFileDownUpModel.subFileDownUpModels filteredArrayUsingPredicate:subPredicate]; //最终结果filteredArray
                if (subfilteredArray.count) {

                    //刷新当前文件夹.
                    downloaddingFolderFrameModel.csFileDownUpModel.downUpStatus = fileDownUpModel.downUpStatus;
                    if (weakself.downUpModel == DownUpModelDown) {

                        NSInteger index = [weakself.downloadProcessDataArray indexOfObject:downloaddingFolderFrameModel];

                        dispatch_async(dispatch_get_main_queue(), ^{

//                            [weakTableView reloadData];
                            [weakTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationNone];

                        });
                        
                    }
                    
                }
            
                
            }
            
        }

        
               
    };

}

- (void)registerFileFolderDownloadNotoice
{
    __weak typeof(self)weakSelf = self;
    //新增文件夹下载
    CSTabBarController *tabBarController = (CSTabBarController *)self.tabBarController;
    
    tabBarController.cloudControlerFileDownloadBlock = ^(NSArray *dbModels){
        
        
          [weakSelf initData];
#warning 2017-08-01 待完善.以及后续主动更新
        
    };
    
}

- (void)segmentaction:(UISegmentedControl *)setmentController
{
    
    self.downUpModel = (DownUpModel)setmentController.selectedSegmentIndex;
    
    [self.mainTableView reloadData];
    
}

#pragma mark -- 
#pragma mark -- tableviewDatasource

- (CSFileDownUpFrameModel *)getTargetDataArrayWithIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *dataArray = nil;
    if (indexPath.section == 0) {
        dataArray = self.processDataArray;
    }else if(indexPath.section == 1)
    {
        dataArray = self.finishDataArray;
    }
    CSFileDownUpFrameModel *frameModel = dataArray[indexPath.row];
    
    return frameModel;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
  
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.processDataArray.count;
    }else if(section == 1)
    {
        return self.finishDataArray.count;
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 
    CSFileDownUpFrameModel *frameModel = [self getTargetDataArrayWithIndexPath:indexPath];
    
    CSFileDownUpCell *csFileDownUpCell = [CSFileDownUpCell fileDownUpCellWithCSFileDownUpFrameModel:frameModel tableView:tableView indexPath:indexPath identifier:CSFileDownUpCellIdentifier opItems:@[@{@"icon":@"file_share_normal",@"title":@"分享",@"opType":@(ExtensionOPShare)},@{@"icon":@"file_delete_normal",@"title":@"删除",@"opType":@(ExtensionOPDelete)}]];
    
    csFileDownUpCell.allowsMultipleSelection = tableView.allowsMultipleSelection;
    
    csFileDownUpCell.csFileDownUpFrameModel = frameModel;
    
    csFileDownUpCell.indexPath = indexPath;
    
    __weak typeof(self.mainTableView)weakTableView = self.mainTableView;
    __weak typeof(self)weakself = self;
    
    csFileDownUpCell.extensionSwitchBlock = ^(CSFileDownUpFrameModel *csFileDownUpFrameModel){
     

        NSInteger index = [weakself.finishDataArray indexOfObject:csFileDownUpFrameModel];
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:1];
        
        csFileDownUpFrameModel.isFileExtensionOP = !csFileDownUpFrameModel.isFileExtensionOP;
        
        [weakTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        
        [weakTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:YES];
        
    };
    
    csFileDownUpCell.downUpStatusBlock = ^(CSFileDownUpFrameModel *csFileDownUpFrameModel, DownUpStatus downUpStatus){

        csFileDownUpFrameModel.csFileDownUpModel.downUpStatus = downUpStatus;

        //db save
        [kCloudStorageDB updateCSDownUpFileStatusWithCSFileDownUpModel:csFileDownUpFrameModel.csFileDownUpModel];
        
        //center notice.
        if (!csFileDownUpFrameModel.csFileDownUpModel.isdir) {
            
            if (csFileDownUpFrameModel.csFileDownUpModel.downUpType == DownUpModelUp) {
                //
                [[CloudStorageUploadCenter sharedInstance]updateOneUploadStatusWithcsfileDownUpModel:csFileDownUpFrameModel.csFileDownUpModel downUpStatus:downUpStatus];
                
            }else if (csFileDownUpFrameModel.csFileDownUpModel.downUpType == DownUpModelDown)
            {
                [[CloudStorageDownloadCenter sharedInstance]updateOneDownloadStatusWithcsfileDownUpModel:csFileDownUpFrameModel.csFileDownUpModel downUpStatus:downUpStatus];
            }
            
            //如果上层文件夹下所有文件都暂停,则上层文件夹状态也为暂停,反之如果文件夹初始暂停,其中某个文件开始,则设置文件夹状态为doing.
            //取消判断,数据库viewwillapper时会判断.
#warning 2017-08-02 bug 之：如果此时刷新，则会将同一model当前cell的block重新被父cell下的model抢注册。导致首个回调不体现。解决思路：通知上层只刷新ui，不注册block？
            
            if (weakself.parentFileResponseSubFilesBlock) {
                weakself.parentFileResponseSubFilesBlock(@[csFileDownUpFrameModel.csFileDownUpModel],weakself.parentCSFileDownUpModel,downUpStatus);
            }
            
        }else{

            NSMutableArray *tempArray = [NSMutableArray array];
            
            for (CSFileDownUpModel *csFileDownUpModel in csFileDownUpFrameModel.csFileDownUpModel.subFileDownUpModels) {
                
                if (csFileDownUpFrameModel.csFileDownUpModel.downUpType == DownUpModelDown && csFileDownUpModel.downUpStatus != DownUpStatusSuccess) {
                    
                    csFileDownUpModel.downUpStatus = csFileDownUpFrameModel.csFileDownUpModel.downUpStatus;
                    
                    //移至cengter
//                    [kCloudStorageDB updateCSDownUpFileStatusWithCSFileDownUpModel:csFileDownUpModel];
                    //需要先判断是否有同文件在进行,如果有,移除文件夹的callblock.
                    
                    if (!csFileDownUpModel.isdir && (csFileDownUpModel.downUpStatus != DownUpStatusSuccess )) {
                        
                        [tempArray addObject:csFileDownUpModel];

                    }
                   
                    //内层所有文件夹暂停下载,则外层文件夹也需要暂停.
                    
                }
                
            }
            
            [[CloudStorageDownloadCenter sharedInstance]updateDownloadStatusWithcsfileDownUpModels:tempArray downUpStatus:downUpStatus];
            
            if (weakself.parentFileResponseSubFilesBlock) {
                weakself.parentFileResponseSubFilesBlock(tempArray,weakself.parentCSFileDownUpModel,downUpStatus);
            }
         
            //DB 或者 http 获取所有文件夹下的文件
            
            //这里还是需要获取所有文件信息,需要批量操作上传下载.
        }
        
        NSInteger index = [weakself.processDataArray indexOfObject:csFileDownUpFrameModel];
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
        
        [weakTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        
        [weakTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:YES];
    };
    
#warning 2017-07-26 待修改为start next先,再1s后success first.
    csFileDownUpCell.fileDownUpSuccessBlock = ^(CSFileDownUpFrameModel *downUpFrameModel){
    
        if (weakself.parentFileResponseSubFilesBlock) {
            weakself.parentFileResponseSubFilesBlock(@[downUpFrameModel.csFileDownUpModel],weakself.parentCSFileDownUpModel,DownUpStatusSuccess);
        }
        
        NSInteger index = 0;
     
        if (downUpFrameModel.csFileDownUpModel.downUpType == DownUpModelUp) {
            
            index = [weakself.uploadProcessDataArray indexOfObject:downUpFrameModel];
            
            [weakself.uploadProcessDataArray removeObject:downUpFrameModel];
            [weakself.uploadFinishDataArray insertObject:downUpFrameModel atIndex:0];
            
            
        }else{
            
            index = [weakself.downloadProcessDataArray indexOfObject:downUpFrameModel];
        
            [weakself.downloadProcessDataArray removeObject:downUpFrameModel];
            [weakself.downloadFinishDataArray insertObject:downUpFrameModel atIndex:0];

        }
    
        //or 先next再sucess.
        dispatch_async(dispatch_get_main_queue(), ^{
#warning section header不刷新,以及小文件成功的刷新不及时
#warning willwillappear 刷新数据优化.
            if (downUpFrameModel.csFileDownUpModel.downUpType == weakself.downUpModel) {
                [weakTableView reloadData];
//                [weakTableView moveRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] toIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];//无法更新num.
//            
//                [weakTableView reloadSectionIndexTitles];
                
            }
            
        });

    };
//
    csFileDownUpCell.extensionOpBlock = ^(ExtensionOP extensionOP, CSFileDownUpFrameModel *csFileDownUpFrameModel){
                
        switch (extensionOP) {
            case ExtensionOPDelete:
                
                [weakself deleteFile:csFileDownUpFrameModel];
                
                break;
                
  
            case ExtensionOPShare:
         
                [weakself shareFile:csFileDownUpFrameModel];
                
                break;
                
            default:
                break;
        }
        
        
    };

    
    return csFileDownUpCell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    switch (self.downUpModel) {
        case DownUpModelDown:
            if (section == 0) {
                return [NSString stringWithFormat:@"正在下载 (%ld)",self.processDataArray.count];
            }else if (section == 1){
            
                return [NSString stringWithFormat:@"下载完成 (%ld)",self.finishDataArray.count];
            }
            break;
        case DownUpModelUp:
            if (section == 0) {
                return [NSString stringWithFormat:@"正在上传 (%ld)",self.processDataArray.count];
            }else if (section == 1){
                
                return [NSString stringWithFormat:@"上传完成 (%ld)",self.finishDataArray.count];
            }
            break;
            
        default:
            break;
    }
    
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
       return self.processDataArray.count?40:0;
    }else return self.finishDataArray.count?40:0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
   CSFileDownUpFrameModel *frameModel = [self getTargetDataArrayWithIndexPath:indexPath];
    
   return frameModel.cellHeight;
}

#pragma mark --
#pragma mark -- tableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    __weak typeof(self)weakSelf = self;
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    CSFileDownUpFrameModel *frameModel = [self getTargetDataArrayWithIndexPath:indexPath];
    
    if (!tableView.allowsMultipleSelection) {
        if (!frameModel.csFileDownUpModel.isdir) {
            if (frameModel.csFileDownUpModel.downUpStatus == DownUpStatusSuccess) {
                
                NSString *fileRouter = nil;
                
                if (frameModel.csFileDownUpModel.fileSouce == FileSourceFileLocal) {
                    if (frameModel.csFileDownUpModel.fileType == FileTypeImage) {
                        fileRouter = [NSString stringWithFormat:@"%@/%@",PhotosMessageDir,frameModel.csFileDownUpModel.localRootPath];
                    }else fileRouter = [NSString stringWithFormat:@"%@/%@",FileFolderFullRouter,frameModel.csFileDownUpModel.localRootPath];
                }else fileRouter = [NSString stringWithFormat:@"%@/%@",CloudStorageFullRouter,frameModel.csFileDownUpModel.localRootPath];
                
                [[FileUtils shareFileUtils]filePreViewWithOrigionPath:[NSString stringWithFormat:@"%@",fileRouter] showController:self];
            }
        }else{
            
            
            CSFileTransListController *fileTransListControll = [CSFileTransListController new];
            
            fileTransListControll.parentCSFileDownUpModel = frameModel.csFileDownUpModel;
            
            fileTransListControll.pid = frameModel.csFileDownUpModel.sid;
            
            fileTransListControll.downUpModel = frameModel.csFileDownUpModel.downUpType;
            
            fileTransListControll.parentFileResponseSubFilesBlock = ^(NSArray <CSFileDownUpModel *> *selfFileDownUpModels,CSFileDownUpModel *parentFileDownUpModel, DownUpStatus downUpStatus){
            
                [weakSelf subFileOperateWithSubFiles:selfFileDownUpModels parentFolderFileModel:parentFileDownUpModel downUpStutas:downUpStatus];
            };
            
            fileTransListControll.title = frameModel.csFileDownUpModel.name;
            
            [self.navigationController pushViewController:fileTransListControll animated:YES];
            
        }
        

    }else{
    
#warning 2017-07-20 未完成上传的文件不可分享.sid无.待进一步优化.
        frameModel.isSelected = !frameModel.isSelected;
        
        if (frameModel.isSelected) {
            [self.muiltSelectFilesArray addObject:frameModel];
            
        }else [self.muiltSelectFilesArray removeObject:frameModel];
        
        
        if (self.muiltSelectFilesArray.count) {
            
            self.extensionView.disable = NO;
            
        }else self.extensionView.disable = YES;
        
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        
    }
    
}


- (DownUpStatus)judgeFileFolderStatusWithFileFolderModel:(CSFileDownUpModel *)csFileFolderModel
{
    NSInteger successNum = 0;
    NSInteger faiureNum = 0;
    NSInteger doingNum = 0;
    NSInteger waitNum = 0;
    NSInteger pauseNum = 0;
    
    //暂停条件,不存在doing和wating下,只有pause和success,faiure.
    DownUpStatus fileFolderStatus = DownUpStatusSuccess;
    
    NSArray *tempArray = csFileFolderModel.subFileDownUpModels;
    
    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;
    
    return fileFolderStatus;
}

#pragma mark --
#pragma mark -- celOp汇总
- (void)deleteFiles:(NSArray<CSFileDownUpFrameModel*> *)files
{
    //下载同时删除本地文件.多数据同一文件的情况--,不同pid,同name和Md5文件
    
    //上传只删除数据库.
    
    __block NSMutableArray *tempArray = [NSMutableArray array];
    
    [files enumerateObjectsUsingBlock:^(CSFileDownUpFrameModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [tempArray addObject:obj.csFileDownUpModel];
    }];
    
    
    __weak typeof(self)weakself = self;

    [kCloudStorageDB deleteCSDownUpFiles:tempArray downUpType:self.downUpModel ResultBlock:^(NSArray *files) {
        
        //取消任务.
        if (weakself.downUpModel == DownUpModelDown) {
            
            [[CloudStorageDownloadCenter sharedInstance]updateDownloadStatusWithcsfileDownUpModels:files downUpStatus:DownUpStatusDelete];
            
        }else{
        
            [[CloudStorageUploadCenter sharedInstance]updateUploadStatusWithcsfileDownUpModels:files downUpStatus:DownUpStatusDelete];
            
        }
        //如果一个md5和name相同的数据库只有1个,则删除文件,否则只删除文件.
        for(CSFileDownUpModel *csFileDownUpModel  in files) {
            if (!csFileDownUpModel.isdir && csFileDownUpModel.fileSouce == FileSourceCSCloud) {
                NSError *error = nil;
                [[NSFileManager defaultManager]removeItemAtPath:[NSString stringWithFormat:@"%@/%@",CloudStorageFullRouter,csFileDownUpModel.localRootPath] error:&error];
            }
        }
    }];
    
    
    
    [self.finishDataArray removeObjectsInArray:files];
    [self.processDataArray removeObjectsInArray:files];
    
    [self.mainTableView reloadData];
    
    if (self.muiltSelectFilesArray.count) {
    
        [self.muiltSelectFilesArray removeAllObjects];
        
        self.extensionView.disable = YES;
        
    }
    
}

- (void)deleteFile:(CSFileDownUpFrameModel *)file
{
    [self deleteFiles:@[file]];
}

- (void)shareFiles:(NSArray<CSFileDownUpFrameModel*> *)files
{
//    __block NSMutableArray *tempArray = [NSMutableArray array];
//    
//    [files enumerateObjectsUsingBlock:^(CSFileDownUpFrameModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        [tempArray addObject:obj.csFileDownUpModel];
//    }];
//    
//    NewMessageTransController *tanrsController = [NewMessageTransController new];
//    tanrsController.csfilesArray = tempArray;
//    tanrsController.isDisableMulitselect = YES;
//    IWNavigationController *navCor = [[IWNavigationController alloc]initWithRootViewController:tanrsController];
//    
//    [self.navigationController presentViewController:navCor animated:YES completion:nil];
}

- (void)shareFile:(CSFileDownUpFrameModel *)file
{

    [self shareFiles:@[file]];
    
    
}

/**
 *  对父文件夹进行操作,含递归.
 */
- (void)subFileOperateWithSubFiles:(NSArray *)subFiles parentFolderFileModel:(CSFileDownUpModel *)parentFileDownUpModel downUpStutas:(DownUpStatus)downUpStatus
{
    
    __weak typeof(self)weakSelf = self;
    
    __weak typeof(self.mainTableView)weakTableView = self.mainTableView;
    
#warning 2017-08-02 bug之首次点击二级页面未注册process - block.
    //先修改文件夹状态.
    NSArray *targetFileFolder = [weakSelf.downloadProcessDataArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"csFileDownUpModel.downUpUUID = %@",parentFileDownUpModel.downUpUUID]];
    
    if (targetFileFolder.count) {
        
        CSFileDownUpFrameModel *folerFileDownUpFrameModel = targetFileFolder[0];
        
        for (CSFileDownUpModel *subCsFileDownUpModel in subFiles) {
            
            NSArray *targetParentFolderFiles = [folerFileDownUpFrameModel.csFileDownUpModel.subFileDownUpModels filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"md5 = %@ and name = %@",subCsFileDownUpModel.md5,subCsFileDownUpModel.name]];
            
            for (CSFileDownUpModel *currentSubFiles in targetParentFolderFiles) {
                currentSubFiles.downUpStatus = downUpStatus;
                currentSubFiles.downUpSize = subCsFileDownUpModel.downUpSize;
            }
        }
        
        
        DownUpStatus newFolderStatus = [weakSelf judgeFileFolderStatusWithFileFolderModel:folerFileDownUpFrameModel.csFileDownUpModel];
        
        if (newFolderStatus != folerFileDownUpFrameModel.csFileDownUpModel.downUpStatus) {
            
            if (newFolderStatus == DownUpStatusSuccess) {
                
                [weakSelf.downloadProcessDataArray removeObject:folerFileDownUpFrameModel];
                
                [weakSelf.downloadFinishDataArray addObject:folerFileDownUpFrameModel];
                
                [weakTableView reloadData];
                
            }else{
                folerFileDownUpFrameModel.csFileDownUpModel.downUpStatus = newFolderStatus;
                
                NSInteger index = [weakSelf.downloadProcessDataArray indexOfObject:folerFileDownUpFrameModel];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
                });
            }
            
            
        }
        
    }
    
    
    //如果成功,需要移动.
//    if (downUpStatus == DownUpStatusSuccess) {
//        
//        
//        CSFileDownUpModel *selfFileDownUpModel = subFiles[0];
//        
//        //同理,暂停,开始,都可以.
//        NSMutableArray *needMoveframeModels = [NSMutableArray array];
//        NSMutableArray *needMoveIndexs = [NSMutableArray array];
//        
//        NSArray *targetFileFolder = [weakSelf.downloadProcessDataArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"csFileDownUpModel.downUpUUID = %@",parentFileDownUpModel.downUpUUID]];
//        
//        NSArray *targetSameFiles = [weakSelf.downloadProcessDataArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"csFileDownUpModel.md5 = %@ and csFileDownUpModel.name = %@",selfFileDownUpModel.md5,selfFileDownUpModel.name]];//获取取消父节点?for递归文件夹subfiles及文件.
//        
//        if (targetFileFolder.count) {
//            
//            CSFileDownUpFrameModel *folerFileDownUpFrameModel = targetFileFolder[0];
//            folerFileDownUpFrameModel.csFileDownUpModel.downUpStatus = DownUpStatusDoing;
//            NSArray *targetParentFolderFiles = [folerFileDownUpFrameModel.csFileDownUpModel.subFileDownUpModels filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"md5 = %@ and name = %@",selfFileDownUpModel.md5,selfFileDownUpModel.name]];
//            for (CSFileDownUpModel *subFilesInFolder in targetParentFolderFiles) {
//                subFilesInFolder.downUpStatus = selfFileDownUpModel.downUpStatus;
//                subFilesInFolder.downUpSize = selfFileDownUpModel.downUpSize;
//            }
//            
//            if([weakSelf judgeFileFolderStatusWithFileFolderModel:folerFileDownUpFrameModel.csFileDownUpModel] == DownUpStatusSuccess){
//                
//                folerFileDownUpFrameModel.csFileDownUpModel.downUpStatus = DownUpStatusSuccess;
//                
//                [needMoveframeModels addObject:folerFileDownUpFrameModel];
//                
//                NSInteger index = [weakSelf.downloadProcessDataArray indexOfObject:folerFileDownUpFrameModel];
//                
//                [needMoveIndexs addObject:[NSIndexPath indexPathForRow:index inSection:0]];
//            }
//            
//            //修改targetSubFolderFiles状态
//            //判断subs是否都成功,如果成功,则修改folerFileDownUpModel位置.
//        }
//        
//        if (targetSameFiles.count) {
//            
//            for (CSFileDownUpFrameModel *csFileDownUpFrameModel in targetSameFiles) {
//                csFileDownUpFrameModel.csFileDownUpModel.downUpStatus = selfFileDownUpModel.downUpStatus;
//                csFileDownUpFrameModel.csFileDownUpModel.downUpSize = selfFileDownUpModel.downUpSize;
//                
//                [needMoveframeModels addObjectsFromArray:targetSameFiles];
//                
//                NSInteger index = [weakSelf.downloadProcessDataArray indexOfObject:csFileDownUpFrameModel];
//                
//                [needMoveIndexs addObject:[NSIndexPath indexPathForRow:index inSection:0]];
//            }
//            
//            
//            
//        }
//        
//        if (needMoveframeModels.count) {
//            
//            [weakSelf.downloadProcessDataArray removeObjectsInArray:needMoveframeModels];
//            
//            [weakSelf.downloadFinishDataArray addObjectsFromArray:needMoveframeModels];
//            
//            dispatch_async(dispatch_get_main_queue(), ^{
//                 [weakSelf.mainTableView reloadData];
//            });
//           
//            //                [weakSelf.mainTableView deleteRowsAtIndexPaths:needMoveIndexs withRowAnimation:UITableViewRowAnimationNone];
//            //                weakSelf.mainTableView i
//        }
//        
//    }
    
    //递归.
    if (weakSelf.parentFileResponseSubFilesBlock) {
        weakSelf.parentFileResponseSubFilesBlock(subFiles,weakSelf.parentCSFileDownUpModel,downUpStatus);
    }

}

- (void)dealloc
{
    
}

@end
