//
//  MainTabBarViewController.m
//  TianLing_App
//
//  Created by 刘荣毅 on 2017/10/20.
//  Copyright © 2017年 Liu. All rights reserved.
//

#import "MainTabBarViewController.h"
#import "WorkbenchTableViewController.h"
#import "ContactsViewController.h"
#import "MessageViewController.h"
#import "MineViewController.h"

#import "KSNavigationController.h"
#import "UIColor+KSString.h"

#import "ConversationListController.h"
#import "JX_NewLoginViewController.h"

@interface MainTabBarViewController ()
/// 每一小时登录一次
@property (nonatomic, strong) dispatch_source_t updateTokenTimer;

@end

@implementation MainTabBarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setUpAllChildViewController];
    
    [self updateLoginTime];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    // 登录成功就启动计时
    if (self.isAutoLogin) {
        [self updateLoginTime];
    }
}


- (void)updateLoginTime {
    if (self.updateTokenTimer == nil) {
        NSTimeInterval time = 60 * 60;
        self.updateTokenTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
        dispatch_source_set_timer(self.updateTokenTimer, DISPATCH_TIME_NOW, time * NSEC_PER_SEC, 0);
        dispatch_source_set_event_handler(self.updateTokenTimer, ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [self updateLogin];
            });
        });
        dispatch_resume(self.updateTokenTimer);
    }
}

#pragma mark tabbar视图控制
-(void)setUpAllChildViewController{
    
    self.view.backgroundColor = [UIColor whiteColor];
    //TabBar_OrganizationChart_Selected
    
    // TODO: 待办  -------->>>>
    //    MessageViewController *home = [[MessageViewController alloc]init];
    ConversationListController *home = [[ConversationListController alloc]init];
    // TODO: 待办  -------->>>>
    UIImage *homeA = [UIImage imageNamed:@"xiaoxi-no"];
    UIImage *homeB = [UIImage imageNamed:@"xiaoxi-yes"];
    [self setUpOneChildViewController:home imageBefore:homeA imageAfter:homeB title:@"消息"];
    
    
    ContactsViewController  *Classify = [[ContactsViewController alloc]init];
    UIImage *ClassifyA = [UIImage imageNamed:@"tongxunlu-no"];
    UIImage *ClassifyB = [UIImage imageNamed:@"tongxunlu-yes"];
    [self setUpOneChildViewController:Classify imageBefore:ClassifyA imageAfter:ClassifyB title:@"通讯录"];
    
    WorkbenchTableViewController *shopping = [[WorkbenchTableViewController alloc]init];
    UIImage *shoppingA = [UIImage imageNamed:@"gongzuotai-no"];
    UIImage *shoppingB = [UIImage imageNamed:@"gongzuotai-yes"];
    [self setUpOneChildViewController:shopping imageBefore:shoppingA imageAfter:shoppingB title:@"工作台"];
    

    
    MineViewController *myCenter = [[MineViewController alloc]init];
    UIImage *myCenterA = [UIImage imageNamed:@"wode-no"];
    UIImage *myCenterB = [UIImage imageNamed:@"wode-yes"];
    [self setUpOneChildViewController:myCenter imageBefore:myCenterA imageAfter:myCenterB title:@"我的"];
}




#pragma mark tabbar item方法
- (void)setUpOneChildViewController:(UIViewController *)viewController imageBefore:(UIImage *)imageBefore imageAfter:(UIImage *)imageAfter title:(NSString *)title {
    
    [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithHexString:@"#4284F4"]];//Nav颜色
    //    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"navBG"] forBarMetrics:UIBarMetricsDefault];//加背景图片
    
    [[UINavigationBar appearance] setTintColor:[UIColor colorWithHexString:@"#333333"]];//按钮颜色
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName :[UIColor colorWithHexString:@"#FFFFFF"],NSFontAttributeName:[UIFont systemFontOfSize:18]}];//title颜色
    KSNavigationController *navC = [[KSNavigationController alloc]initWithRootViewController:viewController];
    imageBefore = [imageBefore imageWithRenderingMode:UIImageRenderingModeAutomatic];
    imageAfter = [imageAfter imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    navC.tabBarItem = [[UITabBarItem alloc]initWithTitle:title image:imageBefore selectedImage:imageAfter];
//    navC.tabBarItem.imageInsets = UIEdgeInsetsMake(-2,-2,0,-2); //改变图片大小
    [navC.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#4284F4"]} forState:UIControlStateSelected];//bar字体颜色
    
    [self addChildViewController:navC];
}

- (void)setIsAutoLogin:(BOOL)isAutoLogin {
    if (_isAutoLogin != isAutoLogin) {
        _isAutoLogin = isAutoLogin;
        // 自动登录
        if (self.isAutoLogin) {
            [self autoLogin];
        }
    }
}

#pragma mark- 自动登录
- (void)autoLogin{
    [HUDManager showMBProgressHUDModeIndeterminate:nil TopView:self.view];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    // 发送请求
    parameters[@"domainName"] = [[NSUserDefaults standardUserDefaults] objectForKey:@"domainName"] ;
    parameters[@"username"] =  [[NSUserDefaults standardUserDefaults] objectForKey:@"account"];
    
    NSData *data = [[[NSUserDefaults standardUserDefaults] objectForKey:@"password"] dataUsingEncoding:NSUTF8StringEncoding];
    NSString *base64String = [data base64EncodedStringWithOptions:0];
    parameters[@"password"] = base64String;
    
//    DLog(@"请求体 === %@",parameters);
    [HttpClient sendPostWithURL:USERLOGIN_URL parameter:parameters success:^(id JSON) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:JSON options:0 error:nil];
//        DLog(@"提交 === %@",dict);
        [HUDManager hideHUD];
        if ([dict[@"status"] integerValue] == 0) {
            
            //存储用户数据
            [[NSUserDefaults standardUserDefaults]  setObject:dict[@"data"][@"avatar"] forKey:@"avatar"];
            [[NSUserDefaults standardUserDefaults]  setObject:dict[@"data"][@"username"] forKey:@"username"];
            [[NSUserDefaults standardUserDefaults]  setObject:dict[@"data"][@"userId"] forKey:@"userId"];
            [[NSUserDefaults standardUserDefaults]  setObject:dict[@"data"][@"access_token"] forKey:@"access_token"];
            
            //数据持久化
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            
            
        }
        else{
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userId"];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"access_token"];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"account"];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"password"];
            
            [Tools showAlertViewWithTitle:nil content:@"您的登录信息已失效"];
            
            JX_NewLoginViewController *loginVC = [[JX_NewLoginViewController alloc]init];
            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:loginVC];
            UIWindow * window = [[UIApplication sharedApplication] keyWindow];
            window.rootViewController = nav;
            
        }
        
    } failure:^(NSError *error) {
        [HUDManager hideHUD];
    }];
}

- (void)updateLogin{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    // 发送请求
    parameters[@"domainName"] = [[NSUserDefaults standardUserDefaults] objectForKey:@"domainName"] ;
    parameters[@"username"] =  [[NSUserDefaults standardUserDefaults] objectForKey:@"account"];
    
    NSData *data = [[[NSUserDefaults standardUserDefaults] objectForKey:@"password"] dataUsingEncoding:NSUTF8StringEncoding];
    NSString *base64String = [data base64EncodedStringWithOptions:0];
    parameters[@"password"] = base64String;
    
//    DLog(@"请求体 === %@",parameters);
    [HttpClient sendPostWithURL:USERLOGIN_URL parameter:parameters success:^(id JSON) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:JSON options:0 error:nil];
//        DLog(@"提交 === %@",dict);
        if ([dict[@"status"] integerValue] == 0) {
            
            //存储用户数据
            [[NSUserDefaults standardUserDefaults]  setObject:dict[@"data"][@"avatar"] forKey:@"avatar"];
            [[NSUserDefaults standardUserDefaults]  setObject:dict[@"data"][@"username"] forKey:@"username"];
            [[NSUserDefaults standardUserDefaults]  setObject:dict[@"data"][@"userId"] forKey:@"userId"];
            [[NSUserDefaults standardUserDefaults]  setObject:dict[@"data"][@"access_token"] forKey:@"access_token"];
            
            //数据持久化
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            
            
        }
        else{
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userId"];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"access_token"];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"account"];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"password"];
            
            [Tools showAlertViewWithTitle:nil content:@"您的登录信息已失效"];
            
            JX_NewLoginViewController *loginVC = [[JX_NewLoginViewController alloc]init];
            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:loginVC];
            UIWindow * window = [[UIApplication sharedApplication] keyWindow];
            window.rootViewController = nav;
            
        }
        
    } failure:^(NSError *error) {
        
    }];
}

@end
