//
//  JoinTeamVC.m
//  RadioDemo
//
//  Created by Mac Book DQ02 on 16/9/25.
//  Copyright © 2016年 Xu Mengzhu. All rights reserved.
//

#import "JoinTeamVC.h"

#define KMargin 10
#define kHeight 30


@interface JoinTeamVC ()

@end

@implementation JoinTeamVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.jCellArr = [NSMutableArray array];

   
    
    self.navigationItem.title = @"加入团队";
     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(joinBackClicked)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
#pragma mark --设置UISegmentController，分段控制器
    UIImage *apply_yes = [UIImage imageNamed:@"join0"];
    apply_yes = [apply_yes imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIImage *create = [UIImage imageNamed:@"create1"];
    create = [create imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    NSArray *titleArray = @[apply_yes, create];
    UISegmentedControl *segC = [[UISegmentedControl alloc] initWithItems:titleArray];
    segC.frame = CGRectMake(KMargin, KMargin,SCREEN_WIDTH - 2*KMargin , kHeight);
    segC.tintColor = [UIColor whiteColor];
    segC.selectedSegmentIndex = 0;
    [segC addTarget:self action:@selector(segCClicked:) forControlEvents:UIControlEventValueChanged];
    self.operaSegC = segC;
     [self.view addSubview: self.operaSegC];
    
    
#pragma mark --设置创建团队的输入框还有创建按钮(设定是一直存在的，只是被tableview盖住不显示)
    UITextField *teamF = [[UITextField alloc]initWithFrame:CGRectMake(3*KMargin, KMargin*6+kHeight, SCREEN_WIDTH - 6*KMargin, 45)];
    teamF.placeholder = @"请输入团队名称";
    teamF.borderStyle = UITextBorderStyleLine;
    teamF.layer.borderColor = [[UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1] CGColor];
    [self.view addSubview:teamF];
    self.tNameField = teamF;
    
    UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(3*KMargin, KMargin*6+kHeight+50, SCREEN_WIDTH - 6*KMargin, 30)];
    lab.font = [UIFont systemFontOfSize:14];
    lab.text = @"";
    lab.textAlignment = NSTextAlignmentRight;
    lab.textColor = [UIColor redColor];
    [self.view addSubview:lab];
    self.nameWarningLab = lab;
   
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(9*KMargin,  KMargin*8+kHeight+80, SCREEN_WIDTH - 18*KMargin, 50)];
    [btn setTitle:@"创建团队" forState:UIControlStateNormal];
    [btn.layer setMasksToBounds:YES];//设置按钮的圆角半径不会被遮挡
    [btn.layer setCornerRadius:10];
    [btn.layer setBorderWidth:2];//设置边界的宽度
    [btn setBackgroundColor:[UIColor colorWithRed:235/255.0 green:235/255.0 blue:235/255.0 alpha:1]];
    btn.layer.borderColor = [[UIColor colorWithRed:235/255.0 green:235/255.0 blue:235/255.0 alpha:1] CGColor];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    [btn addTarget:self action:@selector(createBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    self.cTeamBtn = btn;
    
#pragma mark --添加团队列表的table
    [self getAllTeamsInfo];
   
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismissSelfAndPostNoti) name:@"teamVCDismiss" object:nil];
}


-(void)joinBackClicked
{
    //返回的时候。不仅本视图要dismiss掉，还要通知竞赛详情页面，present赛事列表页面
    [self dismissSelfAndPostNoti];
}


-(void)segCClicked:(UISegmentedControl *)sender
{
    if (sender.selectedSegmentIndex == 1) {
        NSLog(@"111111");
        //做跳转到创建团队操作(注意一点，如果创建团队成功，也是跳至赛事列表,如果没创建，就返回加入团队列表)
        [self.operaSegC setImage:[[UIImage imageNamed:@"join1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forSegmentAtIndex:0];
        [self.operaSegC setImage:[[UIImage imageNamed:@"create0"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forSegmentAtIndex:1];
        self.nameWarningLab.text = @"";
        self.tNameField.text = @"";
        [self.teamTable removeFromSuperview];
        
    }else{
        [self.operaSegC setImage:[[UIImage imageNamed:@"join0"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forSegmentAtIndex:0];
        [self.operaSegC setImage:[[UIImage imageNamed:@"create1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forSegmentAtIndex:1];
        
        [self getAllTeamsInfo];
   
    }
}


#pragma mark --TeamCellDelegate事件
-(void)showPromptVC:(UIAlertController *)ac
{
    [self presentViewController:ac animated:NO completion:nil];
}


-(void)presentEventScheduleVC
{
    if (self.isApplyOrCreate) {
        //如果是第一次申请或者创建赛事，进入赛事列表，否则，直接dismiss掉页面
        [self scheduleVC];
    }else
    {
        [self dismissSelfAndPostNoti];
    }
}


#pragma mark --页面diss后，给竞赛详情页发送请求
-(void)dismissSelfAndPostNoti
{
    [self dismissViewControllerAnimated:NO completion:^{
        //页面dismiss后，通知竞赛详情，刷新页面
        [[NSNotificationCenter defaultCenter] postNotificationName:@"competeDetailFreshWeb" object:nil];
    }];
}


#pragma mark --创建团队的按钮点击事件
-(void)createBtnClicked
{
    self.nameWarningLab.text = @"";

    //创建团队的请求事件
    if ([self.tNameField.text isEqualToString:@""]) {
        self.nameWarningLab.text = @" 团队名字不能为空";
        return;
    }
    
    if ([self.tNameField.text length]>5) {
        self.nameWarningLab.text = @"团队名字不能超过5个字符";
        return;
    }
    Singleton *single = [Singleton defaultSingleton];
    
    //添加蒙板
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:YES];
    hud.labelText = @"正在创建...";
    [hud show:YES];
    //创建请求连接.
    NSString *postStr = [NSString stringWithFormat:@"%@/terminal/event/create_team",localRequestUrl];
    
    NSDictionary *parameter= [[NSDictionary alloc]initWithObjectsAndKeys:self.tNameField.text,@"teamName",single.userid,@"userId",single.eventId,@"eventId", nil];
    // 初始化Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain",nil];
    
    [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);
        if ([[responseDic objectForKey:@"code"] isEqualToString:@"000"]) {
            //表示创建团队成功，如果是添加虚拟赛事，或者申请别人的赛事进入的，要跳至 ，赛事安排列表（已加入，已创建）
            [self presentEventScheduleVC];
           
        }else
        {
            [FileDownloadTool alert:@"创建团队失败" view:self.view];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error=%@",error);
        //蒙板消失
        [hud hide:YES];
         [FileDownloadTool alert:@"创建团队失败" view:self.view];
       
    }];

    
    NSLog(@"创建团队");
}


#pragma mark --跳转至赛事那排列表页面
-(void)scheduleVC
{
    // 跳转到我的赛事安排页面
    MyCompeteScheduleVC *comSchVC= [[MyCompeteScheduleVC alloc]init];
    comSchVC.fromTeamVC = YES;
    UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:comSchVC];
    [self presentViewController:naVC animated:NO completion:nil];

}


#pragma mark --获取团队列表数据
-(void)getAllTeamsInfo
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:YES];
    hud.labelText = @"获取队员信息...";
    [hud show:YES];
    
    Singleton *single = [Singleton defaultSingleton];
    [self.jCellArr removeAllObjects];
    //创建请求连接.
    NSString *postStr = [NSString stringWithFormat:@"%@/terminal/event/team_info_list",localRequestUrl];
    
    NSDictionary *parameter= [[NSDictionary alloc]initWithObjectsAndKeys:single.eventId,@"eventId", nil];
    
    // 初始化Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain",nil];
    
    [manager POST:postStr parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
        NSLog(@"responseDic=%@",responseDic);
        NSArray *teamArr = [responseDic objectForKey:@"teamList"];
        if (teamArr.count != 0) {
            for (NSString *memJsonStr in teamArr) {
                NSData *memData = [memJsonStr dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary *memDic = [NSJSONSerialization JSONObjectWithData:memData options:NSJSONReadingMutableLeaves error:nil];
                TeamInfo *teamModel = [[TeamInfo alloc]initWithTeamInforDic:memDic];
                [self.jCellArr addObject:teamModel];
            }
        }
        [hud hide:YES];
        [self waitAddTeamTable];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error=%@",error);
        //蒙板消失
        [hud hide:YES];
        [Manager setNetStatusOnView:self.view];
        
    }];
    
}

#pragma mark --将tableview添加到视图上的函数
-(void)waitAddTeamTable
{
    if (self.operaSegC.selectedSegmentIndex == 0) {
        [self.teamTable reloadData];
        [self.view addSubview:self.teamTable];
    }
}





#pragma mark ---lazy load
-(UITableView *)teamTable
{
    if (!_teamTable) {
        _teamTable = [[UITableView alloc]initWithFrame:CGRectMake(0, kHeight+2*KMargin, SCREEN_WIDTH, SCREEN_HEIGHT- 2*KMargin -kHeight-64)];
    }
    [_teamTable   setSeparatorColor:[UIColor    lightGrayColor]];  //设置分割线为浅灰色
    _teamTable.backgroundColor = [UIColor whiteColor];
    _teamTable.delegate = self;
    _teamTable.dataSource = self;
    return _teamTable;
}

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


#pragma mark --tableviewDatasource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.jCellArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cellReuse";
    
    TeamNameCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        [tableView registerNib:[UINib nibWithNibName:@"TeamNameCell" bundle:nil] forCellReuseIdentifier:@"cellReuse"];
        cell = [tableView dequeueReusableCellWithIdentifier:@"cellReuse"];
    }
    cell.jFlag = 0;
     [cell setTable:tableView andArr:self.jCellArr];
    [cell.joinBtn setTitle:@"加入团队" forState:UIControlStateNormal];
    TeamInfo *info = (TeamInfo *)[self.jCellArr objectAtIndex:indexPath.row];
    cell.teamNaLab.text = info.teamName;
    cell.teamNumLab.text = [NSString stringWithFormat:@"%@",info.teamNum];
    cell.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

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


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0,  0, tableView.frame.size.width, 40)];
    NSArray *wordA = @[@"团队名称",@"人数",@"操作"];
    int i;
    for (i=0; i<3; i++) {
        UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(0+i*tableView.frame.size.width/3.0, 0, tableView.frame.size.width/3.0, 40)];
        
        lab.text = [wordA objectAtIndex:i];
        lab.textAlignment = NSTextAlignmentCenter;
        [view addSubview:lab];
        
    }
    view.backgroundColor = [UIColor colorWithRed:235/255.0 green:235/255.0 blue:235/255.0 alpha:1];
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}

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