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

#import "HomePageViewController.h"
#import "IntroduceViewController.h"
#import "UIViewController+MMDrawerController.h"
#import "CompeteDetailVC.h"
#import "Singleton.h"
#import "MyCompeteScheduleVC.h"



@interface HomePageViewController () <UIWebViewDelegate> {
    Singleton *singleton;
}

@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong)  UIButton * leftBtn;


@end

@implementation HomePageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    singleton = [Singleton defaultSingleton];
    self.view = [[UIView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
      self.navigationItem.title = @"首页";
    
#pragma - 导航栏的渲染颜色为绿色。
//    [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];
    
    
#pragma - 设置导航栏左边的按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"menu"] landscapeImagePhone:nil style:UIBarButtonItemStylePlain target:self action:@selector(btnIsClicked)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
   
#pragma - 以下是对webView的一些处理。
    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 60)];
    [_webView setUserInteractionEnabled:YES];//是否支持交互
    
    [_webView setOpaque:NO]; //opaque是不透明的意思
    [_webView setScalesPageToFit:YES]; //自动缩放以适应屏幕
  //  _webView.scrollView.bounces = NO;
    _webView.scrollView.showsVerticalScrollIndicator = NO;
    
    _webView.delegate = self;
    [self.view addSubview:_webView];
    //加载网页的方式
    //1.创建并加载远程网页
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/terminal/index.html",localRequestUrl]];
    
    [_webView loadRequest:[NSURLRequest requestWithURL:url]];
    
    UIScrollView *scrollView = self.webView.scrollView;
    // 添加下拉刷新控件
    scrollView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSURL *url = [NSURL URLWithString:_currentUrl];
        
        [_webView loadRequest:[NSURLRequest requestWithURL:url]];
    }];
    
}



#pragma mark - 导航栏左侧button点击事件处理
-(void)btnIsClicked
{
    [_hud hide:YES];
    
    if([self.webView canGoBack])
        
        [self.webView goBack];
    else
        [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:^(BOOL finished) {
        }];
}



#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    
//[_hud hide:YES];
    
    //加蒙板
    if (![request.URL.absoluteString containsString:@"terminal/scenic/area_info/call_phone?phone="])
    {
        
        _hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        _hud.labelText = @"正在加载...";

    }
   
    NSLog(@"首页:%@", request.URL.absoluteString);
    if ([request.URL.absoluteString containsString:@"index.html"]) {
        [self.navigationItem.leftBarButtonItem setImage:[UIImage imageNamed:@"menu"]];
         self.navigationItem.title = @"首页";
        _currentUrl = request.URL.absoluteString;
    }

    if ([request.URL.absoluteString containsString:@"scenic/introduce_index"]) {
        //跳到“景区详情”页面
        [self.navigationItem.leftBarButtonItem setImage:[UIImage imageNamed:@"nav_back"]];
     
        self.navigationItem.title = @"景区详情";
        _currentUrl = request.URL.absoluteString;
    }
    
   if ([request.URL.absoluteString containsString:@"area_info?id="] && [request.URL.absoluteString containsString:@"imgUrl="])
    {

        //景点详情页
        NSString *encodingString = [request.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSArray *rootArr = [encodingString componentsSeparatedByString:@"id="];
        NSArray *foreArr= [[rootArr objectAtIndex:1] componentsSeparatedByString:@"&name="];
        NSString *areadId = [foreArr objectAtIndex:0];
        NSArray *secondA = [[foreArr objectAtIndex:1] componentsSeparatedByString:@"&imgUrl="];
        NSString *areaName = [secondA objectAtIndex:0];
        NSArray *thirdA = [[secondA objectAtIndex:1] componentsSeparatedByString:@"&keyword="];
        if (![[thirdA objectAtIndex:1] isEqualToString:@""]) {
            //表示有keyword
            NSString *keyword = [thirdA objectAtIndex:1];
            areaName = [NSString stringWithFormat:@"%@(%@)",areaName,keyword];
        }
        AttractionDetailController *at = [[AttractionDetailController alloc]init];
        at.titleString = areaName;
        at.code = @"";
        at.areaId = areadId;
        UINavigationController *na= [[UINavigationController alloc]initWithRootViewController:at];
        [self presentViewController:na animated:NO completion:nil];
        
       _currentUrl = request.URL.absoluteString;
        [_hud hide:YES];
        return NO;
    }

    if ([request.URL.absoluteString containsString:@"area_info?type=ditu&name="]){
        NSArray *arr = [request.URL.absoluteString componentsSeparatedByString:@"&code="];
        NSString *code;
        //游客中心和厕所直接跳到地图，标出位置
        NSArray *inerA = [[arr objectAtIndex:0] componentsSeparatedByString:@"&name="];
        NSString *na = [inerA objectAtIndex:1];
        NSString *name = [na stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"name = %@",name);
        NSArray * innerB = [[arr objectAtIndex:1] componentsSeparatedByString:@"&keyword="];
        code = [innerB objectAtIndex:0];
        //景点详情页面，地图点击跳转
        [Manager spotDetailMapClicked:self andName:name andCode:code];
              
        [_hud hide:YES];
        return NO;
    }

    if ([request.URL.absoluteString containsString:@"event/event_info?eventId"]) {
        //点击某个具体的赛事，跳到“竞赛详情”页面
        [_hud hide:YES];

        CompeteDetailVC *comDVC = [[CompeteDetailVC alloc] init];
        UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:comDVC];
        NSArray *ary = [request.URL.absoluteString componentsSeparatedByString:@"eventId="];
        //NSRange range = {request.URL.absoluteString.length - 3, 3};//第一个数代表起始位置, 第二个数代表长度
        //NSString *str = [request.URL.absoluteString substringWithRange:range];
        //        NSLog(@"%@", ary[1]);
        comDVC.urlStr = ary[1];
        [self presentViewController:naVC animated:NO completion:nil];
        
        return NO;
    }
    if ([request.URL.absoluteString containsString:@"s?__biz="]) {
        //跳到“公告详情”页面

        [self.navigationItem.leftBarButtonItem setImage:[UIImage imageNamed:@"nav_back"]];
        
        self.navigationItem.title = @"公告详情";
        _currentUrl = request.URL.absoluteString;
    }
    
    if ([request.URL.absoluteString containsString:@"mp/homepage?__biz"])
    {

         [self.navigationItem.leftBarButtonItem setImage:[UIImage imageNamed:@"nav_back"]];
      
        self.navigationItem.title = @"公告列表";
        _currentUrl = request.URL.absoluteString;
    }
    
   if ([request.URL.absoluteString containsString:@"event/introduce_index"])
   {
       //点竞赛详情的箭头，下面的tabbar切换到竞赛地方
       //发送通知，通知appdelegate，切换到竞赛
       [_hud hide:YES];

       [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"AppChangeTabbarSelectIndex" object:nil]];
       return NO;
   }
   
    
 /*
    if ([request.URL.absoluteString containsString:@"scenic/area_info?isLogin=false"])
    {
        [_hud hide:YES];
        //未登录情况下，点击评论，跳转至登录界面
        LoginViewController *vc = [[LoginViewController alloc]init];
        vc.skipFrom = @"homeSpotDetaiComment";
        UINavigationController *na = [[UINavigationController alloc]initWithRootViewController:vc];
        [self presentViewController:na animated:NO completion:nil];
        return NO;
    }
    
    
    if ([request.URL.absoluteString containsString:@"terminal/scenic/area_info/call_phone?phone="])
   {
       //拨打电话，调用电话功能
       [_hud hide:YES];
       NSArray *ary = [request.URL.absoluteString componentsSeparatedByString:@"phone="];//电话号码截取出来
       NSString *phone = [ary objectAtIndex:1];
       [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"telprompt:%@",phone]]];
       return NO;
   }
    
    if ([request.URL.absoluteString containsString:@"/scenic/area_info?type=share"]) {
        [_hud hide:YES];
        //分享
         [Manager shareToSinaEvent:self viewController:self andImgUrl:self.currentSpotImgUrl andSpotname:self.currentSpotName];
        return NO;
    }
    
    if ([request.URL.absoluteString containsString:@"/scenic/area_info?type=favorite"]) {
        //收藏
        [_hud hide:YES];
        [Manager collectionBtnClicked:self andAreaId:self.areaId];
        return NO;
    }
  */  
     [_hud hide:YES];
    return YES;
}




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

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

#pragma mark - KVC
//使用KVC赋值, 没有找到对应的key
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
    //    NSLog(@"不能识别%@", key);
    //字典中是id，属性中是ID
    //    if ([key isEqualToString:@"id"]) {
    //        self.ID = value;
    //    }
}

//使用KVC取值, 没有找到对应的key
- (id)valueForUndefinedKey:(NSString *)key {
    //    NSLog(@"不能识别%@", key);
    return nil;
}


-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"freshSpotDetailWebview" 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
