//
//  TabBarViewController.m
//  Macalline
//
//  Created by JianjiYuan on 14-12-1.
//  Copyright (c) 2014年 JianjiYuan. All rights reserved.
//

#import "SATabBarViewController.h"
#import "RDVTabBarItem.h"
#import "TaskListViewController.h"
#import "NoticeListViewController.h"
#import "SettingViewController.h"
#import "BRNetworkMgr.h"
#import "GexinPushMgr.h"
#import "SANewHomeViewController.h"
#import "GoodExampleViewController.h"

@interface SATabBarViewController () < BRNetworkMgrDelegate, RDVTabBarControllerDelegate, UITabBarControllerDelegate
, GexinPushMgrDelegate >
{
    SANewHomeViewController* vcHome;
    GoodExampleViewController *vcTask;
    NoticeListViewController *vcNotice;
    SettingViewController *vcSetting;
    BOOL hasAddObserver;
}

@property (nonatomic, strong) BRNetworkMgr *networkMgr;

@end

@implementation SATabBarViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        hasAddObserver = NO;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [GexinPushMgr getInstance].delegate = self;
    
    vcHome = [[SANewHomeViewController alloc] init];
    BaseNavigationController *navhomew = [[BaseNavigationController alloc]
                                          initWithRootViewController:vcHome];
    
    
//    vcTask = [[GoodExampleViewController alloc] init];
//    BaseNavigationController *navTask = [[BaseNavigationController alloc]
//                                         initWithRootViewController:vcTask];
    
    vcNotice = [[NoticeListViewController alloc] init];
    BaseNavigationController *navNotice = [[BaseNavigationController alloc]
                                           initWithRootViewController:vcNotice];
    
    vcSetting = [[SettingViewController alloc] init];
    BaseNavigationController *navSetting = [[BaseNavigationController alloc]
                                            initWithRootViewController:vcSetting];
    
    self.viewControllers = @[navhomew,navNotice, navSetting];
    
    [self customizeTabBarForController:self];
    self.delegate = self;
    self.hidesBottomBarWhenPushed = YES;
    
    [self queryInitCount];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (!hasAddObserver) {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(gexinPushMgrPayloadDidRecieved:)
                                                     name:kGexinPushMgrPayloadRecieved
                                                   object:nil];
        
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(queryInitCount)
                                                     name:kShouldReQueryCountInit
                                                   object:nil];
        
        hasAddObserver = YES;
    }
    
    NSString *payloadMsg = [UIApplication getObjectType:String key:kLocalNotifyRecievedContent];
    NSDictionary *dictPayload = [NSJSONSerialization JSONObjectWithData:[payloadMsg dataUsingEncoding:NSUTF8StringEncoding]
                                                                options:NSJSONReadingAllowFragments
                                                                  error:nil];
    if (dictPayload.count > 0) {
        [self dealGexinPushMgrPayload:dictPayload];
    }
    
}

- (void)gexinPushMgrPayloadDidRecieved:(NSNotification *)notifyPayload
{
    DLog(@"notifyPayload  %@", notifyPayload);
    if (![notifyPayload isKindOfClass:[NSNotification class]]) {
        return;
    }
    NSDictionary *payload = notifyPayload.object;
    
    [self dealGexinPushMgrPayload:payload];
    
}

- (void)dealGexinPushMgrPayload:(NSDictionary *)payload
{
    DLog(@"payload  %@", payload);
    if (![payload isKindOfClass:[NSDictionary class]]) {
        return;
    }
    NSString* str = [NSString stringWithFormat:@"%@",payload[@"type"]];
    if ([str isEqualToString:@"1"]) {
        
        if (self.selectedIndex != 1 && self.navigationController.viewControllers.count < 4) {
            self.selectedIndex = 1;
            [self.navigationController popToViewController:self animated:YES];
        }
        
    }else if ([str isEqualToString:@"2"]) {
        
        if (self.selectedIndex != 0 && self.navigationController.viewControllers.count < 4) {
            self.selectedIndex = 0;
            [self.navigationController popToViewController:self animated:YES];
        }
        
    }
    
    [UIApplication saveObject:@"" type:String key:kLocalNotifyRecievedContent];

}

- (void)queryInitCount
{
    NSString *interface = @"queryInitCountEX";
    AFHTTPRequestOperation *operation = [self.networkMgr operationWithURL:kBaseEXURL(interface)
                                                                interface:interface
                                                                   params:nil
                                                                 dataType:BRNetMgrDataTypeJSON
                                                                   method:BRNetMgrMethodPost];
    [self.networkMgr startOperation:operation];
}

- (void)customizeTabBarForController:(RDVTabBarController *)tabBarController
{
    UIImage *finishedImage = nil;
    UIImage *unfinishedImage = nil;
//    NSArray *tabBarItemImages = @[@"TabBar/icon_home_",@"TabBar/icon_notice_",@"TabBar/icon_task_",  @"TabBar/icon_setting_"];
    NSArray *tabBarItemImages = @[@"TabBar/icon_home_",@"TabBar/icon_task_",  @"TabBar/icon_setting_"];
    NSInteger index = 0;
    for (RDVTabBarItem *item in [[tabBarController tabBar] items]) {
        [item setBackgroundSelectedImage:finishedImage withUnselectedImage:unfinishedImage];
        UIImage *selectedimage = [UIImage imageNamed:[NSString stringWithFormat:@"%@pre.png",
                                                      [tabBarItemImages objectAtIndex:index]]];
        UIImage *unselectedimage = [UIImage imageNamed:[NSString stringWithFormat:@"%@nor.png",
                                                        [tabBarItemImages objectAtIndex:index]]];
        [item setBackgroundSelectedImage:selectedimage withUnselectedImage:unselectedimage];
        item.badgeBackgroundColor = RGBColor(229, 0, 129, 1);
        item.titlePositionAdjustment = UIOffsetMake(0, 15);
        item.badgePositionAdjustment = UIOffsetMake(20, 0);
        
        item.unselectedTitleAttributes = @{
                                           UITextAttributeFont: [UIFont systemFontOfSize:14],
                                           UITextAttributeTextColor: RGBColor(177, 177, 177, 1)
                                           };
        item.selectedTitleAttributes = @{
                                         UITextAttributeFont: [UIFont systemFontOfSize:14],
                                         UITextAttributeTextColor: RGBColor(0, 120, 193, 1)
                                         };
        item.backgroundColor = RGBColor(253, 253, 253, 1);
        index++;
    }
    
    [tabBarController tabBar].layer.borderColor = [UIColor lightGrayColor].CGColor;
    [tabBarController tabBar].layer.borderWidth = 0.5;
    
}

/*
 - (void)customizeTabBarForController:(UITabBarController *)tabBarController
 {
 NSArray *tabBarItemImages = @[@"TabBar/icon_task_", @"TabBar/icon_notice_", @"TabBar/icon_setting_"];
 tabBarController.tabBar.backgroundColor = RGBColor(253, 253, 253, 1);
 
 NSInteger index = 0;
 
 for (UITabBarItem *item in tabBarController.tabBar.items) {
 UIImage *selectedimage = [UIImage imageNamed:[NSString stringWithFormat:@"%@pre.png",
 [tabBarItemImages objectAtIndex:index]]];
 UIImage *unselectedimage = [UIImage imageNamed:[NSString stringWithFormat:@"%@nor.png",
 [tabBarItemImages objectAtIndex:index]]];
 [item setFinishedSelectedImage:selectedimage withFinishedUnselectedImage:unselectedimage];
 
 item.imageInsets = UIEdgeInsetsMake(5, 0, 0, 0);
 item.titlePositionAdjustment = UIOffsetMake(0, 15);
 index++;
 
 }
 
 }
 
 */

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

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

#pragma mark =============  GexinPushMgr Delegate  =============
- (void)didTapOnNotificationWithPayload:(NSDictionary *)payload
{
    DLog(@"payload  %@", payload);
    if (![payload isKindOfClass:[NSDictionary class]]) {
        return;
    }
    NSString* str = [NSString stringWithFormat:@"%@",payload[@"type"]];
    if ([str isEqualToString:@"1"]) {
        
        self.selectedIndex = 1;
        if (self.navigationController.viewControllers.count > 3) {
            [self.navigationController popToViewController:self animated:YES];
        }
        
    }else if ([str isEqualToString:@"2"]) {
        
        self.selectedIndex = 0;
        if (self.navigationController.viewControllers.count > 3) {
            [self.navigationController popToViewController:self animated:YES];
        }
        
    }
    
    [UIApplication saveObject:@"" type:String key:kLocalNotifyRecievedContent];
    
//    [self queryInitCount];
    
}

#pragma mark =============  BRNetworkMgr Delegate  =============
- (void)httpOperationSuccess:(AFHTTPRequestOperation *)operation
                      result:(NSDictionary *)result
{
    if ([operation.userInfo[@"interface"] isEqualToString:@"queryInitCountEX"]) {
        
//        vcTask.arrItemTitles = [NSMutableArray arrayWithArray:
//                                @[[NSString stringWithFormat:@"未完成(%@)", result[@"unFinishedTaskCount"]],
//                                  [NSString stringWithFormat:@"已完成(%@)", result[@"finishedTaskCount"]]]];
//        [vcTask reloadItemTitles];
        vcHome.finishedTaskCount = result[@"finishedTaskCount"];
        vcHome.unFinishedTaskCount = result[@"unFinishedTaskCount"];
        vcHome.dayCount = result[@"days"];
        vcHome.progress = [NSString stringWithFormat:@"%@",result[@"progress"]];
        
        [DataMgr getInstance].dayCount = result[@"days"];
        [DataMgr getInstance].unfinishedTaskCountToDacuxiao = result[@"dacuxiaoUndoneNum"];
        [DataMgr getInstance].unfinishedTaskCountToXiaocuxiao = result[@"xiaocuxiaoUndoneNum"];
        [DataMgr getInstance].unfinishedTaskCountToDaoshi = result[@"daoshiUndoneNum"];
        [DataMgr getInstance].unfinishedTaskCountToMeicheng = result[@"meichenUndoneNum"];
        [DataMgr getInstance].unfinishedTaskCountToXiuxiqu = result[@"xiuxiquUndoneNum"];
        [DataMgr getInstance].unfinishedTaskCountToGuanggaowei = result[@"guanggaoweiUndoneNum"];
        [DataMgr getInstance].unfinishedTaskCountToBeijingyinyue = result[@"beijingyinyueUndoneNum"];
        [DataMgr getInstance].unfinishedTaskCountToYingyunwuliao = result[@"yingyunwuliaoUndoneNum"];
        
        [DataMgr getInstance].serverTime = result[@"serverTime"];
        NSNotification *notification =[NSNotification notificationWithName:@"reloadNumber" object:nil userInfo:nil];
        //通过通知中心发送通知
        [[NSNotificationCenter defaultCenter] postNotification:notification];
        
        UITabBarItem *itemNotice = [self.tabBar.items objectAtIndex:1];
        int unReadNoticeCount = [result[@"unReadNoticeCount"] intValue];
        if (unReadNoticeCount == 0) {
            [itemNotice setBadgeValue:nil];
        }else {
            [itemNotice setBadgeValue:@" "];
        }
        
//        UITabBarItem *itemSetting = [self.tabBar.items objectAtIndex:3];
//        if ([[DataMgr getInstance].hasNewVersion isEqualToString:@"YES"]) {
//            [itemSetting setBadgeValue:@" "];
//        }
//        else
//        {
//            [itemSetting setBadgeValue:nil];
//        }
    }
    
}

- (void)httpOperationFailed:(AFHTTPRequestOperation *)operation
                      error:(NSError *)error
{
    
}

#pragma mark =============  Properties Lazy Load  =============

- (BRNetworkMgr *)networkMgr
{
    if (!_networkMgr) {
        self.networkMgr = [BRNetworkMgr getInstance];
        _networkMgr.delegate = self;
    }
    return _networkMgr;
}

@end
