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

#import "RootViewController.h"
#import <NSString+MD5.h>
#import "GexinPushMgr.h"
#import "LoginViewController.h"
#import "TabBarViewController.h"
#import "SATabBarViewController.h"
#import "BATabBarViewController.h"

@interface RootViewController () < UIAlertViewDelegate >
{
    NSDictionary *dictUpdateInfo;
}

@end

@implementation RootViewController

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

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIImageView *imageVBg = [UIImageView newAutoLayoutView];
    if ([DataMgr isScreenIphone4Size]) {
        imageVBg.image = [UIImage imageNamed:@"LaunchImage.png"];
    }else {
        imageVBg.image = [UIImage imageNamed:@"LaunchImage-568h.png"];
    }
    
    [self.view addSubview:imageVBg];
    [imageVBg autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    
//    UIImageView *imageVLogo = [UIImageView newAutoLayoutView];
//    imageVLogo.image = [UIImage imageNamed:@"Login/logo_login.png"];
//    imageVLogo.autoresizingMask = UIViewAutoresizingNone;
//    [self.view addSubview:imageVLogo];
//    
//    [imageVLogo autoPinToTopLayoutGuideOfViewController:self withInset:60];
//    [imageVLogo autoSetDimensionsToSize:CGSizeMake(138, 64.5)];
//    [imageVLogo autoAlignAxisToSuperviewAxis:ALAxisVertical];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadUI) name:@"noNetwork" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(blendID) name:@"shouldBlendClientId" object:nil];
}
-(void)blendID
{
    [self bindClientId];
}
-(void)reloadUI
{
    bool value = NO;
    for (UIViewController *controller in self.navigationController.viewControllers) {
        if ([controller isKindOfClass:NSClassFromString(@"LoginViewController")]) {
            //[self.navigationController popToViewController:controller animated:YES];
            value = YES;
        }
    }
    if (value) {
        [UIApplication hideLoadingView];
    }else
    {
        LoginViewController *vcLogin = [[LoginViewController alloc] initWithNibName:nil bundle:nil];
        [self.navigationController pushViewController:vcLogin animated:YES];
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
    //检查版本更新
    [self checkAppUpdate];
    
//    [self checkApplicationIsAutoLogin];
}

- (void)checkAppUpdate
{
    NSString *interface = @"checkAppUpdateEX";
    NSString *curVersion = [[NSBundle mainBundle] infoDictionary][@"CFBundleVersion"];
    NSDictionary *dicParam = @{@"versionCode":curVersion, @"platform":@"2"};//1. android 2. ios
    AFHTTPRequestOperation *operation = [self.networkMgr operationWithURL:kBaseEXURL(interface)
                                                                interface:interface
                                                                   params:dicParam
                                                                 dataType:BRNetMgrDataTypeJSON
                                                                   method:BRNetMgrMethodPost];
    [operation setUserInfo:@{@"interface":interface, kDealExtraWhenErrorOcur:@YES}];
    [self.networkMgr startOperation:operation];
}

- (void)checkApplicationIsAutoLogin
{
    NSDictionary *dict = [UIApplication getObjectType:Dictionary key:kDictAutoLoginInfo];
    
    if ([[dict valueForKey:kAutoLogin] boolValue]) {
        [UIApplication showLoadingView:@"正在登录.."];
        
        NSString *interface = @"loginEX";
        NSDictionary *dicParam = @{@"username":[dict valueForKey:kUserName]?:@"",
                                   @"password":[dict valueForKey:kPasswordMD5]?:@""};
//        NSDictionary *dicParam = @{@"username":@"areaManager",//zongbuceshi,bigAreaManager,areaManager
//                                   @"password":[[NSString stringWithFormat:@"%@%@",@"zongbuceshi",@"111111"]  MD5Digest]};
        
        AFHTTPRequestOperation *operation = [self.networkMgr operationWithURL:kBaseEXURL(interface)
                                                                    interface:interface
                                                                       params:dicParam
                                                                     dataType:BRNetMgrDataTypeJSON
                                                                       method:BRNetMgrMethodPost];
        [operation setUserInfo:@{@"interface":interface, kDealExtraWhenErrorOcur:@YES}];
        [self.networkMgr startOperation:operation];
    }else {
        LoginViewController *vcLogin = [[LoginViewController alloc] initWithNibName:nil bundle:nil];
        [self.navigationController pushViewController:vcLogin animated:NO];
    }
    
}

- (void)bindClientId
{
    NSString *interface = @"bindClientIdEX";
    NSDictionary *dicParam = @{@"platform":@"2", @"clientId":[UIApplication getObjectType:String key:kClientIdOfApplication]};
    AFHTTPRequestOperation *operation = [self.networkMgr operationWithURL:kBaseEXURL(interface)
                                                interface:interface
                                                   params:dicParam
                                                 dataType:BRNetMgrDataTypeJSON
                                                   method:BRNetMgrMethodPost];
    [operation setUserInfo:@{@"interface":interface, kDealExtraWhenErrorOcur:@YES}];
    [self.networkMgr startOperation:operation];
}


#pragma mark =============  BRNetworkMgr Delegate  =============
- (void)httpOperationSuccess:(AFHTTPRequestOperation *)operation
                      result:(NSDictionary *)result
{
    if ([operation.userInfo[@"interface"] isEqualToString:@"loginEX"]) {
        
        LoginViewController *vcLogin = [[LoginViewController alloc] initWithNibName:nil bundle:nil];
        if (![result[@"resultCode"] isEqualToString:@"01"]) {
            [self.navigationController pushViewController:vcLogin animated:YES];
        }else {
            [self.navigationController pushViewController:vcLogin animated:NO];
            [self setCustomNavBar];
            [DataMgr getInstance].userID = result[@"userId"];
#warning 判断[DataMgr getInstance].remoteNotificationID跳转页面
            if ([result[@"roleCode"] isEqualToString:kDaqufuzerencode]) {
                [DataMgr getInstance].roleId = @"daqufuzeren";
                [DataMgr getInstance].bigAreaId = result[@"bigAreaId"];
                [DataMgr getInstance].bigAreaName = result[@"areaName"];
                
                BATabBarViewController*vcTabBar = [[BATabBarViewController alloc] initWithNibName:nil bundle:nil];
                [vcLogin.navigationController pushViewController:vcTabBar animated:YES];
            }else if([result[@"roleCode"] isEqualToString:kXiaoqufuzerencode])
            {
                [DataMgr getInstance].roleId = @"xiaoqufuzeren";
                [DataMgr getInstance].smallAreaId = result[@"smallAreaId"];
                [DataMgr getInstance].smallAreaName = result[@"smallAreaName"];
                SATabBarViewController*vcTabBar = [[SATabBarViewController alloc] initWithNibName:nil bundle:nil];
                [vcLogin.navigationController pushViewController:vcTabBar animated:YES];
            }
            else
            {
                [DataMgr getInstance].roleId = @"guanliyuan";
                [DataMgr getInstance].shopName = result[@"shopName"];
                TabBarViewController *vcTabBar = [[TabBarViewController alloc] initWithNibName:nil bundle:nil];
                [vcLogin.navigationController pushViewController:vcTabBar animated:YES];
            }
//            SATabBarViewController*vcTabBar = [[SATabBarViewController alloc] initWithNibName:nil bundle:nil];
//            TabBarViewController *vcTabBar = [[TabBarViewController alloc] initWithNibName:nil bundle:nil];
//            BATabBarViewController*vcTabBar = [[BATabBarViewController alloc] initWithNibName:nil bundle:nil];
            
//            [self bindClientId];
            // [EXT] 登录成功，才接受消息
            [[GexinPushMgr getInstance] applicationDidBecomeActive];

        }
        
    }else if ([operation.userInfo[@"interface"] isEqualToString:@"checkAppUpdateEX"]) {
        
        if (![result[@"resultCode"] isEqualToString:@"01"]) {
            
            if ([result[@"resultCode"] isEqualToString:@"05"]) {
                [UIApplication showAlertViewWithTitle:@"提示"
                                              message:@"版本信息出错，请联系系统管理员！"
                                             delegate:self
                                                  tag:200
                                    cancelButtonTitle:@"重试" otherButtonTitles:nil, nil];
            }else {
                [UIApplication showAlertViewWithTitle:@"提示"
                                              message:@"检查版本更新失败！"
                                             delegate:self
                                                  tag:200
                                    cancelButtonTitle:@"重试" otherButtonTitles:@"开始使用", nil];
            }
            
        }else {
            
            dictUpdateInfo = result[@"versionDetails"];
            if (dictUpdateInfo) {
                
                if ([dictUpdateInfo[@"type"] isEqualToString:@"1"]) {//强制更新
                    
                    [UIApplication showAlertViewWithTitle:@"提示"
                                                  message:dictUpdateInfo[@"updateLog"]
                                                 delegate:self
                                                      tag:101
                                        cancelButtonTitle:@"确认更新" otherButtonTitles:nil, nil];
                }else {
                    
                    [UIApplication showAlertViewWithTitle:@"提示"
                                                  message:dictUpdateInfo[@"updateLog"]
                                                 delegate:self
                                                      tag:100
                                        cancelButtonTitle:@"下次再说" otherButtonTitles:@"立即更新", nil];
                }
                
         
            }else {
                [self checkApplicationIsAutoLogin];
            }
        }

        
    }else if ([operation.userInfo[@"interface"] isEqualToString:@"bindClientIdEX"]) {
        if (![result[@"resultCode"] isEqualToString:@"01"]) {
            [self performSelector:@selector(bindClientId) withObject:nil afterDelay:3*60];
        }
    }
    
}

- (void)httpOperationFailed:(AFHTTPRequestOperation *)operation
                      error:(NSError *)error
{
    if ([operation.userInfo[@"interface"] isEqualToString:@"checkAppUpdateEX"]) {
        [UIApplication showAlertViewWithTitle:@"提示"
                                      message:@"检查版本更新失败！"
                                     delegate:self
                                          tag:200
                            cancelButtonTitle:@"重试" otherButtonTitles:@"开始使用", nil];
        
    }else if ([operation.userInfo[@"interface"] isEqualToString:@"login"]) {
        LoginViewController *vcLogin = [[LoginViewController alloc] initWithNibName:nil bundle:nil];
        [self.navigationController pushViewController:vcLogin animated:YES];
        
    }else if ([operation.userInfo[@"interface"] isEqualToString:@"bindClientIdEX"]) {
        [self performSelector:@selector(bindClientId) withObject:nil afterDelay:3*60];
    }
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 100) {
        if (buttonIndex == 0) {
            if ([dictUpdateInfo[@"type"] isEqualToString:@"1"]) {
                [UIApplication showToastViewMessage:@"本次更新为强制更新，应用程序即将退出"];
                [self performSelector:@selector(exitApplication) withObject:nil afterDelay:1.5];
            }else {
                [DataMgr getInstance].hasNewVersion = @"YES";
                [self checkApplicationIsAutoLogin];
            }
        }else {
            [self performSelector:@selector(exitApplication) withObject:nil afterDelay:1.5];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[dictUpdateInfo[@"appURL"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
            
        }
    }else if (alertView.tag == 200) {
        if (buttonIndex == 0) {
            [self checkAppUpdate];
        }else {
            LoginViewController *vcLogin = [[LoginViewController alloc] initWithNibName:nil bundle:nil];
            [self.navigationController pushViewController:vcLogin animated:YES];
        }
    }else if (alertView.tag == 101) {
        [self performSelector:@selector(exitApplication) withObject:nil afterDelay:1.5];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[dictUpdateInfo[@"appURL"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    }
}

- (void)exitApplication
{
    exit(0);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)setCustomNavBar
{
#if kIOSVersion7Later
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
#endif
    [[UINavigationBar appearance] setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
                                                           [UIColor whiteColor], UITextAttributeTextColor,
                                                           [UIFont boldSystemFontOfSize:19], NSFontAttributeName, nil]];
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >=7.0) {
        [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"NavBar/nav_bar_128.png"]
                                           forBarMetrics:UIBarMetricsDefault];
    }else{
        [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"NavBar/nav_bar_88.png"]
                                           forBarMetrics:UIBarMetricsDefault];
    }
    
}
@end
