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

#import "ManageTeamVC.h"

#define KMargin 10
#define kHeight 30

@interface ManageTeamVC ()

@end

@implementation ManageTeamVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [Manager setNavi:self.navigationController.navigationBar];
    
#pragma - 设置导航栏左边的按钮
    self.navigationItem.title = @"管理团队";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav_back.png"] landscapeImagePhone:nil style:UIBarButtonItemStylePlain target:self action:@selector(manageBackClicked)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
   
#pragma mark --设置团队名称还有团队总人数的显示(注意区分 团队创建者和非创建者)
    UILabel *namePromptLab = [[UILabel alloc]initWithFrame:CGRectMake(2*KMargin, KMargin, 110, kHeight)];
    namePromptLab.text = @"团队名称：";
    [self.view addSubview:namePromptLab];
    
    UILabel *nameLab = [[UILabel alloc]initWithFrame:CGRectMake(112,KMargin, (SCREEN_WIDTH-4*KMargin)/2, kHeight)];
    nameLab.text = @"";
    [self.view addSubview:nameLab];
    self.teamNameLab = nameLab;
    
    
    UILabel *numPromptLab = [[UILabel alloc]initWithFrame:CGRectMake(2*KMargin, KMargin+kHeight, 110, kHeight)];
    numPromptLab.text = @"团队人数：";
    [self.view addSubview:numPromptLab];
    
    UILabel *numLab = [[UILabel alloc]initWithFrame:CGRectMake(112, KMargin+kHeight, (SCREEN_WIDTH-4*KMargin)/2, kHeight)];
    numLab.text = @"";
    [self.view addSubview:numLab];
    self.teamNumLab = numLab;
    
    if (self.isCreater) {
        UILabel *opePromptLab = [[UILabel alloc]initWithFrame:CGRectMake(2*KMargin, KMargin+2*kHeight, (SCREEN_WIDTH-4*KMargin)/2, kHeight)];
        opePromptLab.text = @"操作：";
        [self.view addSubview:opePromptLab];
        
        UIButton *dissolve = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH*2/3, KMargin+2*kHeight, SCREEN_WIDTH/3-KMargin, kHeight)];
        [dissolve.layer setMasksToBounds:YES];//设置按钮的圆角半径不会被遮挡
        [dissolve.layer setCornerRadius:10];
        [dissolve.layer setBorderWidth:2];//设置边界的宽度
        [dissolve setBackgroundColor:[UIColor colorWithRed:235/255.0 green:235/255.0 blue:235/255.0 alpha:1]];
        dissolve.layer.borderColor = [[UIColor colorWithRed:235/255.0 green:235/255.0 blue:235/255.0 alpha:1] CGColor];
        [dissolve setTitle:@"解散团队" forState:UIControlStateNormal];
        [dissolve setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [dissolve addTarget:self action:@selector(dissolveTeam) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:dissolve];
    }else
    {
        UILabel *createrPromptLab = [[UILabel alloc]initWithFrame:CGRectMake(2*KMargin, KMargin+2*kHeight, 110, kHeight)];
        createrPromptLab.text = @"团队创建者：";
        [self.view addSubview:createrPromptLab];
        
        UILabel *cNameLab = [[UILabel alloc]initWithFrame:CGRectMake(116, KMargin+2*kHeight, (SCREEN_WIDTH-4*KMargin)/2, kHeight)];
        cNameLab.text = @"";
        [self.view addSubview:cNameLab];
        self.orgaNameLab = cNameLab;
    }
   

    
#pragma mark --获取数据，填充数据源
    self.mCellArr = [NSMutableArray array];

    [self getAllMembersInTeam];

   
#pragma mark --添加管理团队的table
    [self.view addSubview:self.manageTable];
    
}


#pragma mark --拉取某个团队的所有成员
-(void)getAllMembersInTeam
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:YES];
    hud.labelText = @"正在获取...";
    [hud show:YES];
    
    Singleton *single = [Singleton defaultSingleton];
    [self.mCellArr removeAllObjects];
    //创建请求连接.
    NSString *postStr = [NSString stringWithFormat:@"%@/terminal/event/one_team_user_list",localRequestUrl];
    
    NSDictionary *parameter= [[NSDictionary alloc]initWithObjectsAndKeys:single.eventId,@"eventId",single.userid,@"userId", 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 *memList = [responseDic objectForKey:@"teamUserList"];
        if (memList.count != 0) {
            //表示有数据
            for (NSString *memJsonStr in memList) {
                NSData *memData = [memJsonStr dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary *memDic = [NSJSONSerialization JSONObjectWithData:memData options:NSJSONReadingMutableLeaves error:nil];
                MemberInfo *info = [[MemberInfo alloc]initWithMemberInforDic:memDic];
                //在团队成员展示页面，因为自己不是管理者，所以需要列出队长是谁，判断谁是组织者
                if ([info.organizerId intValue] == [info.userId intValue]) {
                    //表示当前的cell是队长
                    self.organizerName = info.userName;
                }
                [self.mCellArr addObject:info];
            }
        }
        [hud hide:YES];
        //刷新表格
        [self waitLoadManageTable];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error=%@",error);
        //蒙板消失
        [hud hide:YES];

        [Manager setNetStatusOnView:self.view];
        
    }];

}

#pragma mark --刷新表格函数
-(void)waitLoadManageTable
{
    MemberInfo *info = (MemberInfo *)[self.mCellArr objectAtIndex:0];
    self.teamNameLab.text = info.teamName;//团队名称
    self.teamNumLab.text = [NSString stringWithFormat:@"%ld",(unsigned long)self.mCellArr.count]; //团队总人数
    if ( self.orgaNameLab) {
        self.orgaNameLab.text = self.organizerName;
    }
    [self.manageTable reloadData];
    [self.view addSubview:self.manageTable];
}


#pragma mark --解散团队按钮的点击事件
-(void)dissolveTeam
{
    UIAlertController *disAlert = [UIAlertController alertControllerWithTitle:@"解散团队" message:@"确定要解散团队吗？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ensure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self dissolveTeamRequest];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style: UIAlertActionStyleCancel handler:nil];
    [disAlert addAction:ensure];
    [disAlert addAction:cancel];
    [self presentViewController:disAlert animated:NO completion:nil];
    
}

#pragma mark --解散团队的接口
-(void)dissolveTeamRequest
{
    Singleton *single = [Singleton defaultSingleton];
    //创建请求连接.
    NSString *postStr = [NSString stringWithFormat:@"%@/terminal/event/fire_team",localRequestUrl];
    
    MemberInfo *info = (MemberInfo *)[self.mCellArr objectAtIndex:0];
    
    NSDictionary *parameter= [[NSDictionary alloc]initWithObjectsAndKeys:single.userid,@"organizerId",info.teamId,@"teamId", 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) {
        
        NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
        NSLog(@"responseDic=%@",responseDic);
        if ([[responseDic objectForKey:@"code"] isEqualToString:@"000"
            ]) {
            
            //解散成功后，页面dismiss掉，并且，通知竞赛详情页面刷新
            [self dismissViewControllerAnimated:NO completion:^{
                
            }];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error=%@",error);
        //蒙板消失
        
        [Manager setNetStatusOnView:self.view];
        
    }];

}


#pragma mark --管理团队的返回按钮点击事件
-(void)manageBackClicked
{
    
    [self dismissViewControllerAnimated:NO completion:nil];

}

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


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

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

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

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cellReuse";
    Singleton * single = [Singleton defaultSingleton];
    TeamNameCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        [tableView registerNib:[UINib nibWithNibName:@"TeamNameCell" bundle:nil] forCellReuseIdentifier:@"cellReuse"];
        cell = [tableView dequeueReusableCellWithIdentifier:@"cellReuse"];
    }
    cell.delegate = self;
    [cell setTable:tableView andArr:self.mCellArr];
    cell.jFlag = 1;
    MemberInfo *info = (MemberInfo *)[self.mCellArr objectAtIndex:indexPath.row];
    if (self.isCreater) {
        if ([single.userid isEqualToString:[NSString stringWithFormat:@"%@",info.userId]]) {
            //表示是本团队的创建者
            cell.isOrganizer = YES;
            [cell.joinBtn setTitle:@"团队创建者" forState:UIControlStateNormal];
        }else
        {
            [cell.joinBtn setTitle:@"踢出团队" forState:UIControlStateNormal];
        }
        cell.isCreater = YES;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
  
    cell.teamNaLab.text = info.userName;
    cell.teamNumLab.text = @"";//此处是中间显示的label，此处不显示
    return cell;
}

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

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0,  0, tableView.frame.size.width, 40)];
    NSArray *wordA;
    if (self.isCreater) {
        wordA = @[@"成员昵称",@"",@"操  作"];
    }else{
         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)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
