//
//  BaseViewController.m
//  唔即云相册
//
//  Created by 余衡武 on 2021/12/8.
//

#import "BaseViewController.h"
#import "FLAnimatedImageView.h"
#import "FLAnimatedImage.h"


#import "HWWebViewController.h"
#import "HWPageViewController.h"

@interface BaseViewController () <HWToolBarDelegate,HWSearchBarDelegate>
{
    UIView               *wattingView;
    BOOL                 needSowWattingView;
    FLAnimatedImageView  *wattingViewImageView;
}

@end

@implementation BaseViewController
@synthesize wattingViewForHaveStr;
@synthesize needSowWattingViewStr;
@synthesize navBarBGView;
@synthesize backBtn;
@synthesize titleLabel;

#pragma mark 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    _canBack = YES;
    [self drawBaseView];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    
}

//- (UIStatusBarStyle)preferredStatusBarStyle {
//    return UIStatusBarStyleDefault;
//}

#pragma mark UI布局
- (void)drawBaseView {
    
    self.navigationController.navigationBar.hidden = YES;
    self.view.backgroundColor = HW1D1E1FColor;
    
    // 导航栏
    self.navigationBar = [HWSearchBar shareInstance];
    self.navigationBar.delegate = self;
    [self.navigationBar setBackgroundColor:HW1D1E1FColor];
    [self.view addSubview:self.navigationBar];
    [self.navigationBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(64.f+AdaptNaviHeight);
    }];
    //self.navigationBar.hidden = YES;
    
    // 底部工具条
    self.toolBar = [HWToolBar shareInstance];
    self.toolBar.delegate = self;
    [self.view addSubview:self.toolBar];
    [self.toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.width.mas_equalTo(SCREEN_W);
        make.height.mas_equalTo(TABBARHEIGHT);
    }];
    //self.toolBar.hidden = YES;
    
    navBarBGView = [[UIView alloc] init];
    [navBarBGView setBackgroundColor:HWF5F7FAColor];
    [self.view addSubview:navBarBGView];
    [navBarBGView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(H_STATE_BAR + 64.f);
    }];
    [navBarBGView setHidden:YES];
    
    CGFloat btn_w_h  = 40;
    CGFloat btn_show = 28;
    backBtn = [[UIButton alloc] init];
    [navBarBGView addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(H_STATE_BAR + (64.f - btn_w_h)/2.f);
        make.left.mas_equalTo(10);
        make.width.mas_equalTo(btn_w_h);
        make.height.mas_equalTo(btn_w_h);
    }];
    [backBtn setImage:[UIImage imageNamed:@"icon_base_back"] forState:(UIControlStateNormal)];
    [backBtn setImageEdgeInsets:(UIEdgeInsetsMake((btn_w_h - btn_show)/2.f, (btn_w_h - btn_show)/2.f, (btn_w_h - btn_show)/2.f, (btn_w_h - btn_show)/2.f))];
    [backBtn addTarget:self
                action:@selector(backBtnPressed)
      forControlEvents:(UIControlEventTouchUpInside)];
//    @synthesize titleLabel;
    
    titleLabel = [[UILabel alloc] init];
    [titleLabel setTextColor:HW0A132BColor];
    [titleLabel setFont:[UIFont boldSystemFontOfSize:18.f]];
    [navBarBGView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(backBtn.mas_centerY);
        make.left.mas_equalTo(60);
        make.right.mas_equalTo(-60);
        make.height.mas_equalTo(25);
    }];
    [titleLabel setTextAlignment:(NSTextAlignmentCenter)];
}

- (void)backBtnPressed{
    if (!self.canBack) {
        HLog(@"无法返回");
        return;
    }
    
    if (self.navigationController)
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else
    {
        [self dismissViewControllerAnimated:YES completion:^{
            ;
        }];
    }
}

#pragma mark - HWSearchBarDelegate
- (void)searchBarWithText:(NSString *)text {
    HLog(@"搜索：%@", text)
}

#pragma mark - HWToolBarDelegate
- (void)backBtnDidClick {
    HLog(@"后退");
}

- (void)forwardBtnDidClick {
    HLog(@"前进");
}

- (void)toolBtnDidClick {
    HLog(@"工具");
}

- (void)homeBtnDidClick {
    HLog(@"主页");
    HWWebViewController *vc = [[HWWebViewController alloc] init];
    vc.webUrl = Const_HomeUrl;
    UINavigationController *nvc = [[UINavigationController alloc] initWithRootViewController:vc];
    UIWindow *keyWindow = [iTools getKeyWindow];
    keyWindow.rootViewController = nvc;
}

- (void)pageBtnDidClick {
    HLog(@"页面");
    
    // 1、更新截图
    [self updateBrowserImageWithWindow];
    
    // 2、跳转控制器
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        HWPageViewController *vc = [[HWPageViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    });
}

- (void)updateBrowserImageWithWindow {
    
    // 浏览器当前窗口索引ID
    NSInteger ID = [HWDataManager getIntegerWithKey:BrowserWindowsCurrentID];
    NSString *IDValue = [NSString stringWithFormat:@"%ld", ID];
    NSString *where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"ID"),bg_sqlValue(IDValue)];
    NSArray *modelArr = [BaseModel bg_find:DB_BrowserWindows_TableName where:where];
    
    if (modelArr.count == 0) { // 当前窗口已被删除 更新BrowserWindowsCurrentID
        
        BaseModel *lastModel = [BaseModel bg_lastObject:DB_BrowserWindows_TableName];
        [HWDataManager setIntegerWithKey:BrowserWindowsCurrentID value:lastModel.ID];
    
    }else { // 当前窗口加载页面 更新model
        
        BaseModel *model = modelArr.firstObject;
        // 更新截图
        UIImage *image = [self getScreenShotImageFromBase];
        if (!image) {
            HLog(@"截图获取失败");
            return;
        }
        NSString *imageName = [NSString stringWithFormat:@"%ld", ID];
        NSString *imageUrl = [HWDataManager writeScreenShotImageToLocal:image withName:imageName];
        model.iconFile = imageUrl;
        
        // 更新数据库
        model.bg_tableName = DB_BrowserWindows_TableName;
        [model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
            HLog(@"BaseModel更新： %@", isSuccess ? @"成功":@"失败");
        }];
    }
}

/**View截图*/
- (UIImage *)getScreenShotImageFromBase {
    
    CGSize size = self.view.frame.size;
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return viewImage;
}

#pragma mark loading
-(void)showNewIndicatorWithCanBack:(BOOL)canBack canTouch:(BOOL)canTouch
{
    
    needSowWattingView = YES;
    self.canTouch = canTouch;
    self.canBack  = canBack;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (self->needSowWattingView)
        {
            if (self->wattingView == nil)
            {
                HLog(@"Tan +++++开");
                self->wattingView =  [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
                [self->wattingView setBackgroundColor:RGBACOLOR(0.f, 0.f, 0.f, 0.7)];
                [self->wattingView.layer setCornerRadius:10.f];
                self->wattingView.center = [iTools getKeyWindow].center;// 将wattingVideoImageindicator放于播放画面的中央位置
                self->wattingView.hidden = NO;
                
                  FLAnimatedImage *image = [FLAnimatedImage animatedImageWithGIFData:[NSData dataWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"loadingWhiteGif" withExtension:@"gif"]]];
//                  image.loopCount = 0; // 重复次数0 无限循环重复动画
                  FLAnimatedImageView  *upView =  [[FLAnimatedImageView alloc] init];
                  [upView setFrame:CGRectMake((100 - 65.f)/2.f, (100 - 65.f)/2.f, 65.f, 65.f)];
                  [upView setContentMode:UIViewContentModeScaleAspectFill];
                  [upView setBackgroundColor:[ UIColor clearColor]];
                  upView.animatedImage = image;
                  [self->wattingView addSubview:upView];

                [[iTools getKeyWindow] addSubview:self->wattingView];
            }
        }
    });
}


-(void)showNewIndicatorHaveStrWithCanBack:(BOOL)canBack canTouch:(BOOL)canTouch showText:(NSString *)text
{
    needSowWattingViewStr = YES;
    self.canTouch = canTouch;
    self.canBack  = canBack;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.001 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (self->needSowWattingViewStr)
        {
            if (self->wattingViewForHaveStr == nil)
            {
                HLog(@"Tan +++++开");
                self->wattingViewForHaveStr =  [[UIView alloc] initWithFrame:CGRectMake(0, 0, 135, 135)];
                [self->wattingViewForHaveStr setBackgroundColor:RGBACOLOR(0, 0, 0, 0.5)];
                [self->wattingViewForHaveStr.layer setCornerRadius:11.f];
                self->wattingViewForHaveStr.center = [iTools getKeyWindow].center;// 将wattingVideoImageindicator放于播放画面的中央位置
                self->wattingViewForHaveStr.hidden = NO;
                
                UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 90, 135-10, 40)];
                [contentLabel setBackgroundColor:[UIColor clearColor]];
                [contentLabel setText:text];
                [contentLabel setTextAlignment:(NSTextAlignmentCenter)];
                [contentLabel setTextColor:[UIColor whiteColor]];
                [contentLabel setFont:[UIFont systemFontOfSize:14]];
                contentLabel.numberOfLines = 0;
                [self->wattingViewForHaveStr addSubview:contentLabel];
                
                FLAnimatedImage *image = [FLAnimatedImage animatedImageWithGIFData:[NSData dataWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"loadingWhiteGif" withExtension:@"gif"]]];
                
                FLAnimatedImageView  *upView =  [[FLAnimatedImageView alloc] init];
                [upView setFrame:CGRectMake((135 - 59.f)/2.f, 25.f , 59.f, 59.f)];
                [upView setContentMode:UIViewContentModeScaleAspectFill];
                [upView setBackgroundColor:[ UIColor clearColor]];
                upView.animatedImage = image;
                [self->wattingViewForHaveStr addSubview:upView];

                [[iTools getKeyWindow] addSubview:self->wattingViewForHaveStr];
            }
        }
        
    });
}


-(void)removeNewIndicatorHaveStr
{
    needSowWattingViewStr = NO;
    __weak __typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        self.canTouch = YES;
        self.canBack  = YES;
        [weakSelf.view setUserInteractionEnabled:YES];
        if (self->wattingViewForHaveStr != nil)
        {
            [[self->wattingViewForHaveStr viewWithTag:1111].layer removeAllAnimations];
            
            self->wattingViewForHaveStr.hidden = YES;
            [self->wattingViewForHaveStr removeFromSuperview];
            self->wattingViewForHaveStr = nil;
        }
    });
}


-(void)removeNewIndicator
{
    
    needSowWattingView = NO;
    __weak __typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        self.canTouch = YES;
        self.canBack  = YES;
        [weakSelf.view setUserInteractionEnabled:YES];
        if (self->wattingView != nil)
        {
            [[self->wattingView viewWithTag:1111].layer removeAllAnimations];
            
            self->wattingView.hidden = YES;
            [self->wattingView removeFromSuperview];
            self->wattingView = nil;
        }
    });
}

@end
