//
//  MyViewController.m
//  gaotingshan
//
//  Created by MacBook Dq01 on 16/3/16.
//  Copyright © 2016年 Mac Book DQ02. All rights reserved.
//  

#import "MyViewController.h"
#import "UIViewController+MMDrawerController.h"
#import "MMDrawerBarButtonItem.h"
#import "LoginViewController.h"
#import "Singleton.h"
#import "CompeteDetailVC.h"
#import "CompeteScoreVC.h"
#import "DeviceIntroducedVC.h"
#import "managementDeviceVC.h"
#import "BindingDeviceVC.h"
#import "SmartWatchesViC.h"
#import "ManagementSmartWatchesVC.h"
#import "HearStepVC.h"
#import "MyCompeteScheduleVC.h"
#import "CustomNavViewController.h"


@interface MyViewController () <UIViewControllerTransitioningDelegate, UIWebViewDelegate> {
    //定义单例，用于传值
    Singleton *singleton;
}


@property (nonatomic, strong) UIWebView *noLoginWebView;
@property (nonatomic, strong) UIWebView *didLoginWebView;

@end


@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //创建单例，存储登录成功后的“status”值。
    singleton = [Singleton defaultSingleton];
//    NSLog(@"+++++++++%@", singleton.string);
    
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav_bg"] forBarMetrics:(UIBarMetricsDefault)];
//   
//    //改变字体颜色
//    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
//    textAttrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
//    self.navigationController.navigationBar.titleTextAttributes = textAttrs;
    
    [Manager setNavi:self.navigationController.navigationBar];
    
     self.navigationItem.title = @"我的";
#pragma - 设置导航栏左边的按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"menu"] landscapeImagePhone:nil style:UIBarButtonItemStylePlain target:self action:@selector(leftBntIsClick)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];

#pragma 设置导航栏右边的按钮。

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"setting"] landscapeImagePhone:nil style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnIsClick)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
    //加载webview
    _webView =[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height   - 60)];
    [_webView setUserInteractionEnabled:YES];
    _webView.delegate = self;
    [_webView setOpaque:NO]; //设置是否透明。
    [_webView setScalesPageToFit:YES]; //自动缩放以适应屏幕。
    //   _didLoginWebView.scrollView.bounces = NO;
    _webView.scrollView.showsVerticalScrollIndicator = NO;

    if ([singleton.string isEqualToString:@"9002"]) {
        
        //根据接口url，webview加载页面
        //加载网页
        [self loadDidLoginWebview];

    } else {
        //加载未登录时的webView
        [self loadNoLoginWebview];
    }
    
    UIScrollView *scrollView = _webView.scrollView;
    // 添加下拉刷新控件
    scrollView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if ([singleton.string isEqualToString:@"9002"]) {

            [self loadDidLoginWebview];

        }
        else
        {
            [self loadNoLoginWebview];

        }
        
    }];
    //changeMyVCLogOut，接受左视图退出按钮的通知
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reductionMyVCLayout:) name:@"changeMyVCLogOut" object:nil];
    
    //添加观察者，接收通知（来自于UserInfoVC页面）
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reLoadWebView:) name:@"ToAssignValueAndReLoadWebView" object:nil];
    //添加观察者， 接收通知（来自BindingDeviceVC,managementDeviceVC页面）
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reLoadWebView:) name:@"reLoadMyVCWebView" object:nil];
    
   // changeMyVCToCompete 20160521
    //添加通知，接收通知，我的页面未登录点击申请，登录成功后，我的页面跳至申请页面
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reLoadWebViewToCompete) name:@"changeMyVCToCompete" object:nil];
}


-(void)loadDidLoginWebview
{
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/terminal/memberindex?sesskey=%@",localRequestUrl, singleton.sesskey]];
    [_webView loadRequest:[NSURLRequest requestWithURL:url]];
    
    [self.view addSubview:_webView];
}

-(void)loadNoLoginWebview
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/terminal/startevent",localRequestUrl]];
    [_webView loadRequest:[NSURLRequest requestWithURL:url]];
    
    [self.view addSubview:_webView];
}


#pragma mark - webViewDelegate
- (void)webViewDidFinishLoad:(nonnull UIWebView *)webView
{
    [self.webView.scrollView.mj_header endRefreshing];
    
}




#pragma mark - 我的页面，头像点击触发（实际中我的页面中titleBtn是不可以点击的）
-(void)btnIsClick:(NSString *)str
{
    [self dismissViewControllerAnimated:NO completion:^{
        
    }];
}

#pragma mark - 导航栏左侧按钮点击触发方法
- (void)leftBntIsClick {
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:^(BOOL finished) {
    }];
}

#pragma mark - 导航栏右侧按钮点击触发方法
- (void)rightBtnIsClick {
    if (![singleton.string isEqualToString:@"9002"]) {
        // 跳转到登录页面
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:loginVC];
        [self presentViewController:naVC animated:YES completion:nil];

    } else {
        //用户登录，跳转到用户基本信息
        UserInfoVC *userInforVC = [[UserInfoVC alloc] init];
        UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:userInforVC];
        [self presentViewController:naVC animated:NO completion:nil];
        
    }
}


- (void)reductionMyVCLayout:(id)sender {
    [self loadNoLoginWebview];
}

- (void)reLoadWebView:(id)sender {
    //加载网页
    [self loadDidLoginWebview];
}

//20160521 xmz修改
-(void)reLoadWebViewToCompete
{
    //跳到赛事详情页面，webview重新刷新
    CompeteDetailVC *comDetailVC = [[CompeteDetailVC alloc] init];
    comDetailVC.urlStr = _eventID;
    UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:comDetailVC];
   
    [self presentViewController:naVC animated:YES completion:nil];

}

#pragma mark - UIWebViewDelegate methods
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    NSLog(@"页面url＝%@",request.URL.absoluteString);
    
    if ([request.URL.absoluteString containsString:@"terminal/toapply"]) {
         NSArray *ary = [request.URL.absoluteString componentsSeparatedByString:@"="];
       _eventID = ary[1];
        Singleton *single = [Singleton defaultSingleton];
        single.eventId = _eventID;
        NSLog(@"eventid = %@",_eventID);
    }
 //   NSLog(@"我的页面:%@", request.URL.absoluteString);
    if ([[request.URL absoluteString] containsString:@"/terminal/startevent_login"]) {
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:loginVC];
        [self presentViewController:naVC animated:YES completion:nil];
        return NO;
    } else if ([request.URL.absoluteString containsString:@"terminal/error?err="]) {
        //想办法拿到赛事id
               LoginViewController *loginVC = [[LoginViewController alloc] init];
        //20160521 xmz 修改,未登录点击申请赛事，用于登录后，直接跳回申请赛事页面
        loginVC.skipFrom = @"FromMyOutApply";
        
        UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:loginVC];
        [self presentViewController:naVC animated:YES completion:nil];
        return NO;
        
    } else if ([[request.URL absoluteString] containsString:@"/terminal/loginout"]) {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"退出" message:@"你确定要退出吗？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *ensure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/terminal/startevent",localRequestUrl]];
            [_webView loadRequest:[NSURLRequest requestWithURL:url]];
            [self.view addSubview:_webView];
            //发送通知给(LeftDrawerVC)页面
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeLeftDrawerVCUILayout" object:nil];
            MapInfo *info = [MapInfo shareMapInfo];
            if (info.internetStatus == AFNetworkReachabilityStatusNotReachable) {
                return;
            }
            singleton.string = nil;
            singleton.sesskey = nil;
            singleton.reallyName = nil;
            singleton.JSESSIONIDValue = nil;
            singleton.userid = nil;
            singleton.status = nil;
            singleton.deviceSn = nil;
            singleton.watchSn = nil;
            
            //20160521 xmz 修改
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setObject:nil forKey:@"userName"];
            [defaults setObject:nil forKey:@"userPwd"];
        }];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertController addAction:ensure];
        [alertController addAction:cancel];
        [self presentViewController:alertController animated:YES completion:nil];
        
        return NO;
    } else if ([[request.URL absoluteString] containsString:@"terminal/adddevice"]) {
        //用户没有绑定登山卡，跳转到“绑定登山设备”页面。
        BindingDeviceVC *bindDVC = [[BindingDeviceVC alloc] init];
        UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:bindDVC];
        [self presentViewController:naVC animated:NO completion:nil];
        
        return NO;
    } else if ([request.URL.absoluteString containsString:@"/addBracelet"]) {
        //跳到绑定智能手表页面
        SmartWatchesViC *smartVc = [[SmartWatchesViC alloc] init];
        UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:smartVc];
        [self presentViewController:navc animated:NO completion:nil];
        
        return NO;
        
    } else if ([request.URL.absoluteString containsString:@"/myBracelet"]) {
        //跳到管理我的智能手表页面
        ManagementSmartWatchesVC *magVc = [[ManagementSmartWatchesVC alloc] init];
        UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:magVc];
        [self presentViewController:navc animated:NO completion:nil];
        
        return NO;
    } else if ([request.URL.absoluteString containsString:@"mydevice?sesskey"]) {
        //用户绑定了登山卡，跳转到“管理我的登山设备”页面
        managementDeviceVC *mangDVC = [[managementDeviceVC alloc] init];
        UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:mangDVC];
        [self presentViewController:naVC animated:YES completion:nil];
        
        return NO;
    }
    else if ([[request.URL absoluteString] containsString:@"terminal/myindexevent"]) {
        //跳转到“我的赛事安排”页面。
        MyCompeteScheduleVC *comSchVC= [[MyCompeteScheduleVC alloc]init];
        UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:comSchVC];
        [self presentViewController:naVC animated:YES completion:nil];
        
        return NO;
    } else if ([[request.URL absoluteString] containsString:@"event/event_info?eventId"]) {
        //跳转到“竞赛详情”页面
        CompeteDetailVC *comDetailVC = [[CompeteDetailVC alloc] init];
        UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:comDetailVC];
        NSArray *ary = [request.URL.absoluteString componentsSeparatedByString:@"="];
//        NSRange range = {request.URL.absoluteString.length - 11, 11};//第一个数代表起始位置, 第二个数代表长度
//        NSString *str = [request.URL.absoluteString substringWithRange:range];
        NSLog(@"%@", ary[1]);
        comDetailVC.urlStr = ary[1];
        [self presentViewController:naVC animated:YES completion:nil];
        
        return NO;
    } else if ([[request.URL absoluteString] containsString:@"eventscore"]) {
        //跳转到“赛事成绩”页面
        CompeteScoreVC *comScoreVC = [[CompeteScoreVC alloc] init];
        UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:comScoreVC];
        [self presentViewController:naVC animated:NO completion:nil];
        return NO;
    } else if ([[request.URL absoluteString] containsString:@"/terminal/deviceshow"]) {
        //跳转到“登山设备介绍”页面
        DeviceIntroducedVC *deviceIntroVc = [[DeviceIntroducedVC alloc] init];
        UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:deviceIntroVc];
        [self presentViewController:naVC animated:YES completion:nil];
        
        return NO;
    } else if ([request.URL.absoluteString containsString:@"/terminal/bracelet_report"]) {
        //心率计步
        if (![singleton.watchSn isEqualToString:@""]) {
            HearStepVC *hearVc = [[HearStepVC alloc] init];
            CustomNavViewController *nav = [[CustomNavViewController alloc] initWithRootViewController:hearVc];
            [self presentViewController:nav animated:YES completion:nil];
        }else{
            [FileDownloadTool alert:@"对不起，您还未绑定手表" view:self.view];
        }
        
        return NO;
    }else if ([request.URL.absoluteString containsString:@"member/area_favorite_list?sesskey="]){
        //景点收藏，新开页面跳转到收藏列表页面
        AttractionCollectionListVC *hearVc = [[AttractionCollectionListVC alloc] init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:hearVc];
        [self presentViewController:nav animated:YES completion:nil];
        NSLog(@"111");
        return NO;
    }
    
    return YES;
}



#pragma mark webView加载错误执行的函数
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    MapInfo *info = [MapInfo shareMapInfo];
    if (info.internetStatus == AFNetworkReachabilityStatusNotReachable) {
         [FileDownloadTool alert:@"网络错误或链接超时" view:self.webView];
    }
   
    [self.webView.scrollView.mj_header endRefreshing];
}

-(void)viewWillAppear:(BOOL)animated
{
    if ([singleton.string isEqualToString:@"9002"]) {
        
        //根据接口url，webview加载页面
        //加载网页
        [self loadDidLoginWebview];
        
    } else {
        //加载未登录时的webView
        [self loadNoLoginWebview];
    }

}


-(void)dealloc
{
     [[NSNotificationCenter defaultCenter]removeObserver:self name:@"changeMyVCLogOut" object:nil];
       [[NSNotificationCenter defaultCenter]removeObserver:self name:@"ToAssignValueAndReLoadWebView" object:nil];
       [[NSNotificationCenter defaultCenter]removeObserver:self name:@"reLoadMyVCWebView" object:nil];
       [[NSNotificationCenter defaultCenter]removeObserver:self name:@"changeMyVCToCompete" object:nil];
}

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

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
