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

#import "HWAddBookmarkViewController.h"
#import "HWFolderListCell.h"

@interface HWAddBookmarkViewController () <UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UIView         *bgView;
@property (weak, nonatomic) IBOutlet UITextField    *titleTextField;
@property (weak, nonatomic) IBOutlet UITextField    *urlTextField;

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

@end

@implementation HWAddBookmarkViewController
#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
 
    [self drawView];
    [self getData];
}

#pragma mark - UI布局
- (void)drawView {
    
    self.bgView.layer.cornerRadius = 10;
    self.bgView.layer.masksToBounds = YES;
    
    self.titleTextField.clearButtonMode = UITextFieldViewModeAlways;
    self.urlTextField.clearButtonMode = UITextFieldViewModeAlways;
    
    self.titleTextField.text = self.model.name;
    self.urlTextField.text = self.model.webUrl;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"HWFolderListCell" bundle:nil] forCellReuseIdentifier:@"HWFolderListCell"];
    
    NSAttributedString *attrString1 = [[NSAttributedString alloc] initWithString:@"请输入书签标题" attributes:
    @{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"FFFFFF" alpha:0.2],
                 NSFontAttributeName:[UIFont systemFontOfSize:14.f]}];
    self.titleTextField.attributedPlaceholder = attrString1;
    
    NSAttributedString *attrString2 = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"input_mark_url",nil) attributes:
    @{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"FFFFFF" alpha:0.2],
                 NSFontAttributeName:[UIFont systemFontOfSize:14.f]}];
    self.urlTextField.attributedPlaceholder = attrString2;
}

#pragma mark - 获取数据
- (void)getData {
    
    [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.isSelected = YES;
        [self.dataSource addObject:model];
        
        // 更新数据库
        model.bg_tableName = DB_BookMark_TableName;
        [model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
            HLog(@"HWFolderModel 更新： %@", isSuccess ? @"成功":@"失败");
        }];
        
    }else {
        
        for (HWFolderModel *model in dataArray) {
            if ([model.name isEqualToString:@"Personal collection"]) {
                model.isSelected = YES;
            }else {
                model.isSelected = NO;
            }
            [self.dataSource addObject:model];
        }
    }
    
    [self.tableView reloadData];
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HWFolderListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HWFolderListCell" forIndexPath:indexPath];
    HWFolderModel *model = self.dataSource[indexPath.row];
    cell.model = model;
    return cell;
}

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

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HWFolderModel *model = self.dataSource[indexPath.row];
    if (model.isSelected) {
        return;
    }
    
    for (HWFolderModel *itemModel in self.dataSource) {
        
        if ([itemModel.name isEqualToString:model.name]) {
            itemModel.isSelected = YES;
        }else {
            itemModel.isSelected = NO;
        }
    }
    
    [self.tableView reloadData];
}

// 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)cancelBtnClick:(UIButton *)sender {
    HLog(@"取消");
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (IBAction)sureBtnClick:(UIButton *)sender {
    HLog(@"完成");
    
    // 1、书签保存的文件夹
    HWFolderModel *selectFolderModel;
    for (HWFolderModel *model in self.dataSource) {
        
        if (model.isSelected) {
            selectFolderModel = model;
            break;
        }
    }
    
    // 2、保存的书签
    NSInteger ID = 0;
    for (HWBookmarkModel *model in selectFolderModel.bookmarkArray) { // 找出ID最大的model
        if (model.ID > ID) {
            ID = model.ID;
        }
    }
    
    HWBookmarkModel *bookmarkModel = [[HWBookmarkModel alloc] init];
    bookmarkModel.ID = ID + 1;
    bookmarkModel.folderID = selectFolderModel.ID;
    bookmarkModel.name = self.model.name;
    bookmarkModel.webUrl = self.model.webUrl;
    
    // 3、书签写入文件夹
    [selectFolderModel.bookmarkArray addObject:bookmarkModel];
    
    // 4、更新数据库缓存
    selectFolderModel.bg_tableName = DB_BookMark_TableName;
    [selectFolderModel bg_saveOrUpdateAsync:^(BOOL isSuccess) {
        HLog(@"HWFolderModel 更新： %@", isSuccess ? @"成功":@"失败");
    }];
    
    // 5、提示用户
    [self dismissViewControllerAnimated:YES completion:^{
        [[iToast makeText:NSLocalizedString(@"other_add_bookmark_success",nil)] show];
    }];
}

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

@end
