//
//  downLoadPreviewViewController.m
//  隐私保护
//
//  Created by xd h on 2024/1/7.
//

#import "downLoadPreviewViewController.h"
#import "couldPhoneFileListModel.h"
#import "downLoadPreViewCell.h"
#import "downloadFileBottomView.h"
#import "downloadThumbnailManager.h"
#import "downloadManager.h"
#import "uploadFileRecordViewController.h"
#import "UIScrollView+EmptyDataSet.h"
#import "diskListBgView.h"
#import "diskListTableView.h"

@interface downLoadPreviewViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
{
    UIButton *tapBtn;
}
@property (nonatomic, strong) UITableView *tableView;

@property (strong, nonatomic) UILabel *MytitleLabel;
@property (strong, nonatomic) UIImageView *selectTip;
@property (nonatomic, strong) UIButton *rightButton;
@property (nonatomic, strong) diskListBgView *diskListBgV;
@property (nonatomic, strong) diskListTableView *diskListTableV;
@property (nonatomic, strong)  NSMutableArray*diskListArr;
@property (nonatomic, copy) NSString *defaultDiskPath;


@property (nonatomic, strong) downloadFileBottomView *downloadFileBottomV;

@property(nonatomic,strong) couldPhoneFileListModel *curCouldPhoneFileListMod;
@end

@implementation downLoadPreviewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.toolBar setHidden:YES];
    [self.navigationBar setHidden:YES];
    [self.navBarBGView setHidden:NO];
    self.navBarBGView.backgroundColor = [UIColor whiteColor];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchFileListDoneFun:) name:searchFileListDoneNotification object:nil];
    
    [self drawAnyView];
}

- (void)drawAnyView{
    
    [self initNavHeadUIFun];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-(60 + safeArea));
        make.top.equalTo(self.navBarBGView.mas_bottom).offset(10.f);
    }];
    
    _downloadFileBottomV = [[downloadFileBottomView alloc] init];
    [self.view insertSubview:_downloadFileBottomV atIndex:0];
    
    [_downloadFileBottomV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.height.mas_equalTo(60 + safeArea);
    }];
    
    [self RefreshBottomViewUIFun];
    
    KWeakSelf
    _downloadFileBottomV.didClickDownloadFile = ^{
        [weakSelf gotoDownloadloadFileRecordFun];
    };
    
    
    NSMutableArray *arr = [NSMutableArray new];
    NSArray *diskList = ksharedAppDelegate.cloudPhoneExtraFileListMod.data;
    if(diskList && [diskList isKindOfClass:[NSArray class]]){
        for (cloudPhoneExtraFileModel *model in diskList) {
            model.isCheckType = NO;
            [arr addObject:model];
        }
    }
    
    if(arr.count >0){
        cloudPhoneExtraFileModel *model = arr.firstObject;
        model.isCheckType = YES;
        _defaultDiskPath = model.extraPath;
    }
    _diskListArr = arr;
    [self setTitleAfterGetdiskFun];
}

- (void)initNavHeadUIFun
{
    //title
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont boldSystemFontOfSize:18.0];
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.navBarBGView addSubview:titleLabel];

    self.MytitleLabel = titleLabel;
    
    //selectTipImageView
    UIImageView *selectTip = [[UIImageView alloc] init];
    selectTip.image = [UIImage imageNamed:@"upload_image_arrow"];
    selectTip.translatesAutoresizingMaskIntoConstraints = NO;
    [self.navBarBGView addSubview:selectTip];
    self.selectTip = selectTip;
    
    tapBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    tapBtn.backgroundColor = [UIColor clearColor];
    tapBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [tapBtn addTarget:self action:@selector(selectDiskAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.navBarBGView addSubview:tapBtn];
    
    [tapBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.navBarBGView.mas_centerX);
        make.centerY.mas_equalTo(self.backBtn.mas_centerY);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(30);
    }];
    
    [self setTitleLabelText:@""];
    
    _rightButton = [[UIButton alloc] init];
    [_rightButton setTitle:NSLocalizedString(@"File_upload_Record_select_all",nil) forState:UIControlStateNormal];
    [_rightButton setTitle:NSLocalizedString(@"File_upload_cancel_select_all",nil) forState:UIControlStateSelected];
    
    [_rightButton setTitleColor:[UIColor hwColor:@"#01B7EA" alpha:1.0] forState:UIControlStateNormal];
    _rightButton.titleLabel.font = [UIFont systemFontOfSize:18.0];
    _rightButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [_rightButton addTarget:self action:@selector(didClickSelectAllButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.navBarBGView addSubview:_rightButton];
    
    
    [_rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(90);
        make.height.mas_equalTo(40);
        make.right.mas_equalTo(-15);
        make.centerY.mas_equalTo(self.titleLabel.mas_centerY);
    }];
    
    //_rightButton.backgroundColor = [UIColor redColor];
}


#pragma mark - 懒加载
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H - TABBARHEIGHT) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
//        _tableView.contentInset = UIEdgeInsetsMake(-H_STATE_BAR, 0, 0, 0);
        [_tableView setSeparatorStyle:(UITableViewCellSeparatorStyleNone)];
        [_tableView setSeparatorColor:[UIColor clearColor]];
        [_tableView setBackgroundColor:[UIColor clearColor]];
        [_tableView setTableFooterView:[UIView new]];
        [_tableView setBounces:YES];
        
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
        
        //空数据引入第三方开源处理
        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;
    }
    
    return _tableView;
}

- (diskListBgView*)diskListBgV
{
    if(!_diskListBgV){
        _diskListBgV = [[diskListBgView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        _diskListBgV.hidden = YES;
        [self.view addSubview:_diskListBgV];
        
        KWeakSelf
        _diskListBgV.didTapWhitePlace = ^{
            [weakSelf hideDiskListVieFun];
        };
        
        [_diskListBgV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(0);
            make.bottom.mas_equalTo(0);
            make.right.mas_equalTo(0);
            make.top.mas_equalTo(self.navBarBGView.mas_bottom);
        }];
        
        [self.view addSubview:self.diskListTableV];
        self.diskListTableV.hidden = YES;
        [self.diskListTableV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(0);
            make.height.mas_equalTo(3*70);
            make.right.mas_equalTo(0);
            make.top.mas_equalTo(self.navBarBGView.mas_bottom);
        }];
       
        self.diskListTableV.diskListArr = _diskListArr;
        
        self.diskListTableV.didClickDiskModel = ^(NSString * _Nonnull checkPath) {
            [weakSelf didCheckDiskFunByPath:checkPath];
        };
    }
    
    return  _diskListBgV;
}

- (UITableView *)diskListTableV{
    if (!_diskListTableV) {
        _diskListTableV = [[diskListTableView alloc] init];
//
    }
    return _diskListTableV;
}

#pragma mark 选中磁盘
- (void)didCheckDiskFunByPath:(NSString*)pathStr
{
    self.defaultDiskPath = pathStr;
    //[self searchFileListFun];
    [self setTitleAfterGetdiskFun];
    [self hideDiskListVieFun];
}

#pragma mark - 列表委托
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(!_curCouldPhoneFileListMod){
        return 0;
    }
    return _curCouldPhoneFileListMod.data.list.count;
}

- (downLoadPreViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    __block NSInteger row = indexPath.row;
    static NSString *identifier = @"downLoadPreViewCell";
    
    downLoadPreViewCell * cell =  [tableView dequeueReusableCellWithIdentifier:identifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (!cell){
        cell = [[downLoadPreViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        [cell setBackgroundColor:[UIColor clearColor]];
        [cell setAccessoryType:(UITableViewCellAccessoryNone)];
        
        [cell.bgViewLayer removeFromSuperlayer];
        [cell.titleLabel2 setHidden:NO];
        [cell.rightImage setHidden:YES];
        [cell.lineView setHidden:YES];
        [cell.checkButton setHidden:NO];
        
    }
    
    if(row < _curCouldPhoneFileListMod.data.list.count){
        couldPhoneFileModel* fileModel = _curCouldPhoneFileListMod.data.list[row];
        cell.curFileModel = fileModel;
    }
    
    
    KWeakSelf
    cell.didClickSwitch = ^(BOOL SwitchOn) {
        [weakSelf userCheckFilePreviewByRow:row];
    };
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

#pragma mark 空数据
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    
    NSString *imageName = @"uploadFile_noData";
    
    return [UIImage imageNamed:imageName];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = NSLocalizedString(@"File_download_file_no_data",nil);
    
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:16.0f],
                                 NSForegroundColorAttributeName: HW999999Color};
    
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}

//调整图片位置
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return -150;
}

- (void)userCheckFilePreviewByRow:(NSInteger)row
{
    if(row < _curCouldPhoneFileListMod.data.list.count){
        couldPhoneFileModel* fileModel = _curCouldPhoneFileListMod.data.list[row];
         fileModel.isSelectType = !fileModel.isSelectType;
        [self.tableView reloadData];
        [self RefreshBottomViewUIFun];
    }
}

- (void)didClickSelectAllButton:(UIButton*)button
{
    button.selected = !button.selected;
    
    for (couldPhoneFileModel* fileModel in _curCouldPhoneFileListMod.data.list) {
        fileModel.isSelectType = button.selected;
    }
    
    [self.tableView reloadData];
    [self RefreshBottomViewUIFun];
}

#pragma mark 设置标题
- (void)setTitleLabelText:(NSString*)title
{
    NSArray *diskNameArr = [_defaultDiskPath componentsSeparatedByString:@"/"];
    if(diskNameArr && diskNameArr.count >= 2){
        
        NSString *name = diskNameArr.lastObject;
        if(name.length == 0)
        {
            name = diskNameArr[diskNameArr.count -2];
        }
        
        title = [[NSString alloc] initWithFormat:@"[%@]%@",name,title];
    }
    
    
    
    self.MytitleLabel.text = title;
    
    CGFloat curWidth = [title boundingRectWithSize:CGSizeMake(SCREEN_W, 30) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:18.f]} context:nil].size.width;
    
    curWidth += 20;
    //HLog(@"title w:%f",curWidth);
    [self.MytitleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.navBarBGView.mas_centerX).offset(-10);
        make.centerY.mas_equalTo(self.backBtn.mas_centerY);
        make.width.mas_equalTo(curWidth);
        make.height.mas_equalTo(30);
    }];
    //self.MytitleLabel.backgroundColor = [UIColor greenColor];
    
    [self.selectTip mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.MytitleLabel.mas_right).offset(0);
        make.centerY.mas_equalTo(self.backBtn.mas_centerY);
        make.width.mas_equalTo(15);
        make.height.mas_equalTo(15);
    }];
    
    [tapBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.navBarBGView.mas_centerX);
        make.centerY.mas_equalTo(self.backBtn.mas_centerY);
        make.width.mas_equalTo(curWidth+15);
        make.height.mas_equalTo(30);
    }];
}

#pragma mark 选择硬盘
- (void)selectDiskAction:(UIButton*)but
{
    if(self.diskListBgV.hidden){
        [self showDiskListVieFun];
    }
    else{
        [self hideDiskListVieFun];
        
    }
}

- (void)showDiskListVieFun
{
    self.diskListBgV.hidden = NO;
    self.diskListTableV.hidden = NO;
    
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = self.diskListTableV.frame;
        rect.origin.y = CGRectGetMaxY(self.navBarBGView.frame);
        self.diskListTableV.frame = rect;

        self.selectTip.transform = CGAffineTransformMakeRotation(M_PI);
    }];
}

- (void)hideDiskListVieFun
{
    self.diskListBgV.hidden = YES;
    
    [UIView animateWithDuration:0.3 animations:^{
        self.diskListTableV.hidden = YES;
        self.selectTip.transform = CGAffineTransformIdentity;
        
    }completion:^(BOOL finished) {
        CGRect rect = self.diskListTableV.frame;
        rect.origin.y = 0;
        self.diskListTableV.frame = rect;
    }];
}


#pragma mark 刷新底部
- (void)RefreshBottomViewUIFun
{
    NSMutableArray *selectArr = [NSMutableArray new];
    
    for (couldPhoneFileModel* fileModel in _curCouldPhoneFileListMod.data.list) {
        
        if(fileModel.isSelectType){
            [selectArr addObject:fileModel];
        }
    }
    
    _downloadFileBottomV.indexPathsForSelectedItems = selectArr;
}


#pragma mark 设置标题
- (void)setTitleAfterGetdiskFun
{
    if(_isPhotoType){
        //self.titleLabel.text = NSLocalizedString(@"my_set_no_image_upload",nil) ;
        [self setTitleLabelText:NSLocalizedString(@"my_set_no_image_upload",nil)];
    }
    else{
        //self.titleLabel.text = NSLocalizedString(@"my_set_no_video_upload",nil) ;
        [self setTitleLabelText:NSLocalizedString(@"my_set_no_video_upload",nil)];
    }
    
    [self searchFileListFun];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    
}

- (void)searchFileListFun
{
    NSMutableDictionary *dict = [NSMutableDictionary new];
    NSNumber *curNum = [NSNumber numberWithBool:_isPhotoType];
    [dict setObject:curNum forKey:@"type"];
    if(!_defaultDiskPath){
        _defaultDiskPath = @"";
    }
    [dict setObject:_defaultDiskPath forKey:@"path"];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:searchFileListBeginNotification object:dict];/*发送通知*/
}

- (void)searchFileListDoneFun:(NSNotification*)notification
{
    NSDictionary *dataDict = [notification object];
    
    if(!dataDict || ![dataDict isKindOfClass:[NSDictionary class]]){
        return;
    }
    
    _curCouldPhoneFileListMod = [[couldPhoneFileListModel alloc] initWithDictionary:dataDict error:nil];
    
    NSMutableArray *filterArr = [NSMutableArray new];
    for (couldPhoneFileModel*model in _curCouldPhoneFileListMod.data.list) {
        //if(model.length > 1024)
        if(model.length > 1024*50)
        {
            [filterArr addObject:model];
        }
    }
    
    _curCouldPhoneFileListMod.data.list = filterArr;
    
    [self.tableView reloadData];
    
    //这个要做判断 不能为空
    //[self gotoDownThumbnailManagerFun];
}


#pragma mark 去下载缩略图
- (void)gotoDownThumbnailManagerFun
{
    [[downloadThumbnailManager shareInstance] handlToDownloadThumbnailWith:_curCouldPhoneFileListMod.data.list];
}

- (void)gotoDownloadloadFileRecordFun
{
    uploadFileRecordViewController *vc = [uploadFileRecordViewController new];
    [self.navigationController pushViewController:vc animated:YES];
    vc.isDownloadingType = YES;
    [vc gotoDownloadFile:_downloadFileBottomV.indexPathsForSelectedItems];
}

@end
