//
//  HWHistoryViewController.m
//  双子星云手机
//
//  Created by 余衡武 on 2022/3/25.
//

#import "HWHistoryViewController.h"
#import "HWBookmarkListCell.h"
#import "HWWebViewController.h"
#import "HWHistoryModel.h"

@interface HWHistoryViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UIView         *header;

@property (weak, nonatomic) IBOutlet UITableView    *tableView;

@property (strong, nonatomic) NSMutableArray        *dataSource1; // 今天
@property (strong, nonatomic) NSMutableArray        *dataSource2; // 昨天
@property (strong, nonatomic) NSMutableArray        *dataSource3; // 以前
@property (strong, nonatomic) HWHistoryModel        *deleteModel;

@end

@implementation HWHistoryViewController

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];

    [self drawView];
    [self getData];
}

#pragma mark - UI布局
- (void)drawView {
    
    [self.header mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(NAVIHEIGHT);
    }];
    
    // tableView
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.contentInset = UIEdgeInsetsMake(10, 0, 10, 0);
    [self.tableView registerNib:[UINib nibWithNibName:@"HWBookmarkListCell" bundle:nil] forCellReuseIdentifier:@"HWBookmarkListCell"];
}

#pragma mark - 获取数据
- (void)getData {
    
    [self.dataSource1 removeAllObjects];
    [self.dataSource2 removeAllObjects];
    [self.dataSource3 removeAllObjects];
    
    NSArray *dataArray = [HWHistoryModel bg_findAll:DB_Bookmark_History_TableName];
    
    for (HWHistoryModel *model in dataArray) {
        
        double cTime = (double)model.cTime;
        double nowDataTime = [[NSDate date] timeIntervalSince1970];
        double cha = nowDataTime - cTime;
        
        double oneDay = 60*60*24.0;
        double twoDay = 60*60*24.0*2;
        
        if (cha < oneDay) { // 今天
            [self.dataSource1 addObject:model];
        }else if (cha < twoDay) { // 昨天
            [self.dataSource2 addObject:model];
        }else { // 以前
            [self.dataSource3 addObject:model];
        }
        
    }
    
    [self.tableView reloadData];
}


- (void)deleteWithModel:(HWHistoryModel *)model {
    
    NSString *webUrl = model.webUrl;
    NSString *where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"webUrl"),bg_sqlValue(webUrl)];
    [HWHistoryModel bg_deleteAsync:DB_Bookmark_History_TableName where:where complete:^(BOOL isSuccess) {
        HLog(@"HWHistoryModel 删除 %@", isSuccess ? @"成功":@"失败");
        mainBlock(^{
            // 刷新表格
            [self getData];
        });
    }];
}

- (void)clearData {
    [HWHistoryModel bg_clearAsync:DB_Bookmark_History_TableName complete:^(BOOL isSuccess) {
        HLog(@"DB_Bookmark_History_TableName 清除 %@", isSuccess ? @"成功":@"失败");
        mainBlock(^{
            // 刷新表格
            [self getData];
        });
    }];
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0) {
        return self.dataSource1.count;
    }else if (section == 1) {
        return self.dataSource2.count;
    }else {
        return self.dataSource3.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HWBookmarkListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HWBookmarkListCell" forIndexPath:indexPath];
    
    HWHistoryModel *historyModel;
    if (indexPath.section == 0) {
        historyModel = self.dataSource1[indexPath.row];
    }else if (indexPath.section == 1) {
        historyModel = self.dataSource2[indexPath.row];
    }else {
        historyModel = self.dataSource3[indexPath.row];
    }
    
    cell.historyModel = historyModel;
//    cell.delegate = self;
    return cell;
}

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

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    CGFloat height = 50;
    
    if (section == 0 && self.dataSource1.count == 0) {
        height = 0.1;
    }else if (section == 1 && self.dataSource2.count == 0) {
        height = 0.1;
    }else if (section == 2 && self.dataSource3.count == 0) {
        height = 0.1;
    }
    
    return height;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    // 1、无数据情况
    if (section == 0 && self.dataSource1.count == 0) {
        return [[UIView alloc] init];
    }else if (section == 1 && self.dataSource2.count == 0) {
        return [[UIView alloc] init];
    }else if (section == 2 && self.dataSource3.count == 0) {
        return [[UIView alloc] init];
    }

    // 2、有数据情况
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W - 30, 50)];
    
    UILabel *titleLabel =  [[UILabel alloc] init];
    titleLabel.font = [UIFont boldSystemFontOfSize:15.f];
    titleLabel.numberOfLines = 1;
    titleLabel.textColor = HWFFFFFF80Color;
    titleLabel.textAlignment = NSTextAlignmentLeft;
    [header addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(20);
        make.centerY.mas_equalTo(header.mas_centerY);
    }];
    
    if (section == 0) {
        titleLabel.text = NSLocalizedString(@"history_today",nil);
    }else if (section == 1) {
        titleLabel.text = NSLocalizedString(@"history_yesterday",nil);
    }else if (section == 2) {
        titleLabel.text = NSLocalizedString(@"history_before",nil);
    }
    
    return header;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W - 30, 5)];
    footer.backgroundColor = [UIColor hwColor:@"#101010"];
    return footer;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    HWHistoryModel *historyModel;
    if (indexPath.section == 0) {
        historyModel = self.dataSource1[indexPath.row];
    }else if (indexPath.section == 1) {
        historyModel = self.dataSource2[indexPath.row];
    }else {
        historyModel = self.dataSource3[indexPath.row];
    }

    HWWebViewController *vc = [[HWWebViewController alloc] init];
    vc.webUrl = historyModel.webUrl;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath{

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.03 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self setupSlideBtnWithEditingIndexPath:indexPath];
    });

}

- (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath{

}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

// 删除Cell回调
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    // 发送请求
    HLog(@"左滑删除操作");
//    CloudGameDownLoadMode *model = self.dataSource[indexPath.row];
//    [self deleteModel:model];
}

#pragma mark - 左滑菜单按钮自定义
// 判断系统是否是 iOS13 及以上版本
- (void)setupSlideBtnWithEditingIndexPath:(NSIndexPath *)editingIndexPath {
    if (@available(iOS 13.0, *)) {
        
        for (UIView *subView in self.tableView.subviews) {
            if ([subView isKindOfClass:NSClassFromString(@"_UITableViewCellSwipeContainerView")] && [subView.subviews count] >= 1) {
                // 修改图片
                UIView *remarkContentView = subView.subviews.firstObject;
                [self setupRowActionView:remarkContentView row:editingIndexPath];
            }
        }
        return;
        
    }
    
    // 判断系统是否是 iOS11 及以上版本
    if (@available(iOS 11.0, *)) {
        
        for (UIView *subView in self.tableView.subviews) {
            if ([subView isKindOfClass:NSClassFromString(@"UISwipeActionPullView")] && [subView.subviews count] >= 1) {
                // 修改图片
                UIView *remarkContentView = subView;
                [self setupRowActionView:remarkContentView row:editingIndexPath];
            }
        }
        return;
    }
    
    // iOS11 以下的版本
    HWBookmarkListCell *cell = [self.tableView cellForRowAtIndexPath:editingIndexPath];
    for (UIView *subView in cell.subviews) {
        if ([subView isKindOfClass:NSClassFromString(@"UITableViewCellDeleteConfirmationView")] && [subView.subviews count] >= 1) {
            // 修改图片
            UIView *remarkContentView = subView;
            [self setupRowActionView:remarkContentView row:editingIndexPath];
        }
    }
}

- (void)setupRowActionView:(UIView *)rowActionView row:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        self.deleteModel = self.dataSource1[indexPath.row];
    }else if (indexPath.section == 1) {
        self.deleteModel = self.dataSource2[indexPath.row];
    }else {
        self.deleteModel = self.dataSource3[indexPath.row];
    }
    
    [rowActionView setBackgroundColor:[UIColor clearColor]];
    
    UIButton *deleteBtn = [[UIButton alloc] initWithFrame:(CGRectMake(15, 0, 60.f, 50.f))];
    [deleteBtn.layer setCornerRadius:10.f];
    deleteBtn.clipsToBounds = YES;
    [deleteBtn setBackgroundColor:[UIColor redColor]];
    [deleteBtn setTitle:@"删除" forState:(UIControlStateNormal)];
    [deleteBtn.titleLabel setFont:[UIFont systemFontOfSize:12.f]];
    [deleteBtn setImage:[UIImage imageNamed:@"faceback_list_delete"] forState:(UIControlStateNormal)];
    [deleteBtn setTitleEdgeInsets:UIEdgeInsetsMake(deleteBtn.imageView.frame.size.height+3.f ,-deleteBtn.imageView.frame.size.width, 0.0,0.0)];//文字距离上边框的距离增加imageView的高度，距离左边框减少imageView的宽度，距离下边框和右边框距离不变
    [deleteBtn setImageEdgeInsets:UIEdgeInsetsMake(-deleteBtn.imageView.frame.size.height+7 , 0.0,0.0, -deleteBtn.titleLabel.bounds.size.width)];
    [deleteBtn addTarget:self
                  action:@selector(deleteMessage:)
        forControlEvents:(UIControlEventTouchUpInside)];
    [deleteBtn setTag:12345+indexPath.row];
    
    [rowActionView addSubview:deleteBtn];
    
    UIButton *button = rowActionView.subviews.firstObject;
    [button removeFromSuperview];
}

- (void)deleteMessage:(id)sender {
    HLog(@"删除");
    [self deleteWithModel:self.deleteModel];
}


// UITableView分组切圆角方法
- (void)tableView:(UITableView*)tableView willDisplayCell:(UITableViewCell*)cell forRowAtIndexPath:(NSIndexPath*)indexPath {
    ///每个分组的行数
    NSInteger numberOfRows = [tableView numberOfRowsInSection:indexPath.section];
    ///圆角大小
    CGSize cornerRadii = CGSizeMake(10, 10);
    ///切圆角位置
    UIRectCorner corners = UIRectCornerAllCorners;
    
    if (indexPath.row == 0 && numberOfRows == 1) {
        ///一个为一组时，四个角都为圆角
        corners = UIRectCornerAllCorners;
    }else if (indexPath.row == 0) {
        ///分组第一行，左上、右上角为圆角
        corners = UIRectCornerTopLeft | UIRectCornerTopRight;
    }else if (indexPath.row + 1 == numberOfRows) {
        ///分组最后一行，左下、右下角为圆角
        corners = UIRectCornerBottomLeft | UIRectCornerBottomRight;
    }else {
        ///中间的都为矩形
        cornerRadii = CGSizeZero;
    }
    
    CGRect cellRect = cell.contentView.bounds;
    UIBezierPath*maskPath = [UIBezierPath bezierPathWithRoundedRect:cellRect byRoundingCorners:corners cornerRadii:cornerRadii];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = cellRect;
    maskLayer.path = maskPath.CGPath;
    cell.contentView.layer.mask = maskLayer;
}

#pragma mark - 点击事件
- (IBAction)backBtnClick:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)clearBtnClick:(UIButton *)sender {
    HLog(@"清空");
    [self toShowTips];
}

- (void)toShowTips {

    NSString *tipsStr = NSLocalizedString(@"history_delete_history_tips",nil);

    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"other_confirm",nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self clearData];
    }];
    [sureAction setValue:[UIColor hwColor:@"#3B7FFF"] forKey:@"titleTextColor"];//iOS8.3
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"other_cancel",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [cancelAction setValue:[UIColor colorWithHexString:@"#FFFFFF" alpha:0.5] forKey:@"titleTextColor"];//iOS8.3
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:tipsStr message:@"" preferredStyle:(UIAlertControllerStyleAlert)];
    alertVC.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;
    [alertVC addAction:sureAction];
    [alertVC addAction:cancelAction];

    [self presentViewController:alertVC animated:YES completion:^{
        
    }];
}

#pragma mark - 懒加载
- (NSMutableArray *)dataSource1 {
    if (!_dataSource1) {
        _dataSource1 = [NSMutableArray array];
    }
    return _dataSource1;
}

- (NSMutableArray *)dataSource2 {
    if (!_dataSource2) {
        _dataSource2 = [NSMutableArray array];
    }
    return _dataSource2;
}

- (NSMutableArray *)dataSource3 {
    if (!_dataSource3) {
        _dataSource3 = [NSMutableArray array];
    }
    return _dataSource3;
}

@end
