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

#import "HWPageViewController.h"
#import "HWPageListCell.h"
#import "HWWebViewController.h"
#import <WebKit/WebKit.h>

@interface HWPageViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,HWPageListCellDelegate>

@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (weak, nonatomic) IBOutlet UIView *footerView;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong, nonatomic) NSMutableArray            *dataSource;

@end

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

    [self drawView];
    [self getData];
}

#pragma mark UI布局
- (void)drawView {
    
    [self.headerView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(20+AdaptNaviHeight);
    }];
    
    [self.footerView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(49+AdaptTabHeight);
    }];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.contentInset = UIEdgeInsetsMake(15, 15, 0, 15);
    self.collectionView.backgroundColor = [UIColor clearColor];
    [self.collectionView registerNib:[UINib nibWithNibName:@"HWPageListCell" bundle:nil] forCellWithReuseIdentifier:@"HWPageListCell"];
    
    UICollectionViewFlowLayout *dataLayout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
    CGFloat W = (SCREEN_W - 15*3)*0.5;
    CGFloat H = 280*WAUTOSCALE;
    dataLayout.itemSize = CGSizeMake(W, H);
    dataLayout.minimumLineSpacing = 0;
    dataLayout.minimumInteritemSpacing = 5;
    dataLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
}

#pragma mark 获取数据
- (void)getData {
    
    [self.dataSource removeAllObjects];
    
    NSArray *dataArray = [BaseModel bg_findAll:DB_BrowserWindows_TableName];
    
    if (dataArray.count == 0) {
        
        // 主页
        [self.navigationController popViewControllerAnimated:YES];
        
    }else {
        [self.dataSource addObjectsFromArray:dataArray];
        [self.collectionView reloadData];
    }
}

#pragma mark UICollectionViewDelegate, UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HWPageListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HWPageListCell" forIndexPath:indexPath];
    BaseModel *model = self.dataSource[indexPath.row];
    cell.model = model;
    cell.delegate = self;
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    BaseModel *model = self.dataSource[indexPath.row];
    // 浏览器当前窗口索引ID
    [HWDataManager setIntegerWithKey:BrowserWindowsCurrentID value:model.ID];
    
    if ([model.webUrl isEqualToString:Const_HomeUrl]) {
        // 主页
        HWWebViewController *vc = [[HWWebViewController alloc] init];
        vc.webUrl = Const_HomeUrl;
        UINavigationController *nvc = [[UINavigationController alloc] initWithRootViewController:vc];
        UIWindow *keyWindow = [iTools getKeyWindow];
        keyWindow.rootViewController = nvc;
        
    }else {
        // 网页
        HWWebViewController *vc = [[HWWebViewController alloc] init];
        vc.webUrl = model.webUrl;
        UINavigationController *nvc = [[UINavigationController alloc] initWithRootViewController:vc];
        UIWindow *keyWindow = [iTools getKeyWindow];
        keyWindow.rootViewController = nvc;
    }
}

#pragma mark HWPageListCellDelegate
- (void)deleteBtnClickWithModel:(BaseModel *)model {

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

#pragma mark 点击事件
- (IBAction)backBtnClick:(UIButton *)sender {
    HLog(@"返回");
    [[NSNotificationCenter defaultCenter] postNotificationName:WebviewReloadNotification object:nil];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)addBtnClick:(UIButton *)sender {

    NSArray *dataArray = [BaseModel bg_findAll:DB_BrowserWindows_TableName];
    NSInteger index = 0;
    for (BaseModel *model in dataArray) { // 找出ID最大的model
        if (model.ID > index) {
            index = model.ID;
        }
    }
    
    HLog(@"添加");
    // 浏览器当前窗口索引ID
    NSInteger ID = index + 1;
    BaseModel *model = [[BaseModel alloc] init];
    model.ID = ID;
    model.name = @"主页";
//        model.iconFile = imageUrl;
    model.webUrl = Const_HomeUrl;
    
    // 更新数据库
    [HWDataManager setIntegerWithKey:BrowserWindowsCurrentID value:ID];
    
    model.bg_tableName = DB_BrowserWindows_TableName;
    [model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
        HLog(@"BaseModel更新： %@", isSuccess ? @"成功":@"失败");
    }];
    
    // 跳转到主页
    HWWebViewController *vc = [[HWWebViewController alloc] init];
    vc.webUrl = Const_HomeUrl;
    UINavigationController *nvc = [[UINavigationController alloc] initWithRootViewController:vc];
    UIWindow *keyWindow = [iTools getKeyWindow];
    keyWindow.rootViewController = nvc;
}

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

@end
