//
//  uploadFileRecordBodyView.m
//  隐私保护
//
//  Created by xd h on 2023/11/15.
//

#import "uploadFileRecordBodyView.h"
#import "uploadFileRecordCell.h"
#import "UIScrollView+EmptyDataSet.h"
#import "uploadFileDataModel.h"
#import "ComontAlretViewController.h"
#import "uploadFileManager.h"

@interface uploadFileRecordBodyView ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>


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

@implementation uploadFileRecordBodyView

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    
    _selectIndex = 1;
    [self drawAnyView];
    
    _selectModelArr = [NSMutableArray new];
    return self;
}

- (void)drawAnyView{
    [self setBackgroundColor:[UIColor whiteColor]];
    
    NSInteger maxNum = 3;
    
    _bgScrollV = [[UIScrollView alloc] init];
    _bgScrollV.showsHorizontalScrollIndicator = NO;
    _bgScrollV.pagingEnabled = YES;
    _bgScrollV.delegate = self;
    [self addSubview:_bgScrollV];
    
    [_bgScrollV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    
    KWeakSelf
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        mainBlock(^{
            [weakSelf initBaseTableViewFun:maxNum];
        });
    });
    
}

#pragma mark UITableView
- (void)initBaseTableViewFun:(NSInteger)maxNum
{
    CGRect frame = self->_bgScrollV.frame;
    self->_bgScrollV.contentSize = CGSizeMake(maxNum* SCREEN_W, frame.size.height);
    
    for (NSInteger i= 0; i<maxNum; i++) {
        UITableView *curTableview = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        curTableview.delegate = self;
        curTableview.dataSource = self;
        curTableview.showsVerticalScrollIndicator = NO;
        curTableview.showsHorizontalScrollIndicator = NO;
//        _tableView.contentInset = UIEdgeInsetsMake(-H_STATE_BAR, 0, 0, 0);
        [curTableview setSeparatorStyle:(UITableViewCellSeparatorStyleNone)];
        [curTableview setSeparatorColor:[UIColor clearColor]];
        [curTableview setBackgroundColor:[UIColor clearColor]];
        [curTableview setTableFooterView:[UIView new]];
        [curTableview setBounces:YES];
        if (@available(iOS 15.0, *)) {
            curTableview.sectionHeaderTopPadding = 0;
        }
        [self->_bgScrollV addSubview:curTableview];
        
        curTableview.tag = 10 +i;
        
        //空数据引入第三方开源处理
        curTableview.emptyDataSetSource = self;
        curTableview.emptyDataSetDelegate = self;
        
        [curTableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(SCREEN_W * i);
            make.width.mas_equalTo(SCREEN_W);
            make.top.mas_equalTo(0);
            make.height.mas_equalTo(frame.size.height);
            //make.bottom.mas_equalTo(0);
        }];
        
        
        uploadFileRecordTableViewHeadView *headView =  [[uploadFileRecordTableViewHeadView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 40)];
        curTableview.tableHeaderView = headView;
        
        KWeakSelf
        headView.didClickButFun = ^{
            if(headView == self->_leftHeadView)
            {
                [weakSelf didClickAllSuspendInLoadingFun];
            }
            else if(headView == self->_midHeadView)
            {
                [weakSelf didClickClearRecordInDoneFun];
            }
            else if(headView == self->_rightHeadView)
            {
                [weakSelf didClickClearRecordInFailFun];
            }
        };
        
        if(i==0){
            self->_leftHeadView = headView;
        }
        else if(i==1){
            self->_midHeadView = headView;
        }
        else if(i==2){
            self->_rightHeadView = headView;
        }
    }
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSInteger tag = tableView.tag - 10;
    
    if(_allDataArr && tag <_allDataArr.count){
        NSMutableArray *curArr = _allDataArr[tag];
        
        return curArr.count;
    }
    
    return 0;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSInteger row = indexPath.row;
    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)];
    }
    
    NSInteger tag = tableView.tag - 10;
    
    if(_allDataArr && tag <_allDataArr.count){
        NSMutableArray *curArr = _allDataArr[tag];
        
        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.isEditType = YES;
//                if(self->_didLongPressClick){
//                    self->_didLongPressClick();
//                }
//            };
            
//            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];
//                }
//            };
        }
    }
    

    return cell;
}

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


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if(_bgScrollV != scrollView) return;
    
    CGFloat x = scrollView.contentOffset.x;
    NSInteger index = (x+1)/SCREEN_W;
    
    index += 1;//因为头部是从1开始的
    
     //HLog(@"index:%ld",index);
    if(_didScrollFun){
        _didScrollFun(index);
    }
    
}

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

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = NSLocalizedString(@"File_upload_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)setSelectIndex:(NSInteger)selectIndex
{
    _selectIndex = selectIndex;
    
    CGPoint poit = _bgScrollV.contentOffset;
    poit.x = SCREEN_W * (selectIndex -1);
    
    [UIView animateWithDuration:0.2 animations:^{
        self->_bgScrollV.contentOffset = poit;
    }];
}

- (void)setAllDataArr:(NSMutableArray *)allDataArr
{
    _allDataArr = allDataArr;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if(self->_allDataArr.count >=3){
            [self RefresHeadUIFunBy:self->_allDataArr[0] withMidArr:self->_allDataArr[1] withRightArr:self->_allDataArr[2]];
        }
    });


    mainBlock(^{
        //刷新数据
        [self reloadAllDataFun];
    });
}

#pragma mark 熟悉全部数据
- (void)reloadAllDataFun
{
    if(_allDataArr.count == 3){
        [self RefreshDataWithUploadingArr:_allDataArr[0] withDoneArr:_allDataArr[1] withfailArr:_allDataArr[2]];
    }
}

- (void)RefreshDataWithUploadingArr:(NSMutableArray* _Nullable)uploadingArr withDoneArr:(NSMutableArray* _Nullable)doneArr withfailArr:(NSMutableArray* _Nullable)failArr
{
    if(uploadingArr){
        UITableView *curTabview = [self->_bgScrollV viewWithTag:10];
        
        if([curTabview isKindOfClass:[UITableView class]]){
            [_allDataArr replaceObjectAtIndex:0 withObject:uploadingArr];
            [curTabview reloadData];
            
            BOOL isAllSuspendType = YES;
            
            for (uploadFileDataModel*model in uploadingArr) {
                if(model.curUploadStateType != uploadStateSuspend){
                    isAllSuspendType = NO;
                    break;
                }
            }
            
            mainBlock(^{
                //刷新
                if(isAllSuspendType){
                    self->_leftHeadView.rightButton.selected = YES;
                }
            });
        }
    }
    
    if(doneArr){
        UITableView *curTabview = [self->_bgScrollV viewWithTag:11];
        
        if([curTabview isKindOfClass:[UITableView class]]){
            [_allDataArr replaceObjectAtIndex:1 withObject:doneArr];
            [curTabview reloadData];
        }
    }
    
    if(failArr){
        UITableView *curTabview = [self->_bgScrollV viewWithTag:12];
        
        if([curTabview isKindOfClass:[UITableView class]]){
            [_allDataArr replaceObjectAtIndex:2 withObject:failArr];
            [curTabview reloadData];
        }
    }
    
    [self RefresHeadUIFunBy:uploadingArr withMidArr:doneArr withRightArr:failArr];
}

#pragma mark 熟悉头部数据
-(void)RefresHeadUIFunBy:(NSMutableArray*)letfArr withMidArr:(NSMutableArray*)midArr withRightArr:(NSMutableArray*)rightArr
{

    if(letfArr){
        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,letfArr.count];

        _leftHeadView.titleLabel.text = titleStr;
        [_leftHeadView.rightButton setTitle:rightStr forState:UIControlStateNormal];
        [_leftHeadView.rightButton setTitle:rightSelectStr forState:UIControlStateSelected];
        
        if(letfArr.count == 0){
            _leftHeadView.hidden = YES;
        }
        else{
            _leftHeadView.hidden = NO;
        }
    }
    
    if(midArr){
        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,midArr.count];

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

    if(rightArr){
        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,midArr.count];

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

#pragma mark 点击上传中的全部暂停
- (void)didClickAllSuspendInLoadingFun
{
    _leftHeadView.rightButton.selected = !_leftHeadView.rightButton.selected;
    
    if(_leftHeadView.rightButton.selected){
        [[uploadFileManager shareInstance] suspendUploadFileFun:YES];
    }
    else{
        NSMutableArray *leftArr = _allDataArr[0];
        [[uploadFileManager shareInstance] reUploadFileFunBy:leftArr];
    }
}
#pragma mark 点击上传成功的清空记录
- (void)didClickClearRecordInDoneFun
{
    /*弹窗提示二次确认*/
    KWeakSelf
    ComontAlretViewController *nextVC = [[ComontAlretViewController alloc] initWithTiTle:NSLocalizedString(@"File_upload_Record_clear_Tip_title",nil)
                                                                                     msg:NSLocalizedString(@"File_upload_Record_clear_Tip_msg",nil)
                                                                                imageStr:nil
                                                                             cancelTitle:NSLocalizedString(@"other_cancel",nil)
                                                                                 okTitle:NSLocalizedString(@"other_comment_ok",nil) isOkBtnHighlight:YES
                                                                              didClickOk:^{
        [weakSelf ClearAllRecordInDoneFun];
    } didClickCancel:^{
        
    }];
    nextVC.modalPresentationStyle = UIModalPresentationCustom;
  
    [self.window.rootViewController presentViewController:nextVC animated:YES completion:^{
        nextVC.view.superview.backgroundColor = [UIColor clearColor];
    }];

}

- (void)ClearAllRecordInDoneFun
{
    [[uploadFileManager shareInstance] deleteUploadFileRecordBy:_allDataArr[1] complete:^(BOOL isSuccess) {
        HLog(@"isSuccess:%d",isSuccess);
        
        if(isSuccess){
            [self->_allDataArr replaceObjectAtIndex:1 withObject:[NSMutableArray new]];
            [self reloadAllDataFun];
        }
    }];
}

#pragma mark 点击上传失败的清空记录
- (void)didClickClearRecordInFailFun
{
    /*弹窗提示二次确认*/
    KWeakSelf
    ComontAlretViewController *nextVC = [[ComontAlretViewController alloc] initWithTiTle:NSLocalizedString(@"File_upload_Record_clear_Tip_title",nil)
                                                                                     msg:NSLocalizedString(@"File_upload_Record_clear_Tip_msg",nil)
                                                                                imageStr:nil
                                                                             cancelTitle:NSLocalizedString(@"other_cancel",nil)
                                                                                 okTitle:NSLocalizedString(@"other_comment_ok",nil) isOkBtnHighlight:YES
                                                                              didClickOk:^{
        [weakSelf ClearAllRecordInFailFun];
    } didClickCancel:^{
        
    }];
    nextVC.modalPresentationStyle = UIModalPresentationCustom;
  
    [self.window.rootViewController presentViewController:nextVC animated:YES completion:^{
        nextVC.view.superview.backgroundColor = [UIColor clearColor];
    }];

}

- (void)ClearAllRecordInFailFun
{
    [[uploadFileManager shareInstance] deleteUploadFileRecordBy:_allDataArr[2] complete:^(BOOL isSuccess) {
        HLog(@"isSuccess:%d",isSuccess);
        
        if(isSuccess){
            [self->_allDataArr replaceObjectAtIndex:2 withObject:[NSMutableArray new]];
            [self reloadAllDataFun];
        }
    }];
}


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

#pragma mark  点击全选
- (void)setIsSelectAllType:(BOOL)isSelectAllType
{
    if(isSelectAllType && _allDataArr && _allDataArr.count > (_selectIndex-1)){
        _selectModelArr = [NSMutableArray arrayWithArray:_allDataArr[_selectIndex-1]];
        [self reloadAllDataFun];
    }
}

#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){
        
        return;
    }
    
    [[uploadFileManager shareInstance] deleteUploadFileRecordBy:_selectModelArr complete:^(BOOL isSuccess) {
        HLog(@"isSuccess:%d",isSuccess);
        
        if(isSuccess){
            NSMutableArray *curArr = self->_allDataArr[self->_selectIndex -1];
            [curArr removeObjectsInArray:self->_selectModelArr];
            [self reloadAllDataFun];
            self->_selectModelArr = [NSMutableArray new];
        }
    }];
}


#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];
    }
    
}

@end
