//
//  CSRouterSelectController.m
//  zhuxun
//
//  Created by winsoft on 17/6/28.
//
//

#import "CSRouterSelectController.h"
#import "IWNavigationController.h"
#import "IWNavigationController.h"


#import "CloudStorageTableView.h"

#import "CSFileCell.h"

#import "CloudRouterShowView.h"

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

#import "UIBarButtonItem+Addition.h"

#import "UIActionSheet+Blocks.h"

#import "UIAlertView+Blocks.h"
#import "CSAlertView.h"
#import "CloudStorageDB.h"
#import "Utils.h"

#define CloudRouterShowViewHeight  50
@interface CSRouterSelectController()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic , weak) CloudStorageTableView *mainTableView;

@property (nonatomic , weak) CloudRouterShowView *cloudRouterShowView;

@property (nonatomic , strong) NSMutableArray *folderModelArray;

/**
 *  父节点
 */
@property (nonatomic , strong) CSFileModel *father_csFileModel;
@end
@implementation CSRouterSelectController
- (NSMutableArray *)folderModelArray
{
    if (!_folderModelArray) {
        _folderModelArray = [NSMutableArray array];
    }
    
    return _folderModelArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if([self respondsToSelector:@selector(setEdgesForExtendedLayout:)])
    {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(cancerSelect) icon:nil highlightedIcon:nil title:@"取消" iconSize:CGSizeZero fontSize:14 titleColor:[UIColor whiteColor]];
    
    
    
    if (!self.pid) {
        self.pid = @"0";
        self.title = @"我的网盘";
        
    }else self.title = self.father_csFileModel.name;
    
    [self initSubViews];
    
    __weak typeof(self)weakSelf = self;
    
    __weak typeof(self.mainTableView)weakTableView = self.mainTableView;
    

    [self getTopFolderLists];
    
    if (self.fileMD5 && self.fileName) {
        
        [self judgeSameFileIsExitThisFolder];
    }
    
    
}

- (void)cancerSelect
{
     [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)initSubViews
{
    
    CloudStorageTableView *mainTableView = [[CloudStorageTableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NavBarHeight - STATUSBAR_HEIGHT - CloudRouterShowViewHeight) 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;
    
    __weak typeof(self)weakSelf = self;
    
    CloudRouterShowView *cloudRouterShowView = [CloudRouterShowView cloudRouterShowViewWithItems:@[@"新建文件夹",@"选定"] bkColors:@[RGB(125,125,125),RGB(36, 143, 233)]];
    cloudRouterShowView.backgroundColor = [UIColor blackColor];

    cloudRouterShowView.frame = CGRectMake(0,CGRectGetMaxY(mainTableView.frame), self.view.frame.size.width, CloudRouterShowViewHeight);
    
    cloudRouterShowView.actionBlock = ^(NSInteger index)
    {
        if (index == 0) {
            [weakSelf createNewFileFolder];
        }else{
        
            [weakSelf saveFileToCloudFolde];
        }
    };
    
    [self.view addSubview:cloudRouterShowView];
    self.cloudRouterShowView = cloudRouterShowView;


}

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

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CSFileCell *csFileCell = [CSFileCell fileCellWithTableView:tableView indexPath:indexPath identifier:CSFileCellIdentifier opItems:nil];
    
    csFileCell.indexPath = indexPath;
    
    csFileCell.csFileFrameModel = self.folderModelArray[indexPath.row];
    

    return csFileCell;
}


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

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return self.father_csFileModel?[NSString stringWithFormat:@"选择目标文件夹 (已选:%@)",self.father_csFileModel.name]:[NSString stringWithFormat:@"选择目标文件夹 (已选:我的网盘)"];
}


#pragma mark --
#pragma mark -- tableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    CSFileFrameModel *csFileFrameModel = self.folderModelArray[indexPath.row];
   
        
        //
    CSFileModel *csFileModel = csFileFrameModel.fileModel;
    
    if (csFileModel.isdir) {
        //文件夹
        CSRouterSelectController *csPage =  [CSRouterSelectController new];
        csPage.fileMD5 = self.fileMD5;
        csPage.fileName  = self.fileName;
        csPage.pid = csFileModel.sid;
        csPage.father_csFileModel = csFileModel;
        [self.navigationController pushViewController:csPage animated:YES];
        
        
    }
    
    
}

#pragma mark --
#pragma mark -- rques
- (void)getTopFolderLists
{
    [self getgetTopFolderListsWithPid:self.pid];
}

- (void)judgeSameFileIsExitThisFolder
{
    __weak typeof(self.cloudRouterShowView)weakRouterShowView = self.cloudRouterShowView;
    //只要同名就不可以存放
    
    [[HttpRequest sharedManager]cloudStorageCheckFileNameIsExitWithPid:self.pid fileName:self.fileName isdir:NO ext:[self.fileName  componentsSeparatedByString:@"."].lastObject complete:^(BOOL success, id data, NSError *error) {
        
        /*
         {
         data = 0;
         message = "";
         success = 1;
         }
         */
        
        if (data && success) {
            
            if ([data[@"data"] boolValue]) {
                [weakRouterShowView setIndexActionBtnEnableWithIndex:1 enable:NO];
            }
            
        }else  [weakRouterShowView setIndexActionBtnEnableWithIndex:1 enable:NO];
        NSLog(@"%@",data);
        //不可选择
        //
        
        //请求失败也是不可选.
        
    }];
    
}

- (void)getgetTopFolderListsWithPid:(NSString *)pid
{
    [self.folderModelArray removeAllObjects];
    
    __weak typeof(self)weakSelf = self;
    __weak typeof(self.mainTableView)weakTableView = self.mainTableView;
    
    [[HttpRequest sharedManager]cloudStorageGetAllFolderWithPid:pid excludeIds:nil 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.folderModelArray addObject:csFileFrameModel];
                
            }
            
            [weakTableView reloadData];
        }

        
    }];
   
}

- (void)createNewFileFolder
{

    CSAlertView * alertView  = [[CSAlertView alloc]initWithTitle:@"新建文件夹" message:@"" inputMode:YES sureBtn:@"创建" cancleBtn:@"取消"];
    [alertView showXBAlertView];
    __weak typeof(self)weakSelf = self;
    __weak typeof(self.mainTableView)weakTableView = self.mainTableView;
    __weak typeof(alertView)weakalertView = alertView;
    
    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];
                
                //                [CloudStorageDB addcsFiletoDB:csfileModel];
                
                CSFileFrameModel *csframeModel = [[CSFileFrameModel alloc]initWithFileModel:csfileModel];
                
                [weakSelf.folderModelArray addObject:csframeModel];
                
                [weakTableView reloadData];
                //                [weakTableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:[weakTableView numberOfRowsInSection:0] - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
                //
                [weakTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:weakSelf.folderModelArray.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
            }else{
                [weakalertView showErrorMsg:@"文件夹创建失败"];
                //[Utils showError:@"文件夹创建失败" ToView:weakTableView];
            }

        }];
    };
    /*
    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.length?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.folderModelArray addObject:csframeModel];
                
                [weakTableView reloadData];
                //                [weakTableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:[weakTableView numberOfRowsInSection:0] - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
                //
                [weakTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:weakSelf.folderModelArray.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
            }else{
                
                [Utils showError:@"文件夹创建失败" ToView:weakTableView];
            }
            
            
        }];
        
    } onCancel:^(UIAlertView *alertView) {
        
    }];
    */
}

#warning 通过self的navcontroller 将数据将模型传出.
- (void)saveFileToCloudFolde
{
    IWNavigationController *iwNav = (IWNavigationController *)self.navigationController;
    
    if (iwNav.cloudControlerBlock) {
        iwNav.cloudControlerBlock(self.father_csFileModel.sid?self.father_csFileModel.sid:@"0",self.father_csFileModel.serverFullPath);
    }
    
    [self cancerSelect];;

}




@end
