//
//  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 "WYTestQuestionViewController.h"
#import <Lottie/LOTAnimationView.h>

@interface WYTabBarController ()<UITabBarDelegate,UITabBarControllerDelegate>
{
    UIAlertController *alertupdate;
    UIAlertController *inputAlertController;
}
@property(nonatomic,strong)NSString *Build;
@property (nonatomic,strong) LOTAnimationView *animation;
@property (nonatomic,strong) NSArray *imgParr;
@property (nonatomic,assign) NSInteger  indexFlag;　　//记录上一次点击tabbar，使用时，记得先在init或viewDidLoad里 初始化 = 0

@end
@implementation WYTabBarController

#pragma mark ============定位=============
 -(NSArray *)imgParr
{
    if (!_imgParr) {
        _imgParr =@[@"shouyedata",@"kechengdata",@"kaoshidata",@"xiaoxidata",@"minedata"];
    }
    return _imgParr;
}



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

- (void)viewDidLoad {
    [super viewDidLoad];
    self.delegate = self;
    self.indexFlag = -9999;
    [self buildUpdate];
    [self.tabBar setBarTintColor:[UIColor whiteColor]];
    self.tabBar.translucent = NO;
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, 1)];
    line.backgroundColor = colorf0;
    [self.tabBar addSubview:line];
    //设置子视图
    [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)){
            NSLog(@"wifi-------");
        }
    }];
       
}

#pragma mark  在这里更换 左右tabbar的image
- (void)setUpAllChildVc {
    HomeViewController *home = [HomeViewController new];
    xiaoxiViewController *message = [xiaoxiViewController new];
    MineViewController *mine = [MineViewController new];
    MyCourseViewController *course  =[MyCourseViewController new];
    WYTestQuestionViewController *kaoshi = [WYTestQuestionViewController new];
    [self setUpOneChildVcWithVc:home Image:@"首页" selectedImage:@"首页_sel" title:@"首页" andTag:0];//首页_sel
    [self setUpOneChildVcWithVc:course Image:@"我的课程" selectedImage:@"我的课程_sel" title:@"我的课程" andTag:1];//我的课程_sel
    [self setUpOneChildVcWithVc:kaoshi Image:@"tab_kaoshi_nor" selectedImage:@"tab_kaoshi_sel" title:@"考试" andTag:2];//tab_kaoshi_sel
    [self setUpOneChildVcWithVc:message Image:@"消息" selectedImage:@"消息_sel" title:@"消息" andTag:3];//消息_sel
    [self setUpOneChildVcWithVc:mine Image:@"个人中心" selectedImage:@"个人中心_sel" title:@"个人中心" andTag:4];//个人中心_sel
}
#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:color96,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:^{
        
    }];
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
    UINavigationController *nav = (UINavigationController *)viewController;
    UIViewController *VC =nav.topViewController;
    if ([VC isKindOfClass:[HomeViewController class]]) {
        return YES;
    }else{
        return NO;
    }
    return NO;
    
}
//视图控制器实现的方法
- (BOOL)shouldAutorotate{
    return NO;
}

//-(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
