//
//  uploadFileRecordTableView.m
//  隐私保护
//
//  Created by xd h on 2023/11/22.
//

#import "uploadFileRecordTableView.h"
#import "uploadFileRecordCell.h"
#import "UIScrollView+EmptyDataSet.h"
#import "uploadFileManager.h"
#import "uploadFileRecordTableViewHeadView.h"

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


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

@implementation uploadFileRecordTableView

- (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;
    
    _uploadingArr = outSideDataArr[0];
    _uploadDoneArr = outSideDataArr[1];
    _uploadfailArr = outSideDataArr[2];
    
    [self RefreshAllDataFun];
}

- (void)RefreshAllDataFun
{
    NSMutableArray *totalArr = [NSMutableArray new];
    
    if(_uploadingArr.count>0){
        [totalArr addObject:_uploadingArr];
    }
    
    if(_uploadfailArr.count>0){
        [totalArr addObject:_uploadfailArr];
    }
    
    if(_uploadDoneArr.count>0){
        [totalArr addObject:_uploadDoneArr];
    }
    
    _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 = @"uploadFileRecordCell";
    
    uploadFileRecordCell * cell =  [tableView dequeueReusableCellWithIdentifier:identifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (!cell){
        cell = [[uploadFileRecordCell 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){
            uploadFileDataModel *model = curArr[row];
            cell.curUploadFileDataModel = 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.curUploadStateType == uploadStateUploading){
                    [weakSelf handleUploadingStateTapFunBy:YES with:model];
                }
                else if(model.curUploadStateType == uploadStateSuspend){
                    [weakSelf handleUploadingStateTapFunBy:NO with:model];
                }
                else if(model.curUploadStateType == uploadStateFail){
                    [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(_uploadingArr.count == 0){
            curType = 2;
        }
        else if(_uploadfailArr.count == 0){
            curType = 2;
        }
        else{
            curType = 1;
        }
    }
    else{
        if(_uploadingArr.count > 0){
            curType = 0;
        }
        else if(_uploadfailArr.count > 0){
            curType = 1;
        }
        else{
            curType = 2;
        }
    }
    
    
    [self RefresHeadUIFun];
    
    if(curType == 2){
        return _doneHeadView;
    }
    else if(curType == 1){
        return _failHeadView;
    }
    else{
        return _uploadingHeadView;
    }
    
}

- (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(!_uploadingHeadView){
        _uploadingHeadView = [[uploadFileRecordTableViewHeadView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 40)];
        //headView.backgroundColor = [UIColor greenColor];
        
        NSString *leftStr =  NSLocalizedString(@"File_upload_Record_uploading",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,_uploadingArr.count];

        _uploadingHeadView.titleLabel.text = titleStr;
        [_uploadingHeadView.rightButton setTitle:rightStr forState:UIControlStateNormal];
        [_uploadingHeadView.rightButton setTitle:rightSelectStr forState:UIControlStateSelected];
        
        _uploadingHeadView.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_upload_fail",nil);
        NSString *rightStr =  NSLocalizedString(@"File_upload_Record_clear_Record",nil);
        NSString *titleStr = [[NSString alloc] initWithFormat:@"%@ (%ld)",leftStr,_uploadfailArr.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_upload",nil);
        NSString *rightStr =  NSLocalizedString(@"File_upload_Record_clear_Record",nil);
        NSString *titleStr = [[NSString alloc] initWithFormat:@"%@ (%ld)",leftStr,_uploadDoneArr.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(_uploadingHeadView){
        NSString *leftStr =  NSLocalizedString(@"File_upload_Record_uploading",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,_uploadingArr.count];

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

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

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

#pragma mark  点击全选
- (void)setIsSelectAllType:(BOOL)isSelectAllType
{
    //_selectModelArr = [NSMutableArray arrayWithArray:_curDataArr];
    
    _selectModelArr = [NSMutableArray new];
    
    [_selectModelArr addObjectsFromArray:_uploadingArr];
    [_selectModelArr addObjectsFromArray:_uploadfailArr];
    [_selectModelArr addObjectsFromArray:_uploadDoneArr];
    
    [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:(uploadFileDataModel*)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;
    }
    
    KWeakSelf
    [[uploadFileManager shareInstance] deleteUploadFileRecordBy:_selectModelArr withDelCache:YES complete:^(BOOL isSuccess) {
        HLog(@"isSuccess:%d",isSuccess);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        if(isSuccess){
//            NSMutableArray *curArr = self->_curDataArr;
//            [curArr removeObjectsInArray:self->_selectModelArr];
//            [weakSelf reloadDataFun];
            self->_selectModelArr = [NSMutableArray new];
            
            //重新拿数据
            [weakSelf refreshGetDatabaseFun];
        }
    }];
}

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

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

#pragma mark 处理上传中的 状态点击事件
- (void)handleUploadFailStateWith:(uploadFileDataModel*)model{
    
    if(_uploadfailArr && _uploadfailArr.count > 0){
        [_uploadfailArr removeObject:model];
    }
   
    [self RefreshAllDataFun];
    
    if(_didClickReUploadBlock){
        _didClickReUploadBlock(model);
    }
    
    NSMutableArray*arr = [NSMutableArray new];
    model.curUploadStateType = uploadStateUploading;
    [arr addObject:model];
    [[uploadFileManager shareInstance] reUploadFileFunBy:arr withAll:NO];
    
}
@end
