//
//  downloadFileRecordTableView.m
//  隐私保护
//
//  Created by xd h on 2024/1/10.
//

#import "downloadFileRecordTableView.h"
#import "downloadFileRecordCell.h"
#import "UIScrollView+EmptyDataSet.h"
#import "uploadFileRecordTableViewHeadView.h"

@interface downloadFileRecordTableView()<UITableViewDataSource,UITableViewDelegate,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
{
   
}


@property (nonatomic, strong) NSMutableArray *curDataArr;
@end

@implementation downloadFileRecordTableView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self initCommon];
        [self initTableHeaderInSectionFun];
        _selectModelArr = [NSMutableArray new];
        _curDataArr = [NSMutableArray new];
    }
    return self;
}

- (void)initCommon {
    self.delegate = self;
    self.dataSource = self;
    self.showsVerticalScrollIndicator = NO;
    self.showsHorizontalScrollIndicator = NO;
    [self setSeparatorStyle:(UITableViewCellSeparatorStyleNone)];
    [self setSeparatorColor:[UIColor clearColor]];
    [self setBackgroundColor:[UIColor clearColor]];
    [self setTableFooterView:[UIView new]];
    [self setBounces:YES];
    if (@available(iOS 15.0, *)) {
        self.sectionHeaderTopPadding = 0;
    }
    
    //空数据引入第三方开源处理
    self.emptyDataSetSource = self;
    self.emptyDataSetDelegate = self;
}

- (void)setOutSideDataArr:(NSMutableArray *)outSideDataArr{
    
    if(!outSideDataArr || outSideDataArr.count != 3){
        return;
    }
    
    _outSideDataArr = outSideDataArr;
    
    _downloadingArr = outSideDataArr[0];
    _downloadDoneArr = outSideDataArr[1];
    _downloadfailArr = outSideDataArr[2];
    
    [self RefreshAllDataFun];
}

- (void)RefreshAllDataFun
{
    NSMutableArray *totalArr = [NSMutableArray new];
    
    if(_downloadingArr.count>0){
        [totalArr addObject:_downloadingArr];
    }
    
    if(_downloadfailArr.count>0){
        [totalArr addObject:_downloadfailArr];
    }
    
    if(_downloadDoneArr.count>0){
        [totalArr addObject:_downloadDoneArr];
    }
    
    _curDataArr = totalArr;
    
    [self reloadDataFun];
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if(section < _curDataArr.count){
        NSArray *curArr = _curDataArr[section];
        return curArr.count;
    }
    
    return 0;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSInteger row = indexPath.row;
    NSInteger section = indexPath.section;
    static NSString *identifier = @"downloadFileRecordCell";
    
    downloadFileRecordCell * cell =  [tableView dequeueReusableCellWithIdentifier:identifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (!cell){
        cell = [[downloadFileRecordCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        [cell setBackgroundColor:[UIColor clearColor]];
        [cell setAccessoryType:(UITableViewCellAccessoryNone)];
    }
    
    if(section < _curDataArr.count){
        NSMutableArray *curArr = _curDataArr[section];
        
        if(row < curArr.count){
            couldPhoneFileModel *model = curArr[row];
            cell.curCouldPhoneFileModel = model;
            cell.isEditType = _isEditType;

            if(_isEditType){
                if([_selectModelArr containsObject:model]){
                    cell.isSelectType = YES;
                }
                else{
                    cell.isSelectType = NO;
                }
            }
            
            KWeakSelf
            cell.didLongPressClick = ^{
                [weakSelf didLongPressClickFun];
            };

            cell.didClckSelectBut = ^(BOOL isSelect) {
                [weakSelf selectModelOneByOne:model BySelect:isSelect];
            };

            cell.didTapPressClick = ^{
                if(model.curDownloadStateType == downloadStateUploading){
                    [weakSelf handleDownloadingStateTapFunBy:YES with:model];
                }
                else if(model.curDownloadStateType == downloadStateSuspend){
                    [weakSelf handleDownloadingStateTapFunBy:NO with:model];
                }
                else if(model.curDownloadStateType == downloadStateFail){
                    [weakSelf handleUploadFailStateWith:model];
                }
            };
        }
    }
    
    return cell;
}

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

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSInteger curType = 0;// 0 上传中  1 失败 2 完成
    if(section == 2){
        curType = 2;
    }
    else if(section == 1){
        if(_downloadingArr.count == 0){
            curType = 2;
        }
        else if(_downloadfailArr.count == 0){
            curType = 2;
        }
        else{
            curType = 1;
        }
    }
    else{
        if(_downloadingArr.count > 0){
            curType = 0;
        }
        else if(_downloadfailArr.count > 0){
            curType = 1;
        }
        else{
            curType = 2;
        }
    }
    
    
    [self RefresHeadUIFun];
    
    if(curType == 2){
        return _doneHeadView;
    }
    else if(curType == 1){
        return _failHeadView;
    }
    else{
        return _downloadingHeadView;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

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

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = NSLocalizedString(@"File_upload_Record_no_data",nil);
    
    if(self.tag == 101){
        text = NSLocalizedString(@"File_download_Record_no_data",nil);
    }
    else if(self.tag == 102){
        text = NSLocalizedString(@"File_backups_Record_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)reloadDataFun{
    mainBlock(^{
        [self RefresHeadUIFun];
        [self reloadData];
    });
}

#pragma mark 初始化段头
- (void)initTableHeaderInSectionFun
{
    KWeakSelf
    if(!_downloadingHeadView){
        _downloadingHeadView = [[uploadFileRecordTableViewHeadView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 40)];
        //headView.backgroundColor = [UIColor greenColor];
        
        NSString *leftStr =  NSLocalizedString(@"File_upload_Record_downloading",nil);
        NSString *rightStr =  NSLocalizedString(@"File_upload_Record_all_suspend",nil);
        NSString *rightSelectStr =  NSLocalizedString(@"File_upload_Record_all_open",nil);
        NSString *titleStr = [[NSString alloc] initWithFormat:@"%@ (%ld)",leftStr,_downloadingArr.count];

        _downloadingHeadView.titleLabel.text = titleStr;
        [_downloadingHeadView.rightButton setTitle:rightStr forState:UIControlStateNormal];
        [_downloadingHeadView.rightButton setTitle:rightSelectStr forState:UIControlStateSelected];
        
        _downloadingHeadView.didClickButFun = ^{
            [weakSelf didClickRightButtonFun:0];
        };
    }
    

    if(!_failHeadView){
        _failHeadView = [[uploadFileRecordTableViewHeadView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 40)];
        //headView.backgroundColor = [UIColor greenColor];
        
        NSString *leftStr =  NSLocalizedString(@"File_upload_Record_download_fail",nil);
        NSString *rightStr =  NSLocalizedString(@"File_upload_Record_clear_Record",nil);
        NSString *titleStr = [[NSString alloc] initWithFormat:@"%@ (%ld)",leftStr,_downloadfailArr.count];

         _failHeadView.titleLabel.text = titleStr;
        [_failHeadView.rightButton setTitle:rightStr forState:UIControlStateNormal];
         
        _failHeadView.didClickButFun = ^{
            [weakSelf didClickRightButtonFun:2];
        };
    }
    
    if(!_doneHeadView){
        _doneHeadView = [[uploadFileRecordTableViewHeadView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 40)];
        //headView.backgroundColor = [UIColor greenColor];
        
        NSString *leftStr =  NSLocalizedString(@"File_upload_Record_did_download",nil);
        NSString *rightStr =  NSLocalizedString(@"File_upload_Record_clear_Record",nil);
        NSString *titleStr = [[NSString alloc] initWithFormat:@"%@ (%ld)",leftStr,_downloadDoneArr.count];

        _doneHeadView.titleLabel.text = titleStr;
        [_doneHeadView.rightButton setTitle:rightStr forState:UIControlStateNormal];
        
        _doneHeadView.didClickButFun = ^{
            [weakSelf didClickRightButtonFun:1];
        };
    }
     
    
}

#pragma mark 点击头部右边按钮
- (void)didClickRightButtonFun:(NSInteger)section
{
    if(_didClickSectionHeadViewRightButton){
        _didClickSectionHeadViewRightButton(section);
    }
}

#pragma mark 刷新头部数据
-(void)RefresHeadUIFun
{

    if(_downloadingHeadView){
        NSString *leftStr =  NSLocalizedString(@"File_upload_Record_downloading",nil);
        NSString *rightStr =  NSLocalizedString(@"File_upload_Record_all_suspend",nil);
        NSString *rightSelectStr =  NSLocalizedString(@"File_upload_Record_all_open",nil);
        NSString *titleStr = [[NSString alloc] initWithFormat:@"%@ (%ld)",leftStr,_downloadingArr.count];

        _downloadingHeadView.titleLabel.text = titleStr;
        [_downloadingHeadView.rightButton setTitle:rightStr forState:UIControlStateNormal];
        [_downloadingHeadView.rightButton setTitle:rightSelectStr forState:UIControlStateSelected];
        
        if(_downloadingArr.count == 0){
            _downloadingHeadView.hidden = YES;
        }
        else{
            _downloadingHeadView.hidden = NO;
        }
    }
    
        
     if(_failHeadView){
        NSString *leftStr =  NSLocalizedString(@"File_upload_Record_download_fail",nil);
        NSString *rightStr =  NSLocalizedString(@"File_upload_Record_clear_Record",nil);
        NSString *titleStr = [[NSString alloc] initWithFormat:@"%@ (%ld)",leftStr,_downloadfailArr.count];

         _failHeadView.titleLabel.text = titleStr;
        [_failHeadView.rightButton setTitle:rightStr forState:UIControlStateNormal];
         
         if(_downloadfailArr.count == 0){
             _failHeadView.hidden = YES;
         }
         else{
             _failHeadView.hidden = NO;
         }
    }
    
    if(_doneHeadView){
        NSString *leftStr =  NSLocalizedString(@"File_upload_Record_did_download",nil);
        NSString *rightStr =  NSLocalizedString(@"File_upload_Record_clear_Record",nil);
        NSString *titleStr = [[NSString alloc] initWithFormat:@"%@ (%ld)",leftStr,_downloadDoneArr.count];

        _doneHeadView.titleLabel.text = titleStr;
        [_doneHeadView.rightButton setTitle:rightStr forState:UIControlStateNormal];
        
        if(_downloadDoneArr.count == 0){
            _doneHeadView.hidden = YES;
        }
        else{
            _doneHeadView.hidden = NO;
        }
    }
}

#pragma mark  点击全选
- (void)setIsSelectAllType:(BOOL)isSelectAllType
{
    //_selectModelArr = [NSMutableArray arrayWithArray:_curDataArr];
    
    _selectModelArr = [NSMutableArray new];
    
    [_selectModelArr addObjectsFromArray:_downloadingArr];
    [_selectModelArr addObjectsFromArray:_downloadfailArr];
    [_selectModelArr addObjectsFromArray:_downloadDoneArr];
    
    [self reloadDataFun];
}

-(void)setIsEditType:(BOOL)isEditType
{
    _isEditType = isEditType;
    
    if(_isEditType){
        //_bgScrollV.scrollEnabled = NO;
    }
    else{
        //_bgScrollV.scrollEnabled = YES;
        [_selectModelArr removeAllObjects];
        
    }
    
    [self reloadDataFun];
}

#pragma mark cell长按时间
- (void)didLongPressClickFun{
        self.isEditType = YES;
        if(self->_didLongPressClick){
            self->_didLongPressClick();
        }
}

#pragma mark 单个点击选中 取消
- (void)selectModelOneByOne:(couldPhoneFileModel*)model BySelect:(BOOL)isSelcet
{
    if(isSelcet){
        [_selectModelArr addObject:model];
    }
    else{
        [_selectModelArr removeObject:model];
    }
}

#pragma mark 单个点击选中后删除
- (void)deleteModelOneByOneFun{
    if(!_selectModelArr || _selectModelArr.count==0){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    [[downloadManager shareInstance] deleteDownloadFileRecordBy:_selectModelArr withDelCache:YES];
    
    [_selectModelArr removeAllObjects];
    //重新拿数据
    [self refreshGetDatabaseFun];
}

#pragma mark 删除后重新拿数据
- (void)refreshGetDatabaseFun
{
    if(_didNeedRefreshGetDatabaseFun){
        _didNeedRefreshGetDatabaseFun();
    }
}

#pragma mark 处理上传中的 状态点击事件
- (void)handleDownloadingStateTapFunBy:(BOOL)isSuspendType with:(couldPhoneFileModel*)model
{
    if (isSuspendType) {
        [[downloadManager shareInstance] suspendDownloadFileFun:NO];
    }
    else{
        NSMutableArray*arr = [NSMutableArray new];
        [arr addObject:model];
        [[downloadManager shareInstance] reDownloadFileFunBy:arr withAll:NO];
    }
    
}

#pragma mark 处理上传中的 状态点击事件
- (void)handleUploadFailStateWith:(couldPhoneFileModel*)model{
    
    [_downloadfailArr removeObject:model];
    [_downloadingArr addObject:model];
    
    [self RefreshAllDataFun];

    if(_didClickReUploadBlock){
        _didClickReUploadBlock(model);
    }

    NSMutableArray*arr = [NSMutableArray new];
    model.curDownloadStateType = downloadStateWait;
    [arr addObject:model];
    [[downloadManager shareInstance] reDownloadFileFunBy:arr withAll:NO];
    
}
@end
