//
//  MyCompeteScheduleVC.m
//  gaotingshan
//
//  Created by Mac Book DQ02 on 16/5/25.
//  Copyright © 2016年 Xu Mengzhu. All rights reserved.
//

#import "MyCompeteScheduleVC.h"
#import "ApplyModel.h"
#import "MBProgressHUD.h"


#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
#define KMargin 10
#define kHeight 30
//Cell重用标识符
#define kCompeteCellIdentifier @"Cell"


@interface MyCompeteScheduleVC ()
{
    //发送给服务器的请求参数
    NSString *apply_status;
    Singleton *singleton;
    
    UILabel *NoDataLabel;
}
@property (nonatomic, strong) UISegmentedControl *segmentedControl;
//已加入tableView
@property (nonatomic, strong) UITableView *applyTableView;
//已创建tableView
@property (nonatomic, strong) UITableView *createTableView;

@property (nonatomic, strong) NSMutableArray *applyAry;
@property (nonatomic, strong) NSMutableArray *createAry;
@property (nonatomic, strong) NSMutableArray *m_ary;
//活动状态
@property (nonatomic, strong) NSString *status;

@property (nonatomic, strong) NSArray *applyData;
@property (nonatomic, strong) id createData;


@end

@implementation MyCompeteScheduleVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.createData = nil;
    //创建单例实例
    singleton = [Singleton defaultSingleton];
    
    self.view.backgroundColor = [UIColor whiteColor];
    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)];
    
    [Manager setNavi:self.navigationController.navigationBar];
    
   
    
#pragma - 设置导航栏左边的按钮

//    self.navigationItem.leftBarButtonItem = [Manager rightItemTarget:self img:@"nav_back" tag:1000000 action:@selector(leftBarButtonItemIsClicked:)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav_back"] landscapeImagePhone:nil style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItemIsClicked:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    //改彭敦波
    UIImage *apply_yes = [UIImage imageNamed:@"yijianru_yes"];
    apply_yes = [apply_yes imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIImage *create = [UIImage imageNamed:@"yichuangjian_no"];
    create = [create imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    NSArray *titleArray = @[apply_yes, create];
    _segmentedControl = [[UISegmentedControl alloc] initWithItems:titleArray];
    _segmentedControl.selectedSegmentIndex =0;
    _segmentedControl.frame = CGRectMake(KMargin, 2*KMargin, kScreenWidth - 2*KMargin, kHeight);
    //修改选中颜色
   
    _segmentedControl.tintColor = [UIColor whiteColor];
    [_segmentedControl addTarget:self action:@selector(scheduleSegmentedControlIsClicked:) forControlEvents:(UIControlEventValueChanged)];
    [self.view addSubview:_segmentedControl];
    _segmentedControl.selectedSegmentIndex = 0;
    
    //添加观察者（接受来自于“赛事管理页面”的值）
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(CompetitionScheduleVCReloadData:) name:@"reLoadFromMyCompeteSchedule" object:nil];
    
    [self getAppliedCompetionDataFromServer];
}

#pragma mark - 导航栏左边按钮被点击
- (void)leftBarButtonItemIsClicked:(UIBarButtonItem *)sender {
    //加了团队后，返回按钮的逻辑需要特殊处理（待定）
    
   [self dismissViewControllerAnimated:NO completion:nil];

    //通知团队页面dismiss掉
    if (_fromTeamVC) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"teamVCDismiss" object:nil];
    }
   
#pragma mark --加入团队功能后，这个可能用不上了
    if (_fromCompeteAddSuccess) {
        //如果是从竞赛页面点击添加虚拟赛事进入的，添加成功，直接返回竞赛页面
        [[NSNotificationCenter defaultCenter] postNotificationName:@"addVirtualCompeteDismiss" object:nil];
    }
    
    
}

#pragma mark - UISegmentedControl按钮被点击触发的方法
- (void)scheduleSegmentedControlIsClicked:(UISegmentedControl *)sender {
    if (sender.selectedSegmentIndex ==0) {
        //改彭敦波
        [_segmentedControl setImage:[[UIImage imageNamed:@"yijianru_yes"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forSegmentAtIndex:0];
        [_segmentedControl setImage:[[UIImage imageNamed:@"yichuangjian_no"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forSegmentAtIndex:1];
        
        [NoDataLabel removeFromSuperview];
        [self.createTableView removeFromSuperview];
        [self.applyTableView removeFromSuperview];
        [self.m_ary removeAllObjects];
        [self getAppliedCompetionDataFromServer];
    }
    else if(sender.selectedSegmentIndex ==1)
    {
        //改彭敦波
        [_segmentedControl setImage:[[UIImage imageNamed:@"yichuangjian_yes"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forSegmentAtIndex:1];
        [_segmentedControl setImage:[[UIImage imageNamed:@"yijiaru_no"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forSegmentAtIndex:0];
        
        [NoDataLabel removeFromSuperview];
        [self.applyTableView removeFromSuperview];
        [self.createTableView removeFromSuperview];
        [self.m_ary removeAllObjects];

        [self getCreatedCompetionDataFromServer];
    }
    
}

#pragma mark 懒加载
-(NSMutableArray *)applyAry
{
    if (!_applyAry) {
        _applyAry = [[NSMutableArray alloc]initWithCapacity:10];
    }
    return _applyAry;
}

-(NSMutableArray *)createAry
{
    if (!_createAry) {
        _createAry = [[NSMutableArray alloc]initWithCapacity:10];
    }
    return _createAry;
}



#pragma mark 设置没有数据的label显示“暂无信息”
-(void)setLabelForNoData
{
    //用一个Label提示用户
    NoDataLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_segmentedControl.frame) + KMargin, kScreenWidth, 40)];
    NoDataLabel.text = @"暂无信息";
    NoDataLabel.textAlignment = NSTextAlignmentCenter;
    NoDataLabel.font = [UIFont systemFontOfSize:22];
    NoDataLabel.textColor = [UIColor colorWithRed:100/255. green:100/255. blue:100/255. alpha:0.1];
    [self.view addSubview:NoDataLabel];
}

#pragma mark 从服务器获取“已加入”赛事数据
-(void)getAppliedCompetionDataFromServer
{
    //添加蒙板
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:YES];
    hud.labelText = @"正在加载...";
    [hud show:YES];
    //创建请求连接.
     NSString *postStr = [NSString stringWithFormat:@"%@/terminal/userapplyevent",localRequestUrl];
    NSDictionary *parameter= [[NSDictionary alloc]initWithObjectsAndKeys:@"1",@"apply_status", nil];
    // 初始化Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:postStr parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //消失蒙板
        [hud hide:YES];

        NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
//        NSLog(@"responseDic=%@",responseDic);
        id allDataArr = [responseDic objectForKey:@"data"];
        //如果没有数据，加载无数据标签，函数跳出
        if (![allDataArr isKindOfClass:[NSArray class]] || ((NSArray *)allDataArr).count==0 ) {
            [self setLabelForNoData];
            return;
        }
        //将二进制转化为字符串
        for (NSDictionary *tempDic in (NSArray *)allDataArr) {
            ApplyModel *apply = [[ApplyModel alloc] initWithInforDic:tempDic];
            [self.applyAry addObject:apply];
        }
 
        self.m_ary = self.applyAry;
        
        if (!_applyTableView) {
            _applyTableView = [[UITableView alloc] initWithFrame:CGRectMake(KMargin, CGRectGetMaxY(_segmentedControl.frame) + KMargin, kScreenWidth - 2*KMargin, kScreenHeight - CGRectGetMaxY(_segmentedControl.frame) - KMargin-64) style:(UITableViewStylePlain)];

        }
      
        //注册cell
        [self.applyTableView registerClass:[CompeteCell class] forCellReuseIdentifier:kCompeteCellIdentifier];
        _applyTableView.delegate = self;
        _applyTableView.dataSource= self;
        [self.applyTableView reloadData];
        [self.view addSubview:_applyTableView];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //蒙板消失
        [hud hide:YES];
        [Manager setNetStatusOnView:self.view];
        [self setLabelForNoData];
    }];
}


#pragma mark 从服务器获取“已创建”赛事数据
-(void)getCreatedCompetionDataFromServer
{
    //添加蒙板
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:YES];
    hud.labelText = @"正在加载...";
    [hud show:YES];
    //创建请求连接.
    NSString *postStr = [NSString stringWithFormat:@"%@/terminal/usercreateevent",localRequestUrl];
    
    NSDictionary *parameter= [[NSDictionary alloc]initWithObjectsAndKeys:@"1",@"apply_status", nil];
    // 初始化Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:postStr parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //消失蒙板
//        [MBProgressHUD hideHUDForView:window animated:YES];
        [hud hide:YES];

        NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
        NSLog(@"responseDic=%@",responseDic);
            //如果没有数据，加载暂无数据标签，函数跳出
         id allDataArr = [responseDic objectForKey:@"data"];
         if ([allDataArr isKindOfClass:[NSNull class]] ) {
             [self setLabelForNoData];
             return;
         }
        
        //将二进制转化为字符串
        for (NSDictionary *tempDic in (NSArray *)allDataArr){
            CreateModel *create = [[CreateModel alloc] initWithInforDic:tempDic];
            [self.createAry addObject:create];
        }
        self.m_ary = self.createAry;
//        NSLog(@"已创建%@", _createAry);
        if (!_createTableView) {
             _createTableView = [[UITableView alloc] initWithFrame:CGRectMake(KMargin, CGRectGetMaxY(_segmentedControl.frame) + KMargin, kScreenWidth - 2*KMargin, kScreenHeight - CGRectGetMaxY(_segmentedControl.frame) - KMargin-64) style:(UITableViewStylePlain)];
        }
       
        //注册cell
        [self.createTableView registerClass:[CompeteCell class] forCellReuseIdentifier:kCompeteCellIdentifier];
        _createTableView.delegate = self;
        _createTableView.dataSource= self;
        [self.createTableView reloadData];
        [self.view addSubview:_createTableView];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error=%@",error);
        //蒙板消失
        [hud hide:YES];
        [Manager setNetStatusOnView:self.view];
        //用一个Label提示用户
        [self setLabelForNoData];
    }];

}


#pragma mark tableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _m_ary.count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CompeteCell *cell = [tableView dequeueReusableCellWithIdentifier:kCompeteCellIdentifier forIndexPath:indexPath];

    if (tableView == _applyTableView) {
        ApplyModel *apply = _m_ary[indexPath.row];
        [cell show:apply];
        return cell;
    } else if (tableView == _createTableView) {
        CreateModel *create = _m_ary[indexPath.row];
        [cell showCreate:create];
        return cell;
    } else {
        return nil;
    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 140;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    BOOL internetStatus=[Manager setNetStatusOnView:self.view];
    if (internetStatus == NO) {
        return;
    }
    if (tableView == _applyTableView) {
        //跳转到“我的成绩页面”。
        
       //  [self getAppliedCompetionDataFromServer];
        
        ApplyModel *apply = _m_ary[indexPath.row];
        NSLog(@"apply_eventStatus:%@", apply.eventStatus);
        if ([apply.eventStatus integerValue] == 2) {
            MyScoreVC *scoreVc = [[MyScoreVC alloc] init];
            UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:scoreVc];
            //类型转换工具
            NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
            NSString *eventId = [formatter stringFromNumber:apply.eventId];
            singleton.eventId = eventId;
            singleton.scoreId = eventId;
            [self presentViewController:naVC animated:NO completion:nil];
        } else if (!([apply.eventStatus integerValue] == 2)) {
            //跳转到“我的赛事过程管理”页面。
            
            MyEventProcessManagementVC *processVc = [[MyEventProcessManagementVC alloc] init];
            processVc.fromFlag =@"1";
            UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:processVc];
            //根据状态值计算时间。
            NSString *time_start = [NSString stringWithFormat:@"%@", apply.eventStartTime];
            NSRange start_range = {0, 10};
            NSString *setStartTime = [time_start substringWithRange:start_range];
            NSString *time_real = [NSString stringWithFormat:@"%@", apply.realStartTime];
            
            if (time_real.length > 10) {
                NSRange range = {0, 10};
                NSString *setRealTime = [time_real substringWithRange:range];
                processVc.realStartTime = setRealTime;
                
            } else  {
                processVc.realStartTime = nil;
            }
            //类型转换工具
            NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
            NSString *eventId = [formatter stringFromNumber:apply.eventId];
            NSString *routeId = [formatter stringFromNumber:apply.routeId];
            NSString *organizerId = [formatter stringFromNumber:apply.organizerId];
            bool is = [singleton.userid isEqualToString:organizerId];
            NSLog(@"is :%d", is);
            //单例赋值
            singleton.is = is;
            singleton.deviceSn = apply.deviceSn;
            singleton.routeId = routeId;
            //传值
            processVc.isTure = is;
            processVc.routeId = routeId;
            processVc.eventStartTime = setStartTime;
            processVc.status = [apply.eventStatus integerValue];
            processVc.officalEventRoute = apply.officalRG;//官方赛事的路线
            processVc.evpStart = apply.evStart;//官方赛事起点
            processVc.evpEnd = apply.evEnd;//官方赛事终点
            
            singleton.eventId = eventId;
            singleton.eventType = apply.eventType;
            [self presentViewController:naVC animated:NO completion:nil];
        }
    } else if (tableView == _createTableView) {
        
    //    [self getCreatedCompetionDataFromServer];
        
        CreateModel *create = _m_ary[indexPath.row];
        if ([create.status integerValue] == 2) {
            //跳转到“我的成绩页面”
            MyScoreVC *scoreVc = [[MyScoreVC alloc] init];
            UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:scoreVc];
            //类型转换工具
            NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
            NSString *eventId = [formatter stringFromNumber:create.eventId];
            singleton.scoreId = eventId;
            singleton.eventId = eventId;
            //NSLog(@"event:%@", eventId);
            [self presentViewController:naVC animated:NO completion:nil];
        }else if (!([create.status integerValue] == 2)) {
            //跳转到“我的赛事过程管理”页面。
            
            MyEventProcessManagementVC *processVc = [[MyEventProcessManagementVC alloc] init];
            processVc.fromFlag = @"2";
            UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:processVc];
            //根据状态值计算时间。
            NSString *time_start = [NSString stringWithFormat:@"%@", create.eventStartTime];
            NSRange start_range = {0, 10};
            NSString *setStartTime = [time_start substringWithRange:start_range];
            
            NSString *time_real = [NSString stringWithFormat:@"%@", create.realStartTime];
            NSLog(@"class:%@", [create.realStartTime class]);
            if (time_real.length > 10) {
                NSRange range = {0, 10};
                NSString *setRealTime = [time_real substringWithRange:range];
                processVc.realStartTime = setRealTime;
            } else {
                processVc.realStartTime = nil;
            }
            //类型转换工具
            NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
            NSString *eventId = [formatter stringFromNumber:create.eventId];
            NSString *routeId = [formatter stringFromNumber:create.routeId];
            NSString *organizerId = [formatter stringFromNumber:create.organizerId];
            bool is = [singleton.userid isEqualToString:organizerId];
            //单例赋值
            singleton.deviceSn = create.deviceSn;
            singleton.routeId = routeId;
            singleton.is = is;
            //传值
            processVc.isTure = is;
            processVc.routeId = routeId;
            processVc.eventStartTime = setStartTime;
            processVc.status = [create.status integerValue];
            singleton.eventId = eventId;
             singleton.eventType = create.type;
            singleton.scoreId = eventId;
            [self presentViewController:naVC animated:NO completion:nil];
        }
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

    
}


#pragma mark - 接收到通知之后，重新加载tableView上的数据
- (void)CompetitionScheduleVCReloadData:(NSNotification *)noti{
    //清空数组
    [self.m_ary removeAllObjects];
    
    //重新请求数据
    if ([(NSString *)noti.object isEqualToString:@"1"]) {
        [self.createTableView removeFromSuperview];

        [self getAppliedCompetionDataFromServer];
    }
    else
    {
        [self.applyTableView removeFromSuperview];

        [self getCreatedCompetionDataFromServer];
    }
    
}

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