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

#import "CompeteDetailVC.h"
#import "CompeteViewController.h"
#import "Singleton.h"
#import "LoginViewController.h"
#import "MyEventProcessManagementVC.h"
#import "MyScoreVC.h"

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

@property (nonatomic, strong) UIWebView *webView;

@end

@implementation CompeteDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //创建单例实例
    singleton = [Singleton defaultSingleton];
    
    self.navigationItem.title = @"竞赛详情";
    //改变字体颜色
//    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
//    textAttrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
//    self.navigationController.navigationBar.titleTextAttributes = textAttrs;
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav_bg"] forBarMetrics:(UIBarMetricsDefault)];
//    self.view.backgroundColor = [UIColor whiteColor];
    
     [Manager setNavi:self.navigationController.navigationBar];
    
#pragma - 设置导航栏左边的按钮

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav_back.png"] landscapeImagePhone:nil style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItemIsClicked:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    //添加观察者, 接受来自“我的成绩页面”和“我的赛事过程管理”的通知，还有通知页面跳转后刷新页面
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(comDtailwebViewLoad) name:@"reLoadCompeteDetail" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(comDtailwebViewLoad) name:@"reLoadFromMyCompeteSchedule" object:nil];
    //freshCompeteDetailC
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(comDtailwebViewLoad) name:@"freshCompeteDetailC" object:nil];
    
//    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64)];
//    [_webView setUserInteractionEnabled:YES];//是否支持交互
//    [_webView setOpaque:NO]; //opaque是不透明的意思
//    [_webView setScalesPageToFit:YES]; //自动缩放以适应屏幕
//    _webView.scrollView.bounces = NO;
//    _webView.scrollView.showsVerticalScrollIndicator = NO;
    
    _webView = [Manager screenFrameWebview];
    _webView.delegate = self;

    if (![singleton.string isEqualToString:@"9002"]) {
        //加载网页的方式
        //1.创建并加载远程网页
        //    NSLog(@"_urlStr:%@", _urlStr);
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/terminal/event/event_info?eventId=%@",localRequestUrl, _urlStr]];
        [_webView loadRequest:[NSURLRequest requestWithURL:url]];
        [self.view addSubview:_webView];
        
    } else if ([singleton.string isEqualToString:@"9002"]) {
        //加载网页的方式
        //1.创建并加载远程网页
        NSLog(@"_urlStr:%@", _urlStr);
        singleton.eventId = _urlStr;//此为登陆状态接口，要将当前操作的赛事存储
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/terminal/event/event_info?sesskey=%@&eventId=%@",localRequestUrl,singleton.sesskey, self.urlStr]];
        [_webView loadRequest:[NSURLRequest requestWithURL:url]];
        [self.view addSubview:_webView];
    }
    
    //competeDetailFreshWeb
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(respondToTeamVCFresh:) name:@"competeDetailFreshWeb" object:nil];
}


#pragma mark 接收到我的赛事加入创建表的通知，刷新页面
-(void)respondToTeamVCFresh:(NSNotification *)noti
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/terminal/event/event_info?sesskey=%@&eventId=%@",localRequestUrl, singleton.sesskey, self.urlStr]];
    [_webView loadRequest:[NSURLRequest requestWithURL:url]];
}

#pragma mark - 导航栏左边按钮被点击
- (void)leftBarButtonItemIsClicked:(UIBarButtonItem *)sender {
    
     [self dismissViewControllerAnimated:NO completion:nil];
    

}

#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSLog(@"竞赛详情页－－－：%@", request.URL.absoluteString);

    if ([request.URL.absoluteString containsString:@"terminal/error?err=11"]) {
        //跳到登录页面
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        //20160520 xmz modify
        loginVC.skipFrom = @"FromCompeteDetail";//用于登陆成功后，通知某个视图，刷新页面或者重载页面
        loginVC.fromCompeteEventID = _urlStr;//记录当前未登录下点击的赛事id，用于登陆成功，回传
        UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:loginVC];
        [self presentViewController:naVC animated:NO completion:nil];//登录成功后，是不是要刷新竞赛详情页
        return NO;
        
    }else if ([request.URL.absoluteString containsString:@"terminal/error?err=3"])
    {
        //赛事详情页面，申请赛事的时候，用户登录，但是没有绑卡，弹出绑卡提示框
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"系统提示" message:@"暂无绑定设备，去绑定登山设备" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
            BindingDeviceVC *bindVC = [[BindingDeviceVC alloc] init];
            UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:bindVC];
            [self presentViewController:naVC animated:NO completion:nil];
            
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertVc addAction:sureAction];
        [alertVc addAction:cancelAction];
        
        [self presentViewController:alertVc animated:NO completion:nil];
        
        return NO;
        
    }else if ([request.URL.absoluteString containsString:@"terminal/event/event_manage?parameter"]) {
        //跳到我的赛事过程管理页面，传递各种状态值
        NSLog(@"竞赛详情页：%@", request.URL.absoluteString);
        //截取request.URL.absoluteString参数后面的字符串
        NSArray *ary = [request.URL.absoluteString componentsSeparatedByString:@"parameter="];
        NSString *str = ary[1];
        NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
        NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSLog(@"responseObject:%@", responseObject);
        
        MyEventProcessManagementVC *myEPMVC = [[MyEventProcessManagementVC alloc] init];
        UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:myEPMVC];
        //根据状态值计算时间。
        //赛事预计开始时间
        NSString *time_start = [NSString stringWithFormat:@"%@", responseObject[@"eventStartTime"]];
        NSRange start_range = {0, 10};
        NSString *setStartTime = [time_start substringWithRange:start_range];
        
        //赛事真正开始时间
        //用于判断服务器返回值的类型
        Class class = NSClassFromString(@"NSNumber");
        
        if ([responseObject[@"realStartTime"] isKindOfClass:class]) {
            NSString *time_real = [NSString stringWithFormat:@"%@", responseObject[@"realStartTime"]];
            NSLog(@"赛事真正开始时间的时间戳=%@",time_real);
            NSRange range = {0, 10};
            NSString *setRealTime = [time_real substringWithRange:range];
            
            //传值
            myEPMVC.realStartTime = setRealTime;
        } else {
            myEPMVC.realStartTime = nil;
        }
        
        bool is = [responseObject[@"isOrganizer"] boolValue];
        NSLog(@"istf%d", is);
        myEPMVC.isTure = is;
        myEPMVC.eventStartTime = setStartTime;
        myEPMVC.status = [responseObject[@"eventStatus"] integerValue];
        NSNumberFormatter *start_numberFormatter = [[NSNumberFormatter alloc] init];
        NSString *eventId = [start_numberFormatter stringFromNumber:responseObject[@"eventId"]];
        NSString *routeId = [start_numberFormatter stringFromNumber:responseObject[@"routeId"]];
        singleton.deviceSn = responseObject[@"deviceSn"];
        singleton.routeId = routeId;//存储当前操作的赛事路线id
        singleton.eventId = eventId;
        singleton.eventType = responseObject[@"eventType"];
        singleton.is = is;
        NSLog(@"eventId:%@", eventId);
        
        NSMutableArray *repeaterArr = [NSMutableArray array];
        
        //如果是官方赛事，解析后面的中继点坐标
        if (!([responseObject[@"eventType"] intValue]==0) || !([responseObject[@"eventType"] intValue]==1)) {
           NSArray *repeaterStr = responseObject[@"repeaterAxisList"];
            for (NSString *innerStr in repeaterStr) {
                NSData *innerData = [[NSData alloc] initWithData:[innerStr dataUsingEncoding:NSUTF8StringEncoding]];
                NSDictionary *innerDic = [NSJSONSerialization JSONObjectWithData:innerData options:NSJSONReadingMutableLeaves error:nil];
                AGSPoint *point = [[AGSPoint alloc]initWithX:[[innerDic objectForKey:@"axisX"] doubleValue]  y:[[innerDic objectForKey:@"axisY"] doubleValue] spatialReference:[AGSSpatialReference wgs84SpatialReference]];
                [repeaterArr addObject:point];
            }
            
            AGSGraphic *gra = [[[FMDataBaseTool alloc]init] graphicWithPointArr:repeaterArr];
            myEPMVC.evpStart = [FMDataBaseTool getMarkSymGraphic:[repeaterArr firstObject] type:1];
            myEPMVC.evpEnd = [FMDataBaseTool getMarkSymGraphic:[repeaterArr lastObject] type:2];
            myEPMVC.officalEventRoute = gra;
        }
        
        [self presentViewController:naVC animated:NO completion:nil];

        
    } else if ([request.URL.absoluteString containsString:@"event_repeater_ranking?eventId="] || [request.URL.absoluteString containsString:@"event/event_view?eventId="]) {
        //跳到我的成绩页面
        MyScoreVC *scoreVC = [[MyScoreVC alloc] init];
        UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:scoreVC];
        NSArray *ary = [request.URL.absoluteString componentsSeparatedByString:@"eventId="];
        singleton.scoreId = ary[1];
        [self presentViewController:naVC animated:YES completion:nil];
        
#pragma mark --在这个地方拦截，先跳至加入团队页面，可以加入已有团队或者自己创建团队
//        JoinTeamVC *comSchVC= [[JoinTeamVC alloc]init];
//        UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:comSchVC];
//        [self presentViewController:naVC animated:NO completion:nil];

        
        return NO;
    }else if ([request.URL.absoluteString containsString:@"terminal/success?suc=1"])
    {
        //在用户，信息没有完善的时候，在首页，点击申请别人的赛事，在加入赛事之前要求完善信息，保存信息后，会进入这个if。通知我的，左视图刷新页面
        //保存成功后，截取出昵称，要发送通知给我的，左视图，做视图修改，修改昵称
        if ([request.URL.absoluteString containsString:@"nickName="]) {
            NSArray *ary = [request.URL.absoluteString componentsSeparatedByString:@"nickName="];
            NSString *base64NickAndSex = [ary objectAtIndex:1];
            NSArray *nickAndSex = [base64NickAndSex componentsSeparatedByString:@"&sex="];
            NSString *base64Nick = [nickAndSex objectAtIndex:0];
            NSString *sex = [nickAndSex objectAtIndex:1];
        
            //base64解密
            NSData *data = [[NSData alloc] initWithBase64EncodedString:base64Nick   options:NSDataBase64DecodingIgnoreUnknownCharacters];
            NSString *nick= [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            Singleton *single = [Singleton defaultSingleton];
            single.nickName = nick;
            single.sex = [NSNumber numberWithInt:[sex intValue]];
        
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ToAssignValueAndReLoadWebView" object:nil];//我的
        
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeNickFromHomeCompeteApply" object:single.nickName];//左视图
        }
        
#pragma mark --在这个地方拦截，先跳至加入团队页面，可以加入已有团队或者自己创建团队
        JoinTeamVC *joinVC= [[JoinTeamVC alloc]init];
        joinVC.isApplyOrCreate = YES;
        UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:joinVC];
        [self presentViewController:naVC animated:NO completion:nil];

        
        // 跳转到我的赛事安排页面
//        MyCompeteScheduleVC *comSchVC= [[MyCompeteScheduleVC alloc]init];
//        comSchVC.fromHomeCompeteDetail = YES;
//        UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:comSchVC];
//        [self presentViewController:naVC animated:NO completion:nil];
        
        return NO;
    }else if ([request.URL.absoluteString containsString:@"terminal/error?err=4"]){
        //表示赛事冲突，不能申请
        [FileDownloadTool alert:@"您申请的赛事有冲突" view:self.view];
        return NO;
    }else if ([request.URL.absoluteString containsString:@"join_event_team?type="])
    {
        //点击竞赛详情页面的团队按钮的时候，区分当前团队状态（无团队，有团队非管理员，团队管理员）
        NSArray *strArr = [request.URL.absoluteString componentsSeparatedByString:@"type="];
        NSString *joinType = [strArr objectAtIndex:1];
        if ([joinType isEqualToString:@"notTeam"]) {
            //没有团队，可以跳到加入团队页面，自行加入或者创建
            JoinTeamVC *joinVC= [[JoinTeamVC alloc]init];
            UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:joinVC];
            [self presentViewController:naVC animated:NO completion:nil];
        }else if ([joinType isEqualToString:@"haveTeam"])
        {
            //有团队，但是不是管理员，只能查看团队成员列表,
            ManageTeamVC *maVC= [[ManageTeamVC alloc]init];
            maVC.isCreater = NO;
            UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:maVC];
            [self presentViewController:naVC animated:NO completion:nil];
            
        }else
        {
            //团队管理者,跳到团队管理页面，可以剔除队员
            ManageTeamVC *maVC= [[ManageTeamVC alloc]init];
            maVC.isCreater = YES;
            UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:maVC];
            [self presentViewController:naVC animated:NO completion:nil];
        }
        return NO;
    }
    

    return YES;
}

#pragma mark - 接受“我的成绩页面”的通知， 重新加载竞赛详情页面
- (void)comDtailwebViewLoad {
    if ([singleton.string isEqualToString:@"9002"]) {
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/terminal/event/event_info?sesskey=%@&eventId=%@",localRequestUrl, singleton.sesskey, self.urlStr]];
        singleton.eventId = _urlStr;//此为登陆状态接口，要将当前操作的赛事存储
        [_webView loadRequest:[NSURLRequest requestWithURL:url]];
     
    }
    else
    {
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/terminal/event/event_info?eventId=%@",localRequestUrl, _urlStr]];
        [_webView loadRequest:[NSURLRequest requestWithURL:url]];
 
    }
    
}


-(void)webViewDidFinishLoad:(UIWebView *)webView{
     
}

-(void)viewWillAppear:(BOOL)animated
{
    [self comDtailwebViewLoad];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"reLoadCompeteDetail" object:nil];
     [[NSNotificationCenter defaultCenter]removeObserver:self name:@"reLoadFromMyCompeteSchedule" object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"freshCompeteDetailC" object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"competeDetailFreshWeb" 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
