//
//  uitableViewController.m
//  Open
//
//  Created by gao on 2017/1/20.
//  Copyright © 2017年 黄江涛 . All rights reserved.
//

#import "uitableViewController.h"
#import "LoginVC.h"
#import "Constants.h"


#import "BaseTabar.h"


@interface uitableViewController ()<UITabBarControllerDelegate>
@property (nonatomic, assign) NSDate* lastDate;
@end

@implementation uitableViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.delegate = self;
    BaseTabar*tabBar = [[BaseTabar alloc]init];
    
    [self setValue:tabBar forKey:@"tabBar"];
    
    for (UINavigationController*nav in self.viewControllers) {
        NSDictionary *textTitlOptions = @{NSFontAttributeName:[UIFont systemFontOfSize:13]};
        [nav.tabBarItem setTitleTextAttributes:textTitlOptions forState:UIControlStateNormal];
        [nav.tabBarItem setTitleTextAttributes:textTitlOptions forState:UIControlStateSelected];
        UIImage *image = [nav.tabBarItem.selectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
               self.tabBarItem.selectedImage = image;

        nav.navigationBar.tintColor = [UIColor whiteColor];
    }
    

    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reLoginClick:) name:KKSBLoginTokenOutTimeNotificationName object:nil];
    
    
    
    //解决tabbar透明问题
    if (@available(iOS 15.0, *)) {
        UITabBarAppearance * appearance = [UITabBarAppearance new];
        UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
        
        //UIGraphicsBeginImageContext(effectView.bounds.size);
        UIGraphicsImageRenderer*re=[[UIGraphicsImageRenderer alloc] initWithSize:effectView.bounds.size];
        CGContextRef context = UIGraphicsGetCurrentContext();
        [effectView.layer renderInContext:context];
        UIImage* tImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        appearance.backgroundImage = tImage;//把毛玻璃View转成Image
        self.tabBar.scrollEdgeAppearance = appearance;
    }
}

#pragma mark -  通知绑定方法
- (void)pushTargetVC {
    
    [UserDefault setBool:NO forKey:@"pushVC"];
    
    NSDictionary *dict = [UserDefault objectForKey:@"pushInfo"];
    
    [UserDefault setObject:nil forKey:@"pushInfo"];
    
    // 根据字典字段反射出我们想要的类，并初始化控制器
    Class class = NSClassFromString(dict[@"className"]);
    UIViewController *vc = [[class alloc] init];
    vc.title = dict[@"classTitle"];
    
    // 获取参数列表，使用枚举的方式，对控制器属性进行KVC赋值
    NSDictionary *parameter = dict[@"propertys"];
    [parameter enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        // 在属性赋值时，做容错处理，防止因为后台数据导致的异常
        if ([vc respondsToSelector:NSSelectorFromString(key)]) {
            [vc setValue:obj forKey:key];
        }
    }];
    
    
    
    UINavigationController* nav = self.selectedViewController;
    
    if (nav) {
        vc.hidesBottomBarWhenPushed = YES;
        [nav pushViewController:vc animated:YES];
    }
    // 从字典中获取方法名，并调用对应的方法
    NSString* methods = [NSString stringWithFormat:@"%@",dict[@"method"]];
    if (![Tools isBlankString:methods]) {
        SEL selector = NSSelectorFromString(methods);
        
        ((void (*)(id, SEL))[vc methodForSelector:selector])(vc, selector);
    }
    
}

- (UINavigationController *)currentNC {
    if (![[UIApplication sharedApplication].windows.lastObject isKindOfClass:[UIWindow class]]) {
           NSAssert(0, @"未获取到导航控制器");
           return nil;
       }
       UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
       return [self getCurrentNCFrom:rootViewController];
}


//递归
- (UINavigationController *)getCurrentNCFrom:(UIViewController *)vc
{
    if ([vc isKindOfClass:[UITabBarController class]]) {
        UINavigationController *nc = ((UITabBarController *)vc).selectedViewController;
        return [self getCurrentNCFrom:nc];
    }
    else if ([vc isKindOfClass:[UINavigationController class]]) {
        if (((UINavigationController *)vc).presentedViewController) {
            return [self getCurrentNCFrom:((UINavigationController *)vc).presentedViewController];
        }
        return [self getCurrentNCFrom:((UINavigationController *)vc).topViewController];
    }
    else if ([vc isKindOfClass:[UIViewController class]]) {
        if (vc.presentedViewController) {
            return [self getCurrentNCFrom:vc.presentedViewController];
        }
        else {
            return vc.navigationController;
        }
    }
    else {
        NSAssert(0, @"未获取到导航控制器");
        return nil;
    }
}


- (void)reLoginClick:(NSNotification *)notif {
    
    NSLog(@"token失效,请重新登录");
    
    BOOL isLoginVC = NO;
    
    UINavigationController* nav = (UINavigationController *)self.presentedViewController;
    if (nav) {
        UIViewController* vc = nav.topViewController;
        if ([vc isKindOfClass:[LoginVC class]]) {
            isLoginVC = YES;
        }
    }
    
    
    if (!isLoginVC) {
        
        [SVProgressHUD showErrorWithStatus:@"请重新登录"];
        [[NSNotificationCenter defaultCenter]postNotificationName:KKSBJumpLoginVCNotificationName object:nil];
    }		
    
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController NS_AVAILABLE_IOS(3_0)
{
    
    NSInteger loginState = [UserDefault integerForKey:@"appleLoginState"];
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"] && loginState != 1031){
        if([viewController.tabBarItem.title isEqualToString:@"我的"]){
            [[NSNotificationCenter defaultCenter]postNotificationName:KKSBJumpLoginVCNotificationName object:nil];
            return NO;
        }
        if([viewController.tabBarItem.title isEqualToString:@"财富"]){
            [[NSNotificationCenter defaultCenter]postNotificationName:KKSBJumpLoginVCNotificationName object:nil];
            return NO;
        }
    }
    
    return YES;
}
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
    if([viewController.tabBarItem.title isEqualToString:@"头条"]){
        //判断是否双击
        if ([self doubleClick]) {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"HeadNewsRefreshData" object:nil];
        }
    }
}
/*判断是否是双击(因为系统并没有提供双击的方法, 可以通过点击的时间间隔来判断)*/
- (BOOL)doubleClick {
    NSDate *date = [NSDate date];
    if (date.timeIntervalSince1970 - self.lastDate.timeIntervalSince1970 < 0.5) {
        //完成一次双击后，重置第一次单击的时间，区分3次或多次的单击
        self.lastDate = [NSDate dateWithTimeIntervalSince1970:0];
        return YES;

    }
    self.lastDate = date;
    return NO;
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KKSBLoginTokenOutTimeNotificationName object:nil];
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
