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

#import "HWBookmarkViewController.h"
#import "HWFolderModel.h"
#import "HWBookmarkListCell.h"
#import "HWBookmarkHeader.h"
#import "HWAddFolderViewController.h"
#import "HWWebViewController.h"

@interface HWBookmarkViewController ()<UITableViewDelegate,UITableViewDataSource,HWAddFolderViewControllerDelegate,HWBookmarkHeaderDelegate,HWBookmarkListCellDelegate>

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

@property (weak, nonatomic) IBOutlet UIButton       *downOneBtn;
@property (weak, nonatomic) IBOutlet UIButton       *downTwoBtn;


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

@end

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

    [self drawView];
    [self getDataWithID:-1];
}

#pragma mark - UI布局
- (void)drawView {
    
    [self.header mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(NAVIHEIGHT);
    }];
    
    [self.footer mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(TABBARHEIGHT);
    }];
    
    // 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)getDataWithID:(NSInteger)folderID {
    
    [self.dataSource removeAllObjects];
    
    NSArray *dataArray = [HWFolderModel bg_findAll:DB_BookMark_TableName];
    
    if (dataArray.count == 0) {
        HWFolderModel *model = [[HWFolderModel alloc] init];
        model.ID = 0;
        model.name = @"Personal collection";
        model.bookmarkArray = [NSMutableArray array];
        model.isExpand = YES;
        model.isEditing = NO;
        [self.dataSource addObject:model];

        // 更新数据库
        model.bg_tableName = DB_BookMark_TableName;
        [model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
            HLog(@"HWFolderModel 更新： %@", isSuccess ? @"成功":@"失败");
        }];

    }else {

        for (HWFolderModel *model in dataArray) {
            model.isExpand = NO;
            if (model.ID == folderID) {
                model.isExpand = YES;
            }
            model.isEditing = NO;
            [self.dataSource addObject:model];
        }
    }
    
    if (self.dataSource.count != 0) {
        HWFolderModel *model = self.dataSource.firstObject;
        model.isExpand = YES;
    }
    
    [self.tableView reloadData];
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    HWFolderModel *model = self.dataSource[section];
    if (model.isExpand) {
        return model.bookmarkArray.count;
    }else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HWBookmarkListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HWBookmarkListCell" forIndexPath:indexPath];
    HWFolderModel *folderModel = self.dataSource[indexPath.section];
    HWBookmarkModel *bookmarkModel = folderModel.bookmarkArray[indexPath.row];
    cell.model = bookmarkModel;
    cell.delegate = self;
    return cell;
}

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

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    HWBookmarkHeader *header = [[HWBookmarkHeader alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W - 30, 50)];
    header.delegate = self;
    HWFolderModel *folderModel = self.dataSource[section];
    header.folderModel = folderModel;
    return header;
}

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

- (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 {
    HWFolderModel *folderModel = self.dataSource[indexPath.section];
    HWBookmarkModel *bookmarkModel = folderModel.bookmarkArray[indexPath.row];
    HWWebViewController *vc = [[HWWebViewController alloc] init];
    vc.webUrl = bookmarkModel.webUrl;
    [self.navigationController pushViewController:vc animated:YES];
}

// UITableView分组切圆角方法
- (void)tableView:(UITableView*)tableView willDisplayCell:(UITableViewCell*)cell forRowAtIndexPath:(NSIndexPath*)indexPath {
    ///每个分组的行数
    NSInteger numberOfRows = [tableView numberOfRowsInSection:indexPath.section];
    ///圆角大小
    CGSize cornerRadii = CGSizeMake(10, 10);
    ///切圆角位置
    UIRectCorner corners = UIRectCornerBottomLeft | UIRectCornerBottomRight;

    if (indexPath.row == 0 && numberOfRows == 1) {
        ///一个为一组时，四个角都为圆角
        corners = UIRectCornerBottomLeft | UIRectCornerBottomRight;
    }else if (indexPath.row == 0) {
        ///分组第一行，左上、右上角为圆角
        cornerRadii = CGSizeZero;
    }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 - HWBookmarkHeaderDelegate
- (void)bookmarkHeaderDidClickExpandBtn:(HWFolderModel *)model {
    HLog(@"展开-收缩");
    for (HWFolderModel *folderModel in self.dataSource) {
        if (folderModel.ID == model.ID) {
            folderModel.isExpand = model.isExpand;
            break;
        }
    }

    [self.tableView reloadData];
}

- (void)bookmarkHeaderDidClickDeleteBtn:(HWFolderModel *)model {
    HLog(@"删除");
    NSString *ID = [NSString stringWithFormat:@"%ld", model.ID];
    NSString *where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"ID"),bg_sqlValue(ID)];
    [HWFolderModel bg_deleteAsync:DB_BookMark_TableName where:where complete:^(BOOL isSuccess) {
        HLog(@"HWFolderModel 删除：%d", isSuccess);
        mainBlock(^{
            if (isSuccess) {
                [[iToast makeText:NSLocalizedString(@"folder_deleted_successfully",nil)] show];
                
                // 刷新列表
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self getDataWithID:-1];
                });
                
            }else {
                [[iToast makeText:NSLocalizedString(@"folder_deleted_failed",nil)] show];
            }
        });

    }];
}

#pragma mark - HWBookmarkListCellDelegate
- (void)bookmarkListCellDeleteBtnClick:(HWBookmarkModel *)model {
    
    NSString *ID = [NSString stringWithFormat:@"%ld", model.folderID];
    NSString *where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"ID"),bg_sqlValue(ID)];
    NSArray *dataArray = [HWFolderModel bg_find:DB_BookMark_TableName where:where];
    if (dataArray.count == 0) {
        HLog(@"删除失败");
        return;
    }
    
    HWFolderModel *folderModel = dataArray.firstObject;
    for (HWBookmarkModel *itemModel in folderModel.bookmarkArray) {
        if (itemModel.ID == model.ID) {
            [folderModel.bookmarkArray removeObject:itemModel];
            
            [folderModel bg_saveOrUpdateAsync:^(BOOL isSuccess) {
                HLog(@"HWFolderModel 更新： %@", isSuccess ? @"成功":@"失败");
            }];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self getDataWithID:folderModel.ID];
            });
            
            break;
        }
    }
}

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

- (IBAction)downOneBtnClick:(UIButton *)sender {
    NSString *title = sender.currentTitle;
    HLog(@"%@", title);
    
    if ([title isEqualToString:NSLocalizedString(@"edit_folder",nil)]) {
        HLog(@"编辑文件夹");
        [self setModelTwo];
        [self setFolderEditing];
        
    }else {
        HLog(@"新建文件夹");
        HWAddFolderViewController *vc = [[HWAddFolderViewController alloc] init];
        vc.delegate = self;
        [self presentViewController:vc animated:YES completion:^{
            
        }];
    }
}

- (IBAction)downTwoBtnClick:(UIButton *)sender {
    NSString *title = sender.currentTitle;
    HLog(@"%@", title);
    if ([title isEqualToString:@"编辑书签"]) {
        HLog(@"编辑书签");
        [self setModelTwo];
        [self setBookmarkEditing];
        
    }else {
        HLog(@"完成");
        [self setModelOne];
        [self setBookmarkNormal];
    }
}

- (void)setModelOne {
    [self.downOneBtn setTitle:@"编辑文件夹" forState:(UIControlStateNormal)];
    [self.downTwoBtn setTitle:@"编辑书签" forState:(UIControlStateNormal)];
}

- (void)setModelTwo {
    [self.downOneBtn setTitle:@"新建文件夹" forState:(UIControlStateNormal)];
    [self.downTwoBtn setTitle:@"完成" forState:(UIControlStateNormal)];
}

- (void)setBookmarkNormal {
    
    for (HWFolderModel *model in self.dataSource) { // 全部展开
        
        model.isEditing = NO;

        for (HWBookmarkModel *model1 in model.bookmarkArray) {
            model1.isEditing = NO;
        }
    }
    
    if (self.dataSource.count != 0) {
        HWFolderModel *model = self.dataSource.firstObject;
        model.isExpand = YES;
    }
    
    [self.tableView reloadData];
}

- (void)setBookmarkEditing {
    
    for (HWFolderModel *model in self.dataSource) { // 全部展开
        
        model.isEditing = NO;

        for (HWBookmarkModel *model1 in model.bookmarkArray) {
            model1.isEditing = YES;
        }
    }
    
    if (self.dataSource.count != 0) {
        HWFolderModel *model = self.dataSource.firstObject;
        model.isExpand = YES;
    }
    
    [self.tableView reloadData];
}

- (void)setFolderEditing {
    
    for (HWFolderModel *model in self.dataSource) { // 全部展开
        
        model.isEditing = YES;
        model.isExpand = NO;
        
        for (HWBookmarkModel *model1 in model.bookmarkArray) {
            model1.isEditing = NO;
        }
    }
    
    [self.tableView reloadData];
}

#pragma mark - HWAddFolderViewControllerDelegate
- (void)addFolderWithName:(NSString *)name {
    HLog(@"添加文件夹：%@", name);
    NSString *where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"name"),bg_sqlValue(name)];
    NSArray *dataArray = [HWFolderModel bg_find:DB_BookMark_TableName where:where];
    if (dataArray.count != 0) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[iToast makeText:@"已存在同名文件夹"] show];
        });
        return;
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self addFolderUseName:name];
    });
}

- (void)addFolderUseName:(NSString *)name {
    
    [[iToast makeText:@"成功添加文件夹"] show];
    
    NSArray *dataArray = [HWFolderModel bg_findAll:DB_BookMark_TableName];
    
    // 保存文件夹
    NSInteger ID = 0;
    for (HWFolderModel *model in dataArray) { // 找出ID最大的model
        if (model.ID > ID) {
            ID = model.ID;
        }
    }
    
    HWFolderModel *model = [[HWFolderModel alloc] init];
    model.ID = ID + 1;
    model.name = name;
    model.bookmarkArray = [NSMutableArray array];
    model.isExpand = NO;
    model.isEditing = NO;
    [self.dataSource addObject:model];

    // 更新数据库
    model.bg_tableName = DB_BookMark_TableName;
    [model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
        HLog(@"HWFolderModel 更新： %@", isSuccess ? @"成功":@"失败");
    }];
    
    // 刷新列表
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self getDataWithID:-1];
    });
    
    [self setBookmarkNormal];
}

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


@end
