//
//  ZYTabBarController.m
//  tabbar增加弹出bar
//
//  Created by tarena on 16/7/2.
//  Copyright © 2016年 张永强. All rights reserved.
//
#import "WYTabBarController.h"
#import "HomeViewController.h"
#import "MineViewController.h"
#import "xiaoxiViewController.h"
#import "MyCourseViewController.h"

//@import CoreLocation;

@interface WYTabBarController ()<UITabBarDelegate,UITabBarControllerDelegate>
{
    UIAlertController *alertupdate;
}
@property(nonatomic,strong)NSString *Build;

@end
@implementation WYTabBarController
#pragma mark ============定位=============

//是否可以旋转
- (BOOL)shouldAutorotate
{
    return NO;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.delegate = self;

    [self buildUpdate];
//    [self.tabBar setBackgroundColor:[UIColor whiteColor]];
    
    [self.tabBar setBarTintColor:[UIColor whiteColor]];
    self.tabBar.translucent = NO;
    //设置子视图
    [self setUpAllChildVc];
    [self setCusTintColor];
    self.automaticallyAdjustsScrollViewInsets = NO;

    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    
    AFNetworkReachabilityManager *netManager = [AFNetworkReachabilityManager sharedManager];
    [netManager startMonitoring];  //开始监听 防止第一次安装不显示
    [netManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status){
        if (status == AFNetworkReachabilityStatusNotReachable)
        {
            [self buildUpdate];
            return;
        }else if (status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable){
            NSLog(@"nonetwork-------");
            [self buildUpdate];
        }else if ((status == AFNetworkReachabilityStatusReachableViaWWAN)||(status == AFNetworkReachabilityStatusReachableViaWiFi)){
            [self buildUpdate];
            NSLog(@"wifi-------");
        }
    }];

}

#pragma mark  在这里更换 左右tabbar的image
- (void)setUpAllChildVc {
    HomeViewController *home = [HomeViewController new];
    xiaoxiViewController *message = [xiaoxiViewController new];
    MineViewController *mine = [MineViewController new];
    MyCourseViewController *course  =[MyCourseViewController new];

    [self setUpOneChildVcWithVc:home Image:@"首页" selectedImage:@"首页_sel" title:@"首页" andTag:0];
    [self setUpOneChildVcWithVc:course Image:@"我的课程" selectedImage:@"我的课程_sel" title:@"我的课程" andTag:1];
    [self setUpOneChildVcWithVc:message Image:@"消息" selectedImage:@"消息_sel" title:@"消息" andTag:2];
    [self setUpOneChildVcWithVc:mine Image:@"个人中心" selectedImage:@"个人中心_sel" title:@"个人中心" andTag:3];
}
#pragma mark - 初始化设置tabBar上面单个按钮的方法
/**
 *  @author li bo, 16/05/10
 *
 *  设置单个tabBarButton
 *
 *  @param Vc            每一个按钮对应的控制器
 *  @param image         每一个按钮对应的普通状态下图片
 *  @param selectedImage 每一个按钮对应的选中状态下的图片
 *  @param title         每一个按钮对应的标题
 */
- (void)setUpOneChildVcWithVc:(UIViewController *)Vc Image:(NSString *)image selectedImage:(NSString *)selectedImage title:(NSString *)title andTag:(int)tttttt
{
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:Vc];
    UIImage *myImage = [UIImage imageNamed:image];
    myImage = [myImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    //tabBarItem，是系统提供模型，专门负责tabbar上按钮的文字以及图片展示
    Vc.tabBarItem.image = myImage;
    UIImage *mySelectedImage = [UIImage imageNamed:selectedImage];
    mySelectedImage = [mySelectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    Vc.tabBarItem.selectedImage = mySelectedImage;
    Vc.tabBarItem.title = title;
    Vc.navigationController.navigationBar.hidden = YES;
    Vc.tabBarItem.tag = tttttt;
    [self addChildViewController:nav];
}
-(void)setCusTintColor {
    [[UITabBarItem appearance]setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor blackColor],NSForegroundColorAttributeName,SYS_Font(10),NSFontAttributeName,nil]forState:UIControlStateNormal];
    [[UITabBarItem appearance]setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:normalColors,NSForegroundColorAttributeName,SYS_Font(10),NSFontAttributeName,nil]forState:UIControlStateSelected];
}
//点击开始直播
-(void)buildUpdate{
    //在这里加载后台配置文件
    [WYToolClass postNetworkWithUrl:@"Home.GetConfig" andParameter:nil success:^(int code, id  _Nonnull info, NSString * _Nonnull msg) {
        if (code == 0) {
            NSDictionary *subdic = [info firstObject];
            if (![subdic isEqual:[NSNull null]]) {
//                [[TIMGroupManager sharedInstance] joinGroup:minstr([subdic valueForKey:@"full_group_id"]) msg:@"IOS Join Group" succ:^(){
//                    NSLog(@"Join Succ");
//                }fail:^(int code, NSString * err) {
//                    NSLog(@"code=%d, err=%@", code, err);
//                }];

                NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
                NSNumber *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];//本地 build
                NSString *buildsss = [NSString stringWithFormat:@"%@",app_build];
                //如果不相等说明未上架，检测是否是新版本
                if (![buildsss isEqual:[NSString stringWithFormat:@"%@",[subdic valueForKey:@"ios_shelves"]]]) {
                    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
                    NSNumber *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];//本地
                    NSNumber *build = [subdic valueForKey:@"ipa_ver"];//远程
                    NSComparisonResult r = [app_build compare:build];
                    _Build =[NSString stringWithFormat:@"%@",[subdic valueForKey:@"ipa_url"]];
                    NSString *ipa_des = [NSString stringWithFormat:@"%@",[subdic valueForKey:@"ipa_des"]];
                    if (r == NSOrderedAscending || r == NSOrderedDescending) {//可改为if(r == -1L)
                        alertupdate = [UIAlertController alertControllerWithTitle:@"提示" message:ipa_des preferredStyle:UIAlertControllerStyleAlert];
                        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"使用旧版" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                        }];
                        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"前往更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_Build]];
                        }];
                        [alertupdate addAction:action1];
                        [alertupdate addAction:action2];
                        [self presentViewController:alertupdate animated:YES completion:nil];
                    }
                    NSString *maintain_switch = [NSString stringWithFormat:@"%@",[subdic valueForKey:@"maintain_switch"]];
                    NSString *maintain_tips = [NSString stringWithFormat:@"%@",[subdic valueForKey:@"maintain_tips"]];
                    if ([maintain_switch isEqual:@"1"]) {
                        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"维护信息" message:maintain_tips preferredStyle:UIAlertControllerStyleAlert];
                        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_Build]];
                        }];
                        [alertC addAction:action2];
                        [self presentViewController:alertC animated:YES completion:nil];
                    }
                }
                liveCommon *commons = [[liveCommon alloc]initWithDic:subdic];
                [common saveProfile:commons];
            }

        }
    } fail:^{
        
    }];
}

//- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item{
//
//    NSArray * sss = self.tabBar.subviews;
//
//
//    UIView *tabbarbutton = sss[item.tag+1];
//
//
//    for (UIView *view in tabbarbutton.subviews) {
//
//
//
//        if ([view isKindOfClass:NSClassFromString(@"UITabBarSwappableImageView")]) {
//
//
//            [self.animation removeFromSuperview];
//            NSString * name = self.imgParr[item.tag];
//            CGFloat scale = [[UIScreen mainScreen] scale];
//            name = 3.0 == scale ? [NSString stringWithFormat:@"%@@3x", name] : [NSString stringWithFormat:@"%@@2x", name];
//            LOTAnimationView *animation = [LOTAnimationView animationNamed:name];
//            [view addSubview:animation];
//            animation.bounds = CGRectMake(0, 0,view.bounds.size.width,view.bounds.size.width);
//            animation.center = CGPointMake(view.bounds.size.width/2, view.bounds.size.height/2);
//            [animation playWithCompletion:^(BOOL animationFinished) {
//                // Do Something
//            }];
//            self.animation = animation;
//        }
//
//    }
//
//}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
    
    UINavigationController *nav = (UINavigationController *)viewController;
    UIViewController *VC =nav.topViewController;
    if ([VC isKindOfClass:[HomeViewController class]]) {
                
        return YES;
    }else{
        if (![Config getOwnID] || [[Config getOwnID] intValue] == 0) {
            [[WYToolClass sharedInstance] showLoginView];
            return NO;
        }
    }
    return YES;
    
}
//-(NSArray *)imgParr
//{
//    if (!_imgParr) {
//        _imgParr =@[@"shouye",@"faxian",@"xiaoxi",@"wode"];
//    }
//    return _imgParr;
//}
//- (void)playVoice{
//    NSURL *soundUrl = [[NSBundle mainBundle] URLForResource:@"messageVioce" withExtension:@"mp3"];
//    SystemSoundID soundID;
//    AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundUrl,&soundID);
//    AudioServicesPlaySystemSound(soundID);
//}
@end
