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

#import "TeamNameCell.h"

@implementation TeamNameCell
{
     __weak UITableView *_belongTable;
    __weak NSMutableArray *_tMCellArr;//获取的数据源数组
}

- (void)awakeFromNib {
    // Initialization code
    [super awakeFromNib];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

#pragma mark --加入按钮点击事件
- (IBAction)joinBtnClicked:(UIButton *)sender {

    //先获取btn的父视图
    TeamNameCell * cell = (TeamNameCell *)[[sender superview] superview];
    if (!cell.isCreater && cell.jFlag == 1) {
        //表示是在展示队员的页面，按钮点击没反应
        return;
    }
    
    if (cell.isOrganizer) {
        return;
    }
       NSString *titleS= @"";
    
    NSString *promptS= @"";
    
    if (cell.jFlag == 1) {
        titleS = @"管理团队";
        promptS = [NSString stringWithFormat:@"确定将队员%@踢出团队吗？",cell.teamNaLab.text];
    }else
    {
        titleS = @"加入团队";
        promptS = [NSString stringWithFormat:@"确定加入%@团队吗？",cell.teamNaLab.text];
    }
    UIAlertController * jc = [UIAlertController alertControllerWithTitle:titleS message:promptS preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *join = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //这边做加入团队的请求(请求成功以后，页面dismiss掉，然后跳转至赛事列表)
        if (cell.jFlag == 0) {
            
            [self joinToTeam:cell];//加入团队操作
        }else
        {
            [self manageMember:cell];
        }
        
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [jc addAction:join];
    [jc addAction:cancel];
    
    if ([self.delegate respondsToSelector:@selector(showPromptVC:)]) {
        [self.delegate showPromptVC:jc];
    }
      
}

-(void)setTeamName:(NSString *)name
{
    self.teamNaLab.text = name;
}

-(void)setTable:(UITableView *)tab andArr:(NSMutableArray *)cellA
{
    _belongTable = tab;
    _tMCellArr = cellA;
}

-(void)joinToTeam:(TeamNameCell *)cell
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:YES];
    hud.labelText = @"加入团队...";
    [hud show:YES];

     NSIndexPath *index = [_belongTable indexPathForCell:cell];
    TeamInfo *info = [_tMCellArr objectAtIndex:index.row];//(加入团队的时候，团队信息，当前点击行，表示该团队的ID，名字)
    
    NSLog(@"加入团队");
    //加入团队成功后直接跳至
    Singleton *single = [Singleton defaultSingleton];
    //创建请求连接.
    NSString *postStr = [NSString stringWithFormat:@"%@/terminal/event/join_team",localRequestUrl];
    
    NSDictionary *parameter= [[NSDictionary alloc]initWithObjectsAndKeys:[NSString stringWithFormat:@"%@",info.teamId],@"teamId",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 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);
        //000 表示加入团队成功    002 表示已经有团队 003表示有错误，没传参数
        if ([[responseDic objectForKey:@"code"] isEqualToString:@"000"]) {
            //表示加入团队成功
            if ([self.delegate respondsToSelector:@selector(presentEventScheduleVC)]) {
                [self.delegate presentEventScheduleVC];
            }
            
        }else if ([[responseDic objectForKey:@"code"] isEqualToString:@"002"]){
            //表示已经加入过团队
            [FileDownloadTool alert:@"已经有团队" view:_belongTable];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error=%@",error);
         [hud hide:YES];
        [FileDownloadTool alert:@"加入团队失败" view:_belongTable];
    }];

}



-(void)manageMember:(TeamNameCell *)cell
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:YES];
    hud.labelText = @"删除队员...";
    [hud show:YES];
    
     NSIndexPath *index = [_belongTable indexPathForCell:cell];
    MemberInfo *info = [_tMCellArr objectAtIndex:index.row];
    
    Singleton *single = [Singleton defaultSingleton];
    //创建请求连接.
    NSString *postStr = [NSString stringWithFormat:@"%@/terminal/event/fire_team_user",localRequestUrl];
    
    NSDictionary *parameter= [[NSDictionary alloc]initWithObjectsAndKeys:info.teamId,@"teamId",[NSString stringWithFormat:@"%@",info.userId],@"userId",single.userid,@"organizerId",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) {
        
        [hud hide:YES];
        
        NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
        NSLog(@"responseDic=%@",responseDic);
        if ([[responseDic objectForKey:@"code"] isEqualToString:@"000"]) {
            //表示删除成功
            //刷新表格
            [FileDownloadTool alert:@"踢出成功" view:_belongTable];
            [self waitReloadManageTable:index];
        }
       
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error=%@",error);
        //蒙板消失
        [hud hide:YES];
        [Manager setNetStatusOnView:_belongTable];
        
    }];

    
     NSLog(@"管理团队");
    //删除成功后，刷新表格
   
   }

-(void)waitReloadManageTable:(NSIndexPath *)index
{
    [_tMCellArr removeObjectAtIndex:index.row];
    [_belongTable reloadData];

}

@end
