//
//  CSFirstPageController.m
//  zhuxun
//
//  Created by winsoft on 17/6/15.
//
//
#import <Bugly/Bugly.h>
#import "CSAlertView.h"
#import "CSFirstPageController.h"

//#import "NewMessageTransController.h"

#import "IWNavigationController.h"

#import "CSTabBarController.h"

#import "CSRouterSelectController.h"

#import "HttpRequest.h"
#import <MJExtension/MJExtension.h>

#import "UIBarButtonItem+Addition.h"

#import "UIActionSheet+Blocks.h"

#import "UIAlertView+Blocks.h"

#import "CloudStorageDownloadCenter.h"

#import "CSFileCell.h"

#import "CSFileExtensionViewForCell.h"

#import "CloudStorageBar.h"

#import "CloudStorageTableView.h"

#import "CSFileTypeClassView.h"

#import "CSFileFrameModel.h"

#import "CloudStorageDB.h"

#define TabBarHeight  ((self.hidesBottomBarWhenPushed == 0) ?  (self.tabBarController.tabBar.frame.size.height) : 0)
//剥离ui/控制器可以复用.

@interface CSFirstPageController ()<UITableViewDelegate, UITableViewDataSource, CSSearchBarDelegate>

/**
 *  来源,可提供的网盘文件操作不同
 */
@property (nonatomic , assign) CSFileSourceType csFileSourceType;
@property (nonatomic , copy) NSString *pid;
@property (nonatomic , copy) NSString *shareID;
#warning 2017-07-17


@property (nonatomic , weak) CloudStorageTableView *mainTableView;
@property (nonatomic , weak) CSFileExtensionViewForCell *csFilesExensionView;
@property (nonatomic , weak) CSFileTypeClassView *csFileTypeClassView;
/**
 *  根据是否searchmodel 选择normal还是search array
 */
@property (nonatomic , strong) NSMutableArray *fileModelArray;

@property (nonatomic , strong) NSMutableArray *normalFilesArray;
@property (nonatomic , strong) NSMutableArray *searchResultArray;

@property (nonatomic , assign) BOOL searchModel;
/**
 *  多选操作.
 */
@property (nonatomic , strong) NSMutableArray *muilterOpFilesArray;

@property (nonatomic , strong) CSFileModel *father_csFileModel;
@end

@implementation CSFirstPageController

- (NSMutableArray *)fileModelArray
{
    if (self.searchModel) {
        return self.searchResultArray;
    }else return self.normalFilesArray;
    
}

- (NSMutableArray *)normalFilesArray
{
    if (!_normalFilesArray) {
        _normalFilesArray = [NSMutableArray array];
    }
    
    return _normalFilesArray;
}

- (NSMutableArray *)searchResultArray
{
    if (!_searchResultArray) {
        
        _searchResultArray = [NSMutableArray array];
    }
    
    return _searchResultArray;
}

- (NSMutableArray *)muilterOpFilesArray
{
    if (!_muilterOpFilesArray) {
        _muilterOpFilesArray = [NSMutableArray array];
    }
    
    return _muilterOpFilesArray;
}

//首次启动使用.
+ (CSFirstPageController *)csFirstPageControllerWithCSFileSourceType:(CSFileSourceType)csFileSourceType pid:(NSString *)pid shareId:(NSString *)shareId
{
    
    CSFirstPageController *csFirstPageController = [[CSFirstPageController alloc]initCSFirstPageControllerWithCSFileSourceType:csFileSourceType pid:pid shareId:shareId];
    
    
    return csFirstPageController;
    
}

- (instancetype)initCSFirstPageControllerWithCSFileSourceType:(CSFileSourceType)csFileSourceType pid:(NSString *)pid shareId:(NSString *)shareId
{
    if (self = [super init]) {
        self.csFileSourceType = csFileSourceType;
        _pid = pid;
        _shareID = shareId;
        
        if (csFileSourceType == CSFileSourceTypeSelf) {
            self.title = @"我的网盘";
        }else self.title = @"分享";
        
        self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(outCloudStorage) icon:@"returnBackArrow" highlightedIcon:nil title:nil iconSize:CGSizeMake(20, 20) fontSize:14 titleColor:[UIColor whiteColor]];
    }
    
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (self.searchModel) {
        
        CGPoint point = CGPointMake(0, STATUSBAR_HEIGHT);
        
        //        self.tabBarController.tabBar.isHidden
        __block CGRect adjusetedFrame = CGRectMake(point.x, point.y, SCREEN_WIDTH, SCREEN_HEIGHT - NavBarHeight + STATUSBAR_HEIGHT - TabBarHeight);
        
        [self.navigationController setNavigationBarHidden:YES animated:YES];
        
        [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
        
        self.mainTableView.frame = adjusetedFrame;
        
    }else{
        
        __block CGRect origionFrame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - STATUSBAR_HEIGHT - NavBarHeight - TabBarHeight);
        
        [self.navigationController setNavigationBarHidden:NO animated:YES];
        
        self.mainTableView.frame = origionFrame;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if([self respondsToSelector:@selector(setEdgesForExtendedLayout:)])
    {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    
    UIBarButtonItem *muiltSelectItem = [UIBarButtonItem itemWithTarget:self action:@selector(moreOperate) icon:@"navbar_muiltSel" highlightedIcon:nil title:nil iconSize:CGSizeMake(20, 20) fontSize:14 titleColor:[UIColor whiteColor]];
    
    UIBarButtonItem *fileClassItem = [UIBarButtonItem itemWithTarget:self action:@selector(classFile) icon:nil highlightedIcon:nil title:@"分类" iconSize:CGSizeZero fontSize:14 titleColor:[UIColor whiteColor]];
    
    if ([self.pid isEqualToString:@"0"] && self.csFileSourceType == CSFileSourceTypeSelf) {
        
        self.navigationItem.rightBarButtonItems = @[muiltSelectItem, fileClassItem];
        
    }else self.navigationItem.rightBarButtonItems = @[muiltSelectItem];
    
    [self initSubViews];
    
    
    if (self.pid) {
        
        [self getTopFilesLists];
    }
    
    if (self.shareID) {
        [self getAllShareFiles];
    }
    
}

- (void)outCloudStorage
{
    if (self.tabBarController) {
        [self.tabBarController dismissViewControllerAnimated:YES completion:nil];
    }else [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)moreOperate
{
    if (self.csFileTypeClassView) {
        [self.csFileTypeClassView removeFromSuperview];
        self.csFileTypeClassView = nil;
    }
    
    self.mainTableView.allowsMultipleSelection = !self.mainTableView.allowsMultipleSelection;
    
    //置空.
    for (CSFileFrameModel *fileFrameModel in self.fileModelArray) {
        fileFrameModel.isFileExtensionOP = NO;
        fileFrameModel.isSelected = NO;
    }
    
    [self.muilterOpFilesArray removeAllObjects];
    
    [self.mainTableView reloadData];
    
    __weak typeof(self)weakSelf = self;
    __weak typeof(self.mainTableView)weakTableView = self.mainTableView;
    __weak typeof(self.view)weakView = self.view;
    if (self.mainTableView.allowsMultipleSelection) {
        
        CSFileExtensionViewForCell *extensionView = nil;
        
        if (self.csFileSourceType == CSFileSourceTypeSelf) {
            extensionView = [[CSFileExtensionViewForCell alloc]initWithItmes:@[@{@"icon":@"file_down_narmal",@"title":@"下载",@"opType":@(ExtensionOPDownLoad)},@{@"icon":@"file_share_normal",@"title":@"分享",@"opType":@(ExtensionOPShare)},@{@"icon":@"file_delete_normal",@"title":@"删除",@"opType":@(ExtensionOPDelete)},@{@"icon":@"file_move_normal",@"title":@"迁移",@"opType":@(ExtensionOPEdit)}]];
        }else{
            
            extensionView = [[CSFileExtensionViewForCell alloc]initWithItmes:@[@{@"icon":@"file_down_narmal",@"title":@"下载",@"opType":@(ExtensionOPDownLoad)}]];
        }
        
        extensionView.extensionOpBlock = ^(ExtensionOP extensionOP, CSFileFrameModel *csFileFrameModel){
            
            switch (extensionOP) {
                case ExtensionOPDelete:
                    [weakSelf fileDeletesWithFileFrameModels:weakSelf.muilterOpFilesArray];
                    break;
                    
                case ExtensionOPEdit:
                    //yidong 文件夹;
                    [weakSelf moveCSFilesWithFileModels:weakSelf.muilterOpFilesArray];
                    break;
                case ExtensionOPShare:
                    //分享 文件夹;
                    [weakSelf shareFilesToUserOrGroups:weakSelf.muilterOpFilesArray];
                    break;
                case ExtensionOPDownLoad:
                    
                    //2017-07-17 待对多文件夹选择进行合并请求
                    [weakSelf downloadFileWithFileModels:weakSelf.muilterOpFilesArray];
                    
                    [Utils showSuccess:@"已加入下载队列" toView:weakView finish:nil];
                    
                    break;
                    
                    
                default:
                    break;
            }
        };
        
        extensionView.disable = YES;
        
        extensionView.frame = CGRectMake(0, self.view.frame.size.height -  FileExtensionViewH, SCREEN_WIDTH, FileExtensionViewH);
        
        [self.view addSubview:extensionView];
        
        self.csFilesExensionView = extensionView;
        
    }else{
        
        [self.csFilesExensionView removeFromSuperview];
        self.csFilesExensionView = nil;
        
    }
    
    //调整tableview.frame
    self.mainTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NavBarHeight - STATUSBAR_HEIGHT -(self.hidesBottomBarWhenPushed?0:self.tabBarController.tabBar.frame.size.height) -(self.csFilesExensionView?self.csFilesExensionView.frame.size.height:0));
    
}

- (void)classFile
{
    __weak typeof(self)weakself = self;
    
    if (!self.csFileTypeClassView) {
        CSFileTypeClassView *csFileTypeClassView = [[CSFileTypeClassView alloc]init];
        csFileTypeClassView.utilityOperateBlock = ^(CSFileType csFileType){
            
            [weakself classFileWithFileType:csFileType];
            
            //hidden
            [weakself classFile];
            
        };
        [self.view addSubview:csFileTypeClassView];
        
        [UIView transitionWithView:csFileTypeClassView
                          duration:1
                           options:UIViewAnimationOptionShowHideTransitionViews //any animation
                        animations:^ { }
                        completion:nil];
        [self.view addSubview:csFileTypeClassView];
        

//        [self.view addSubview:csFileTypeClassView];
        
        
        csFileTypeClassView.frame = CGRectMake(0, 0, self.view.frame.size.width, CSFileTypeClassViewH);
        self.csFileTypeClassView = csFileTypeClassView;
        
    }else{
        
        [self.csFileTypeClassView removeFromSuperview];
        self.csFileTypeClassView = nil;
    }
    
    
    
}


- (void)initSubViews
{
    
    CloudStorageTableView *mainTableView = [[CloudStorageTableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NavBarHeight - STATUSBAR_HEIGHT - TabBarHeight) 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;
    
    
    if (self.csFileSourceType == CSFileSourceTypeSelf) {
        
        __weak typeof(self)weakSelf = self;
        CloudStorageBar *cloudStorageBar = [CloudStorageBar new];
        
        cloudStorageBar.delegate = self;
        
        cloudStorageBar.barSortBlock = ^(SortType sortType){
            
            [weakSelf sortFilesWithSortType:sortType];
        };
        
        cloudStorageBar.barNewFolderBlock = ^(){
            
            [weakSelf createNewFileFolder];
            
        };
        
        cloudStorageBar.frame = CGRectMake(0, 0, self.view.frame.size.width, CloudStorageBarHeight);
        mainTableView.tableHeaderView = cloudStorageBar;
        
        __weak typeof(cloudStorageBar)weakCSBar = cloudStorageBar;
        mainTableView.gestureResponseBlock = ^(){
            //退出搜索
            [weakCSBar giveUpSearch];
            
            //退出筛选
            if (weakSelf.csFileTypeClassView) {
                [weakSelf classFile];
            }
        };
        
    }
}

#pragma mark --
#pragma mark -- tableViewDatasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.fileModelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CSFileCell *csFileCell = nil;
    if (self.csFileSourceType == CSFileSourceTypeSelf) {
        
        csFileCell = [CSFileCell fileCellWithTableView:tableView indexPath:indexPath identifier:CSFileCellIdentifier opItems:@[@{@"icon":@"file_down_narmal",@"title":@"下载",@"opType":@(ExtensionOPDownLoad)},@{@"icon":@"file_share_normal",@"title":@"分享",@"opType":@(ExtensionOPShare)},@{@"icon":@"file_delete_normal",@"title":@"删除",@"opType":@(ExtensionOPDelete)},@{@"icon":@"file_down_rename_normal",@"title":@"重命名",@"opType":@(ExtensionOPEdit)}]];
    }else
    {
        csFileCell = [CSFileCell fileCellWithTableView:tableView indexPath:indexPath identifier:CSFileCellIdentifier opItems:@[@{@"icon":@"file_down_narmal",@"title":@"下载",@"opType":@(ExtensionOPDownLoad)}]];
    }
    
    
    csFileCell.allowsMultipleSelection = tableView.allowsMultipleSelection;
    
    csFileCell.csFileFrameModel = self.fileModelArray[indexPath.row];
    
    csFileCell.indexPath = indexPath;
    __weak typeof(self.mainTableView)weakTableView = self.mainTableView;
    __weak typeof(self.view)weakView = self.view;
    __weak typeof(self)weakself = self;
    
    csFileCell.extensionSwitchBlock = ^(CSFileFrameModel *csFileFrameModel){
        
        NSInteger index = [weakself.fileModelArray indexOfObject:csFileFrameModel];
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
        
        csFileFrameModel.isFileExtensionOP = !csFileFrameModel.isFileExtensionOP;
        
        [weakTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        
        [weakTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:YES];
        
    };
    
    csFileCell.extensionOpBlock = ^(ExtensionOP extensionOP, CSFileFrameModel *csFileFrameModel){
        
        switch (extensionOP) {
            case ExtensionOPDelete:
                [weakself fileDeletesWithFileFrameModels:@[csFileFrameModel]];
                break;
                
            case ExtensionOPEdit:
                [weakself renameFilesWithFileFrameModel:csFileFrameModel indexPath:indexPath];
                break;
                
            case ExtensionOPShare:
                //yidong 文件夹;
                [weakself shareFilesToUserOrGroups:@[csFileFrameModel]];
                break;
            case ExtensionOPDownLoad:
                //download 文件;
                [weakself downloadFileWithFileModels:@[csFileFrameModel]];
                
                [Utils showSuccess:@"已加入下载队列" toView:weakView finish:nil];
                break;
                
            default:
                break;
        }
        
        
    };
    
    return csFileCell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CSFileFrameModel *csFileFrameModel = self.fileModelArray[indexPath.row];
    return csFileFrameModel.cellHeight;
}


#pragma mark --
#pragma mark -- tableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    CSFileFrameModel *csFileFrameModel = self.fileModelArray[indexPath.row];
    
    if (tableView.allowsMultipleSelection) {
        csFileFrameModel.isSelected = !csFileFrameModel.isSelected;
        
        if (csFileFrameModel.isSelected) {
            [self.muilterOpFilesArray addObject:csFileFrameModel];
            
        }else [self.muilterOpFilesArray removeObject:csFileFrameModel];
        
        
        if (self.muilterOpFilesArray.count) {
            
            self.csFilesExensionView.disable = NO;
            
        }else self.csFilesExensionView.disable = YES;
        
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    }else{
        
        //
        CSFileModel *csFileModel = csFileFrameModel.fileModel;
        
        if (csFileModel.isdir) {
            //文件夹
            CSFirstPageController *csPage =  [CSFirstPageController new];
            csPage.title = csFileModel.name;
            csPage.pid = csFileModel.sid;
            csPage.csFileSourceType = self.csFileSourceType;
            csPage.father_csFileModel = csFileModel;
            //            __block CGRect origionFrame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - STATUSBAR_HEIGHT - NavBarHeight);
            //
            //            [self.navigationController setNavigationBarHidden:NO animated:NO];
            //
            //            self.mainTableView.frame = origionFrame;
            
            [self.navigationController pushViewController:csPage animated:YES];
            
            
        }
        
    }
    
    
    
    
    
}

#pragma mark --
#pragma mark -- CSBarDelegate
- (void)searchBarStartSearch:(UISearchBar *)searchBar withSearchContent:(NSString *)searchContent
{
    [self searchFilesWithContent:searchContent];
}

- (void)searchBarPrepareToSearch
{
    self.searchModel = YES;
    
    [self.mainTableView reloadData];
    
    CGPoint point = CGPointMake(0, STATUSBAR_HEIGHT);
    __block CGRect adjusetedFrame = CGRectMake(point.x, point.y, SCREEN_WIDTH, SCREEN_HEIGHT - NavBarHeight - TabBarHeight + STATUSBAR_HEIGHT);
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
    
    self.mainTableView.frame = adjusetedFrame;
    
}


- (void)searchBarCancerSearch
{
    self.searchModel = NO;
    
    [self.mainTableView reloadData];
    
    __block CGRect origionFrame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - STATUSBAR_HEIGHT - NavBarHeight - TabBarHeight);
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    self.mainTableView.frame = origionFrame;
}

#pragma mark --
#pragma mark -- fileOp汇总

- (void)fileDeletesWithFileFrameModels:(NSArray *)fileFrameModels
{
    NSMutableArray *fileIds = [NSMutableArray array];
    
    NSMutableArray *indexArray = [NSMutableArray array];
    
    for (CSFileFrameModel *csFileFrameModel in fileFrameModels) {
        [fileIds addObject:csFileFrameModel.fileModel.sid];
        
        NSInteger index = [self.fileModelArray indexOfObject:csFileFrameModel];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
        [indexArray addObject:indexPath];
        
    }
    
    UIActionSheet *sheet = [UIActionSheet actionSheetWithTitle:@"请选择删除方式" cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"彻底删除",@"移到垃圾桶"] completionBlock:^(UIActionSheet *actionSheet, NSInteger selectedButtonIndex) {
        
        [Utils showWaitingToView:self.mainTableView];
        
        __weak typeof(self.mainTableView)weakTableView = self.mainTableView;
        __weak typeof(self.csFilesExensionView)weakExtensionView = self.csFilesExensionView;
        __weak typeof(self)weakself = self;
        
        [[HttpRequest sharedManager]cloudStorageFileDeleteWithItemIDs:fileIds deleteLevel:selectedButtonIndex complete:^(BOOL success, id data, NSError *error) {
            
            [Utils HiddenWaitingToView:weakTableView];
            
            if (success && data) {
                
                [Utils showSuccess:@"删除成功" toView:weakTableView finish:nil];
                
                [weakself.fileModelArray removeObjectsInArray:fileFrameModels];//删除数据源 内对于的对象
                
                
                [weakTableView deleteRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationBottom];
                
                
                weakExtensionView.disable = YES;
                //[weakTableView beginUpdates];
            }else{
                
                [Utils showError:@"删除失败" ToView:weakTableView];
            }
            
        }];
        
    } cancelBlock:^{
        
    }];
    
    [sheet showInView:self.mainTableView];
}

- (void)getTopFilesLists
{
    [self getFileListWithPid:self.pid searchKey:nil classExt:nil];
}

- (void)getAllShareFiles
{
    __weak typeof(self)weakself = self;
    __weak typeof(self.mainTableView)weakTableView = self.mainTableView;
    
    [[HttpRequest sharedManager]cloudStorageGetShareFiles:self.shareID complete:^(BOOL success, id data, NSError *error) {
        
        if (success && data) {
            NSArray *fileDataModel = [CSFileModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
            
            for (CSFileModel *fileModel in fileDataModel) {
                if (fileModel.isdir) {
                    
                    fileModel.serverFullPath = self.father_csFileModel?[NSString stringWithFormat:@"%@%@/",self.father_csFileModel.serverFullPath,fileModel.name]:[NSString stringWithFormat:@"%@/",fileModel.name];
                    
                }else fileModel.serverFullPath = self.father_csFileModel?[NSString stringWithFormat:@"%@%@",self.father_csFileModel.serverFullPath,fileModel.name]:[NSString stringWithFormat:@"%@",fileModel.name];;
                
                //不存储.
                //                [CloudStorageDB addcsFiletoDB:fileModel];
                
                CSFileFrameModel *csFileFrameModel = [[CSFileFrameModel alloc]initWithFileModel:fileModel];
                [weakself.fileModelArray addObject:csFileFrameModel];
                
            }
            
            [weakTableView reloadData];
        }
    }];
}


- (void)renameFilesWithFileFrameModel:(CSFileFrameModel *)fileFrameModel indexPath:(NSIndexPath *)indexPath
{
    
    __weak typeof(self)weakSelf = self;
    __weak typeof(self.mainTableView)weakTableView = self.mainTableView;
    
    UIAlertViewStyle type = UIAlertViewStylePlainTextInput;
    //new name
    
    [UIAlertView showAlertViewWithType:type Title:@"重命名" message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] onDismiss:^(int buttonIndex, UIAlertView *alertView) {
        
        
        UITextField *applyTextField =  [alertView textFieldAtIndex:0];
        
        if (!applyTextField.text) {
            [Utils showError:@"请输入新命名" ToView:weakTableView];
            return ;
        }
        
        [Utils showWaitingToView:weakTableView];
        
        [[HttpRequest sharedManager]cloudStorageFileReNameWithNewName:applyTextField.text fileID:fileFrameModel.fileModel.sid complete:^(BOOL success, id data, NSError *error) {
            
            [Utils HiddenWaitingToView:weakTableView];
            
            if (success && data) {
                
                [Utils showSuccess:@"重命名成功" toView:weakTableView finish:nil];
                
                //reload.
                
                //重新计算尺寸.
                CSFileFrameModel *newfileFrameModel = weakSelf.fileModelArray[indexPath.row];
                newfileFrameModel.fileModel.name = applyTextField.text;
                [newfileFrameModel renameItemWithNewFileModel:newfileFrameModel.fileModel];
                
                if (indexPath) {
                    [weakTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                }
                
            }else{
                
                [Utils showError:@"重命名失败" ToView:weakTableView];
            }
            
        }];
        
        
        
        
    } onCancel:^(UIAlertView *alertView) {
        
    }];
    
}

- (void)createNewFileFolder{
    CSAlertView * alertview = [[CSAlertView alloc]initWithTitle:@"新建文件夹" message:@"" inputMode:YES sureBtn:@"创建" cancleBtn:@"取消"];
    __weak typeof(self)weakSelf = self;
    __weak typeof(alertview)weakalertview = alertview;
    __weak typeof(self.mainTableView)weakTableView = self.mainTableView;
    [alertview showXBAlertView];
    alertview.alertresult = ^(NSString *folderName){
        [[HttpRequest sharedManager]cloudStorageCreateNewFileFolderWithFolderName:folderName pid:weakSelf.pid delflag:@"0" complete:^(BOOL success, id data, NSError *error) {
            if (success && data) {
                
                [weakalertview stopActityAndRemoveAlertView];
                
                [Utils showSuccess:@"文件夹创建成功" toView:weakTableView finish:nil];
                //reload.
                CSFileModel *csfileModel = [CSFileModel mj_objectWithKeyValues:data[@"data"]];
                
                csfileModel.serverFullPath = self.father_csFileModel?[NSString stringWithFormat:@"%@%@/",self.father_csFileModel.serverFullPath,csfileModel.name]:[NSString stringWithFormat:@"%@/",csfileModel.name];
                
                [kCloudStorageDB addcsFiletoDB:csfileModel];
                
                CSFileFrameModel *csframeModel = [[CSFileFrameModel alloc]initWithFileModel:csfileModel];
                
                [weakSelf.fileModelArray addObject:csframeModel];
                
                [weakTableView reloadData];
                //                [weakTableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:[weakTableView numberOfRowsInSection:0] - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
                //
                [weakTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:weakSelf.fileModelArray.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
            }else{
                
                [weakalertview showErrorMsg:@"文件夹创建失败"];
                NSError *createFolderError = [NSError errorWithDomain:@"com.wswinsoft.zhuxun" code:40002 userInfo:@{@"error":error,@"APIDescription":@"cloudStorageCreateNewFileFolderWithFolderName",@"param":[NSString stringWithFormat:@"foldername:%@ pid:%@",folderName,weakSelf.pid],@"systemerrorinfo":error.userInfo}];
                [Bugly reportError:createFolderError];
            }
            
            //[weakalertview stopActity];
        }];
    };
    //    CustomAlertView *alertView =
    //    alertVc.messageColor = [UIColor redColor];
    //    [alertVc alertViewControllerWithMessage:@"测试而已" andBlock:^{
    //        NSLog(@"test");
    //    }];
    //    [self.navigationController presentViewController:alertVc animated:NO completion:nil];
    //presentModalViewController:alertVc animated:YES];
    /*UIAlertViewStyle type = UIAlertViewStylePlainTextInput;
     
     __weak typeof(self)weakSelf = self;
     __weak typeof(self.mainTableView)weakTableView = self.mainTableView;
     
     //待使用新的createNEWFOLDERVIEW
     [UIAlertView showAlertViewWithType:type Title:@"新建文件夹" message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] onDismiss:^(int buttonIndex, UIAlertView *alertView) {
     
     
     UITextField *applyTextField =  [alertView textFieldAtIndex:0];
     
     if (!applyTextField.text.length) {
     [Utils showError:@"请输入文件夹名称" ToView:weakTableView];
     return ;
     }
     
     [Utils showWaitingToView:weakTableView];
     #warning 2016-06-20 貌似有连续请求的问题..
     [[HttpRequest sharedManager]cloudStorageCreateNewFileFolderWithFolderName:applyTextField.text pid:weakSelf.pid delflag:@"0" complete:^(BOOL success, id data, NSError *error) {
     
     [Utils HiddenWaitingToView:weakTableView];
     
     if (success && data) {
     //
     
     [Utils showSuccess:@"文件夹创建成功" toView:weakTableView finish:nil];
     
     //reload.
     
     CSFileModel *csfileModel = [CSFileModel mj_objectWithKeyValues:data[@"data"]];
     
     csfileModel.serverFullPath = self.father_csFileModel?[NSString stringWithFormat:@"%@%@/",self.father_csFileModel.serverFullPath,csfileModel.name]:[NSString stringWithFormat:@"%@/",csfileModel.name];
     
     [CloudStorageDB addcsFiletoDB:csfileModel];
     
     CSFileFrameModel *csframeModel = [[CSFileFrameModel alloc]initWithFileModel:csfileModel];
     
     [weakSelf.fileModelArray addObject:csframeModel];
     
     [weakTableView reloadData];
     //                [weakTableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:[weakTableView numberOfRowsInSection:0] - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
     //
     [weakTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:weakSelf.fileModelArray.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
     }else{
     
     [Utils showError:@"文件夹创建失败" ToView:weakTableView];
     }
     
     
     }];
     
     } onCancel:^(UIAlertView *alertView) {
     
     }];
     
     */}

- (void)sortFilesWithSortType:(SortType)sortType
{
    NSComparator cmptr = nil;
    //本地排序
    if (sortType == SortTypeFileName) {
        cmptr = ^(CSFileFrameModel *frameModelA, CSFileFrameModel *frameModelB){
            if (frameModelA.fileModel.name > frameModelB.fileModel.name) {
                return (NSComparisonResult)NSOrderedDescending;
            }
            
            if (frameModelA.fileModel.name < frameModelB.fileModel.name) {
                return (NSComparisonResult)NSOrderedAscending;
            }
            return (NSComparisonResult)NSOrderedSame;
            
        };
        
    }else if(sortType == SortTypeFileTime){
        
        cmptr = ^(CSFileFrameModel *frameModelA, CSFileFrameModel *frameModelB){
            if (frameModelA.fileModel.server_ctime > frameModelB.fileModel.server_ctime) {
                return (NSComparisonResult)NSOrderedDescending;
            }
            
            if (frameModelA.fileModel.server_ctime < frameModelB.fileModel.server_ctime) {
                return (NSComparisonResult)NSOrderedAscending;
            }
            return (NSComparisonResult)NSOrderedSame;
            
        };
        
    }
    NSArray *newSortArray = [self.fileModelArray  sortedArrayUsingComparator:cmptr];
    
    [self.fileModelArray removeAllObjects];
    [self.fileModelArray addObjectsFromArray:newSortArray];
    [self.mainTableView reloadData];
}

//丢给filetype choose.
- (void)classFileWithFileType:(CSFileType)fileType
{
    if (!self.searchModel) {
        
        //全目录分类,quanbu 时是否不动..
        NSString *classExtNumStr = nil;
        if (fileType != CSFileTypeAll) {
            classExtNumStr = [NSString stringWithFormat:@"%d",fileType];
        }
        [self getFileListWithPid:nil searchKey:nil classExt:classExtNumStr];
        
        
    }else{
        
        //本地搜索结果分类
        
    }
}

- (void)searchFilesWithContent:(NSString *)content
{
    self.searchModel = YES;
    
    [self getFileListWithPid:nil searchKey:content classExt:nil];
    
}

- (void)shareFilesToUserOrGroups:(NSArray *)fileModels
{
#warning 2016-06-20待新增云盘文件消息体.,转发中心待调整.
//    //取出fileModels（FrameModels）中的entity
//    NSMutableArray *tmparr = [NSMutableArray array];
//    [fileModels enumerateObjectsUsingBlock:^(CSFileFrameModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        [tmparr addObject:obj.fileModel];
//    }];
//    NewMessageTransController *tanrsController = [NewMessageTransController new];
//    tanrsController.csfilesArray = tmparr;
//    tanrsController.isDisableMulitselect = YES;
//    IWNavigationController *navCor = [[IWNavigationController alloc]initWithRootViewController:tanrsController];
//    
//    [self.navigationController presentViewController:navCor animated:YES completion:nil];
}

- (void)moveCSFilesWithFileModels:(NSArray *)csfileModels
{
    NSMutableArray *csFileIDsArray = [NSMutableArray array];
    
    for (CSFileFrameModel *csfileFrameModel in csfileModels) {
        [csFileIDsArray addObject:csfileFrameModel.fileModel.sid];
    }
    
    CSRouterSelectController *csRouterSelectController = [CSRouterSelectController new];
    
    IWNavigationController *navCloud = [[IWNavigationController alloc]initWithRootViewController:csRouterSelectController];
    __weak typeof(self.view)weakView = self.view;
#pragma mark -- 2017-07-26 01文件迁移 serverFullPath未处理 --sql
    navCloud.cloudControlerBlock = ^(NSString *pid, NSString *serverFullPath){
        [[HttpRequest sharedManager]cloudStorageMoveFilesToOtherPid:pid needMoveFiles:csFileIDsArray complete:^(BOOL success, id data, NSError *error) {
#warning 2017-07-26 02 文件迁移完成后控制器刷新 未实现
            //update new files.
            //[[CloudStorageDB shareInstance]addcsFilestoDB:csFileIDsArray];
            if (!error&&success) {
                [kCloudStorageDB updateCSFilestoDB:csFileIDsArray targetid:pid];
                
                [Utils showSuccess:@"移动成功" toView:weakView finish:nil];
            }
            else{
                [Utils showSuccess:@"移动失败" toView:weakView finish:nil];
            }
            
            
        }];
        
        
        
        
        
    };
    [self.navigationController presentViewController:navCloud animated:YES completion:nil];
    
    
}

- (void)downloadFileWithFileModels:(NSArray *)csfileModels
{
    
    //获取最外层文件夹.
    //再创建数据库模型,不用考虑重复,uuid相同无法添加
    //全部丢给tarncenter,相同的uuid会自动过滤.
    
    //最后.通知tarns.(如果是文件,带上subfiles.)
    
    
    
    //先获取所有文件.0
    NSMutableArray *tempSidsArrray = [NSMutableArray array];
    
    //need downfiles0
    NSMutableArray *totalNeedDownloadFileArray = [NSMutableArray array];
    
    //trans show 0
    NSMutableArray *totalPidZeroDownloadFilesArray = [NSMutableArray array];//缺少返回allsubfiles.
    
    //save db for all files.csdownfile *
    NSMutableArray *totalDBSaveDownloadFilesArray = [NSMutableArray array];
    
    for (CSFileFrameModel *csFileFrameModel in csfileModels) {
        
        
        if (csFileFrameModel.fileModel.isdir) {
            
            [tempSidsArrray addObject:csFileFrameModel.fileModel.sid];
            
        }
        
        //创建downupmodel
        csFileFrameModel.fileModel.pid = @"0";
        CSFileDownUpModel *newCSFileDownUpModel = [CSFileDownUpModel csfileDownupModelWithfileModel:csFileFrameModel.fileModel downUpType:DownUpModelDown downUpStatus:DownUpStatusWait fileSource:FileSourceCSCloud fileType:FileTypeOther localRootPath:csFileFrameModel.fileModel.name file_category:csFileFrameModel.fileModel.path.pathComponents.count downUpTimeStamp:[NSDate date] downUpUUID:nil downUpSize:0];
        
        [totalPidZeroDownloadFilesArray addObject:newCSFileDownUpModel];//need show to transcontroller - done
        
        [totalDBSaveDownloadFilesArray addObject:newCSFileDownUpModel]; //need save file/filefolder model
        
        if (!newCSFileDownUpModel.isdir) {
            
            [totalNeedDownloadFileArray addObject:newCSFileDownUpModel];//need download file
        }
        
    }
    
    
    [self getAllFileFoldersFilesWithPidsArray:tempSidsArrray resultBlock:^(NSArray *fileModels) {
        
        for (CSFileModel *fileModel in fileModels) {
            
            //创建downupmodel
            CSFileDownUpModel *newCSFileDownUpModel = [CSFileDownUpModel csfileDownupModelWithfileModel:fileModel downUpType:DownUpModelDown downUpStatus:DownUpStatusWait fileSource:FileSourceCSCloud fileType:FileTypeOther localRootPath:fileModel.name file_category:fileModel.path.pathComponents.count downUpTimeStamp:[NSDate date] downUpUUID:nil downUpSize:0];
            
            [totalDBSaveDownloadFilesArray addObject:newCSFileDownUpModel];
            
            if (!fileModel.isdir) {
                [totalNeedDownloadFileArray addObject:newCSFileDownUpModel];
            }
            
        }
        
        NSMutableArray *tempUUIDsArray = [NSMutableArray array];
        
        for (CSFileDownUpModel *csFileDownUpModel in totalDBSaveDownloadFilesArray) {
            
            [tempUUIDsArray addObject:[NSString stringWithFormat:@"'%@'",csFileDownUpModel.downUpUUID]];
            
        }
        
        //过滤数据库中成功的文件.
        if (tempUUIDsArray.count) {
            
            [kCloudStorageDB getCSDownUpFilesWithUUIDs:tempUUIDsArray downUpModel:DownUpModelDown resultBlock:^(NSArray *dbCSFileModels) {
                
                //过滤掉成功的.
                NSArray *successFiles = [dbCSFileModels filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"downUpStatus = %d",DownUpStatusSuccess]];
                
                NSMutableArray *tempSuccessFilesSortArray = [NSMutableArray array];
                
                for (CSFileDownUpModel *sortFileDownUpModel in totalDBSaveDownloadFilesArray) {
                    
                    //if total的在返回的成功列表内能找到,则移除
                    if ([successFiles filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"downUpUUID = %@",sortFileDownUpModel.downUpUUID]].count) {
                        
                        [tempSuccessFilesSortArray addObject:sortFileDownUpModel];
                    }
                    
                }
                
                [totalNeedDownloadFileArray removeObjectsInArray:tempSuccessFilesSortArray];
                
                if (totalNeedDownloadFileArray.count) {
                    
                    [kCloudStorageDB addCSDownUpFilesToDB:totalDBSaveDownloadFilesArray downUpModel:DownUpModelDown];
                    
                    CSTabBarController *iwNav = (CSTabBarController *)self.tabBarController;
                    if (iwNav.cloudControlerFileDownloadBlock) {
                        iwNav.cloudControlerFileDownloadBlock(totalPidZeroDownloadFilesArray);
                    }
                    
                    //downUpFiles
                    //待过滤successfiles
                    [[CloudStorageDownloadCenter sharedInstance]addOneDownloadWithFileDownUpModels:totalNeedDownloadFileArray];
                    
                }
                
            }];
        }
        
        
    }];
    
    
    
}


- (void)getAllFileFoldersFilesWithPidsArray:(NSArray *)pidsArray resultBlock:(void(^)(NSArray *fileModels))resultBlock
{
    
    if (pidsArray) {
        [[HttpRequest sharedManager]cloudStorageGetAllChildsWithPids:pidsArray complete:^(BOOL success, id data, NSError *error) {
            
            if (data && success) {
                NSArray *fileModels = [CSFileModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
                
                resultBlock(fileModels);
                
                //resultBlock();
            }else resultBlock(nil);
            
        }];
    }else resultBlock(nil);
    
}


- (void)getFileListWithPid:(NSString *)pid searchKey:(NSString *)key classExt:(NSString *)ext
{
    [self.fileModelArray removeAllObjects];
    
    __weak typeof(self)weakSelf = self;
    __weak typeof(self.mainTableView)weakTableView = self.mainTableView;
    __weak typeof(self.view)weakView = self.view;
    
    [Utils showWaitingToView:self.view];
    
    [[HttpRequest sharedManager]cloudStorageGetFilesWithPid:pid searchKey:key ext:ext complete:^(BOOL success, id data, NSError *error) {
        
        if (success && data) {
            NSArray *fileDataModel = [CSFileModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
            
            for (CSFileModel *fileModel in fileDataModel) {
                if (fileModel.isdir) {
                    
                    fileModel.serverFullPath = self.father_csFileModel?[NSString stringWithFormat:@"%@%@/",self.father_csFileModel.serverFullPath,fileModel.name]:[NSString stringWithFormat:@"%@/",fileModel.name];
                    
                }else fileModel.serverFullPath = self.father_csFileModel?[NSString stringWithFormat:@"%@%@",self.father_csFileModel.serverFullPath,fileModel.name]:[NSString stringWithFormat:@"%@",fileModel.name];;
                
                CSFileFrameModel *csFileFrameModel = [[CSFileFrameModel alloc]initWithFileModel:fileModel];
                [weakSelf.fileModelArray addObject:csFileFrameModel];
                
            }
            
            [Utils HiddenWaitingToView:weakView];
            
            [weakTableView reloadData];
            
            
            
            if (weakSelf.csFileSourceType == CSFileSourceTypeSelf) {
                
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    [kCloudStorageDB addcsFilestoDB:fileDataModel];
                });
                
            }
        }else{
            
            [Utils HiddenWaitingToView:weakView];
            
            [kCloudStorageDB getAllCloudFilesWithPid:pid resultBlock:^(NSArray *result) {
                
                for (CSFileModel *fileModel in result) {
                    CSFileFrameModel *csFileFrameModel = [[CSFileFrameModel alloc]initWithFileModel:fileModel];
                    [weakSelf.fileModelArray addObject:csFileFrameModel];
                }
                [weakTableView reloadData];
            }];
        }
        
    }];
}
- (void)dealloc
{
    NSLog(@"firstpage delloc");
}

@end
