//
//  NoBeginView.m
//  gaotingshan
//
//  Created by MacBook Dq01 on 16/4/8.
//  Copyright © 2016年 Mac Book DQ02. All rights reserved.
//

#import "NoBeginView.h"
#import "AFNetworking.h"
#import "MyEventProcessManagementVC.h"
#import "Singleton.h"
#import "MyMD5.h"
#import "ApplyTableViewCell.h"
#import "PersoListModel.h"
#import "PersonScoreModel.h"

#define KMargin 10
#define kHeight 30
//ScoreCollectionCell重用标识符
#define kScoreCollectionCellIdentifier @"collect"
//ApplyTableCell重用标识符
#define kApplyTableCellIdentifier @"tableCell"

@interface NoBeginView () <UITableViewDelegate, UITableViewDataSource,AGSMapViewLayerDelegate,AGSMapViewTouchDelegate>
{
    Singleton *singleton;
    NSArray *titleArray;
}



@end

@implementation NoBeginView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        
        //创建单例实例 赋值
        singleton = [Singleton defaultSingleton];
        
        
        float viewWidth = frame.size.width;
        
        
        UIImage *mapno = [UIImage imageNamed:@"gamemanager_tv1_yes"];
        mapno = [mapno imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        
        UIImage *scoreno = [UIImage imageNamed:@"gamemanager_tv2_no"];
        scoreno = [scoreno imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        
        UIImage *applyno = [UIImage imageNamed:@"gamemanager_tv3_no"];
        applyno = [applyno imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        
        titleArray = @[mapno,scoreno,applyno];
        _segmentedControl = [[UISegmentedControl alloc] initWithItems:titleArray];
        _segmentedControl.frame = CGRectMake(0, 0, viewWidth, kHeight);
        
        /*      if (singleton.is) {
         
         titleArray = @[mapno,scoreno,applyno];
         _segmentedControl = [[UISegmentedControl alloc] initWithItems:titleArray];
         _segmentedControl.frame = CGRectMake(0, 0, viewWidth, kHeight);
         } else {
         titleArray = @[mapno,scoreno];
         _segmentedControl = [[UISegmentedControl alloc] initWithItems:titleArray];
         _segmentedControl.frame = CGRectMake(0, 0, viewWidth, 40);
         
         }
         */
        _segmentedControl.tintColor = [UIColor whiteColor];
        
        [_segmentedControl addTarget:self action:@selector(NoBeginViewSegmentedControlIsClicked:) forControlEvents:(UIControlEventValueChanged)];
        [self addSubview:_segmentedControl];
        
        [self loadMapView];
        
    }
    return self;
}



#pragma mark 懒加载
- (NSMutableArray *)Person_ary {
    if (!_Person_ary) {
        _Person_ary = [@[] mutableCopy];
        
    }
    return _Person_ary;
}


#pragma mark -地图API的定位监听方法
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {
    //位置改变后的处理函数
    if ([keyPath isEqual:@"location"]){
        //        NSLog(@"抱歉，您不在景区内");
        self.point = self.mapView.locationDisplay.mapLocation;
        NSString *str_x = [NSString stringWithFormat:@"%lf", self.point.x];
        NSString *str_y = [NSString stringWithFormat:@"%lf", self.point.y];
        NSRange range = {0, 7};
        _point_x = [str_x substringWithRange:range];
        _point_y = [str_y substringWithRange:range];
        
        
    }
}

#pragma mark 从服务器获取成绩列表数据
//-(void)getScoreListFromServer
//{
//
//    [_scoreListArray removeAllObjects];
//    [_applyView removeFromSuperview];
//    //成绩列表。参数拼接
//    //创建单例实例 赋值
//    singleton = [Singleton defaultSingleton];
//    NSLog(@"eventId:%@ userid:%@", singleton.eventId, singleton.userid);
//    //    getUserEventResult
//    NSString *str_sign = [NSString stringWithFormat:@"{\"deviceSn\":\"%@\",\"eventId\":\"%@\",\"repeaterSn\":\"%@\"}eventApplyUserVerify", singleton.deviceSn, singleton.eventId,@""];
//    NSLog(@"%@", str_sign);
//
//    NSString *sign = [MyMD5 md5:str_sign];
//    NSString *para_data = [NSString stringWithFormat:@"{\\\"deviceSn\\\":\\\"%@\\\",\\\"eventId\\\":\\\"%@\\\",\\\"repeaterSn\\\":\\\"%@\\\"}", singleton.deviceSn, singleton.eventId,@""];
//
//
//    NSString *parameter = [NSString stringWithFormat:@"{\"sign\":\"%@\",\"data\":\"%@\",\"partner\":\"eventApplyUserVerify\",\"code\":\"getUserEventResult\",\"key\":\".5Xf_01KXd352s177Jx3wxXc074poII\"}",sign, para_data];
//
//    NSLog(@"parameter=%@",parameter);
//
//    NSDictionary *paramentDic = [[NSDictionary alloc]initWithObjectsAndKeys:parameter,@"out_msg", nil];
//
//    NSString *requestString = @"http://gwms.517gts.com/terminal/eventApplyUserVerify";
//    // 初始化Manager
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//
//    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//
//    // post请求
//    [manager POST:requestString parameters:paramentDic constructingBodyWithBlock:^(id  _Nonnull formData) {
//        // 拼接data到请求体，这个block的参数是遵守AFMultipartFormData协议的。
//
//    } progress:^(NSProgress * _Nonnull uploadProgress) {
//        // 这里可以获取到目前的数据请求的进度
//
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        // 请求成功，解析数据
//        NSLog(@"response=%@", responseObject);
//        NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
//        NSLog(@"str = %@",str);
//        NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
//        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
//        NSLog(@"dic=%@",dic);
//        if (!dic) {
//            return;
//        }
//
//        NSString *result_msg= [dic objectForKey:@"result_msg"];
//        NSLog(@"result_msg=%@",result_msg);
//
//        NSNumber *result_code= [dic objectForKey:@"result_code"];
//        NSLog(@"result_code=%@",result_code);
//
//        NSString *result_data=[dic objectForKey:@"result_data"];
//        NSLog(@"result_data=%@",result_data);
//
//        if([result_data isEqualToString:@""])
//            return;
//
//        //字符串再转化成json
//        NSData *JSONData = [result_data dataUsingEncoding:NSUTF8StringEncoding];
//        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
//        NSArray *arr = [responseJSON objectForKey:@"result"];
//        if (arr.count==0)
//        {
//            [FileDownloadTool alert:@"暂无数据" view:self];
//            return;
//        }
//        for (NSString *scoreDicStr in arr) {
//            NSData *scoreDicData = [scoreDicStr dataUsingEncoding:NSUTF8StringEncoding];
//            NSDictionary *scoreDic = [NSJSONSerialization JSONObjectWithData:scoreDicData options:NSJSONReadingMutableLeaves error:nil];
//            PersonScoreModel *scoreModel = [[PersonScoreModel alloc]initWithInforDic:scoreDic];
//            [self.scoreListArray addObject:scoreModel];
//
//
//        }
//        //对数组进行排序，没排名的，在model赋值的时候，给赋值了10000，所以会排到后面，并且显示的时候会显示无排名信息
//        _arr = [self.scoreListArray sortedArrayUsingComparator:^NSComparisonResult(PersonScoreModel *p1, PersonScoreModel *p2){
//            return [p1.eventTop compare:p2.eventTop];
//        }];
//
//        //等待网络请求完成后，回主线程刷新UI
//        [self waitLoadScoreListView];
//
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//
//        // 请求失败
//        NSLog(@"%@", [error localizedDescription]);
//
//    }];
//
//}
//
//#pragma mark 加载成绩列表tableview
//-(void)waitLoadScoreListView
//{
//    [_scoreView reloadData];
//    [self addSubview:self.scoreView];
//}

#pragma mark ---测试加入团队后的参赛人员接口
-(void)testGetAppliers
{
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:YES];
    hud.labelText = @"正在加载...";
    [hud show:YES];
    //创建请求连接.
    NSString *postStr = [NSString stringWithFormat:@"%@/terminal//event/team_user_list",localRequestUrl];
    NSDictionary *parameter= [[NSDictionary alloc]initWithObjectsAndKeys:singleton.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);
        NSDictionary * allTeamDic = [responseDic objectForKey:@"eventTeamUser"];
#pragma mark --有所属团队的申请人员先解析
        if ([allTeamDic allKeys].count != 0) {
            //表示团队有数据
            for (NSString *teamNa in [allTeamDic allKeys]) {
                //团队里面的成员，一个团队一个key／value对
                NSArray *allMems = [allTeamDic objectForKey:teamNa];
                 [self setMembersWithArr:allMems];
            }
        }
        
#pragma mark --无所属团队的申请人员解析
        NSArray *allMemsArr = [responseDic objectForKey:@"eventNotTeamUser"];
        if (allMemsArr.count != 0) {
            [self setMembersWithArr:allMemsArr];
        }
        
        //等待网络请求完成后，回主线程刷新UI
        [self waitLoadApplyView];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //蒙板消失
        [hud hide:YES];
       
    }];
    
}

#pragma mark --根据数组，给model赋值，填充数据源
-(void)setMembersWithArr:(NSArray *)allMem
{
    //表示有无团队参赛人员
    for (NSString *memjsonStr in allMem) {
        NSData *memData = [memjsonStr dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *memInfo = [NSJSONSerialization JSONObjectWithData:memData options:(NSJSONReadingMutableContainers) error:nil];
        PersoListModel *model = [[PersoListModel alloc] initWithInforDic:memInfo];
        [self.Person_ary addObject:model];
    }

}

- (void)waitLoadApplyView {
    if (self.segmentedControl.selectedSegmentIndex == 2) {
        [_applyView reloadData];
        [self addSubview:self.applyView];
    }
    
    
}



#pragma mark - LazyLoading
- (UIView *)mapView {
    if (!_mapView) {
        _mapView = [[AGSMapView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_segmentedControl.frame) + KMargin, self.frame.size.width, self.frame.size.height - CGRectGetMaxY(_segmentedControl.frame) - KMargin)];
        
    }
    return _mapView;
}


- (UITableView *)applyView {
    if (!_applyView) {
        _applyView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_segmentedControl.frame) + KMargin, self.frame.size.width, self.frame.size.height - CGRectGetMaxY(_segmentedControl.frame) - KMargin-64) style:(UITableViewStylePlain)];
        _applyView.dataSource = self;
        _applyView.delegate = self;
        _applyView.tableFooterView = [[UIView alloc]init];
        //注册cell
        [self.applyView registerClass:[ApplyTableViewCell class] forCellReuseIdentifier:kApplyTableCellIdentifier];
        
        _applyView.backgroundColor = [UIColor whiteColor];
    }
    return _applyView;
}



#pragma mark - segmentedControl被点击
- (void)NoBeginViewSegmentedControlIsClicked:(UISegmentedControl *)sender {
    if ([self.delegate respondsToSelector:@selector(rightNaviShow:)]) {
        [self.delegate rightNaviShow:sender.selectedSegmentIndex];
    }
    //设置选中的index的背景色
    [self setSegmentBG:_segmentedControl.selectedSegmentIndex andTotal:titleArray.count];
    
    if (_segmentedControl.selectedSegmentIndex == 0) {
        
        [_applyView removeFromSuperview];
        [_scoreWeb removeFromSuperview];
        [_mapView setHidden:NO];
        
    } else if (_segmentedControl.selectedSegmentIndex == 1) {
        [_mapView setHidden:YES];
        [_applyView removeFromSuperview];
        if (![singleton.string isEqualToString:@"9002"]) {
            singleton.userid = @"-1";
        }
        NSString *str = [NSString stringWithFormat:@"%@/wap/event_repeater_ranking?eventId=%@&userId=%@",localRequestUrl,singleton.eventId,singleton.userid];
      //  NSString *str = @"http://www.baidu.com";
        NSURL *url = [NSURL URLWithString:str];
        if (!_scoreWeb) {
            _scoreWeb = [[UIWebView alloc]initWithFrame: CGRectMake(0, CGRectGetMaxY(_segmentedControl.frame) + KMargin, self.frame.size.width, self.frame.size.height - CGRectGetMaxY(_segmentedControl.frame) - KMargin-64)];
        }
        _scoreWeb.delegate = self;
        [self addSubview:_scoreWeb];
        [ _scoreWeb loadRequest:[NSURLRequest requestWithURL:url]];
        
    } else if (_segmentedControl.selectedSegmentIndex == 2) {
        
        [_mapView setHidden:YES];
        [_scoreWeb removeFromSuperview];
        [self.Person_ary removeAllObjects];
        //获取数据
       // [self getApplyerListFromServer];
        [self testGetAppliers];
        
    }
}

#pragma mark 点击segmentControl，切换底图
-(void)setSegmentBG:(long)index andTotal:(long)total
{
    for (long i=0; i<total; i++) {
        NSString *imgName = [NSString stringWithFormat:@"gamemanager_tv%ld_no",i+1];
        NSString *imgNameY = [NSString stringWithFormat:@"gamemanager_tv%ld_yes",i+1];
        if (index == i) {
            [_segmentedControl setImage:[[UIImage imageNamed:imgNameY] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forSegmentAtIndex:i];
            continue;
        }
        [_segmentedControl setImage:[[UIImage imageNamed:imgName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forSegmentAtIndex:i];
    }
}

//设置成绩列表数组的值
-(void)setWithAllScore:(NSArray *)thArr my:(PersonScoreModel *)myModel andNumber:(int)count
{
    self.hasScoreArr = thArr;
    self.myScoreModel = myModel;
    self.numberOfHasScore = count;
}

-(void)getDataFromMyEventProgressVC
{
    NSLog(@"设置排名");
    //先计算出自己的排名
    int selfRanking = -1;
    int i;
    if (_myScoreModel != nil) {
        for (i=0; i<_numberOfHasScore; i++) {
            PersonScoreModel *model= (PersonScoreModel *)[ _hasScoreArr objectAtIndex:i];
            if ([_myScoreModel.userId intValue] == [model.userId intValue]) {
                selfRanking = i+1;// 纪录自己的排名，排名是下标＋1
            }
        }
        
    }
    
    [self setRankingMarks:selfRanking];
}

#pragma mark－在地图上显示排名
-(void)setRankingMarks:(int)selfR
{
    [_personRankLayer removeAllGraphics];
    
    //有成绩人数<=15人，全部显示(不区分自己在当前点有没有成绩)
    if (_hasScoreArr.count<16) {
        [self displayRankExceptSelf:_numberOfHasScore];
        return;
    }
    
    //有成绩人数>15人，
    //0. 自己无排名, 显示前15名
    if (selfR == -1) {
        [self displayRankExceptSelf:15];
        return;
    }
    //1. 自己排名<10,显示前十名
    if (selfR < 11) {
        [self displayRankExceptSelf:10];
        return;
    }
    
    //2.自己排名 >10 并且 <＝15 ，显示15名
    if (selfR >10 && selfR <16) {
        [self displayRankExceptSelf:15];
        return;
    }
    
    //自己排名 > 15，先显示前十，后面逻辑再区分
    [self displayRankExceptSelf:10];
    
    //3.自己排名 >15 并且 排名＋2 < 有成绩的总人数，显示前十名，外加自己前2 后2
    if (selfR +2 < _numberOfHasScore) {
        PersonScoreModel *model1= (PersonScoreModel *)[_hasScoreArr objectAtIndex:selfR -3];
        AGSGraphic *graphic1 = [self graphicWithPerson:model1 andTop:selfR-2];
        [self.personRankLayer addGraphic:graphic1];
        
        PersonScoreModel *model2= (PersonScoreModel *)[_hasScoreArr objectAtIndex:selfR -2];
        AGSGraphic *graphic2 = [self graphicWithPerson:model2 andTop:selfR-1];
        [self.personRankLayer addGraphic:graphic2];
        
        PersonScoreModel *model3= (PersonScoreModel *)[_hasScoreArr objectAtIndex:selfR];
        AGSGraphic *graphic3 = [self graphicWithPerson:model3 andTop:selfR+1];
        [self.personRankLayer addGraphic:graphic3];
        
        PersonScoreModel *model4= (PersonScoreModel *)[_hasScoreArr objectAtIndex:selfR+1];
        AGSGraphic *graphic4 = [self graphicWithPerson:model4 andTop:selfR+2];
        [self.personRankLayer addGraphic:graphic4];
        return;
    }
    
    //4.自己排名 >15 并且 排名＋2 > 有成绩的总人数，显示前十名，外加有成绩的人总最后数5位显示
    for (int i = _numberOfHasScore-1; i>_numberOfHasScore-6; i--) {
        PersonScoreModel *model= (PersonScoreModel *)[_hasScoreArr objectAtIndex:i];
        if (selfR == i+1) {
            continue;//排除自己的排名显示
        }
        AGSGraphic *graphic = [self graphicWithPerson:model andTop:i+1];
        [self.personRankLayer addGraphic:graphic];
    }
    
}


#pragma mark 加载地图
-(void)loadMapView
{
    //对地图做一些处理，展示地图
    //1.判断有没有缓存的地图，有缓存的地图，加载缓存的地图 2.无缓存的地图，判断有网没网，有网加载有线地图，没网提示没网
    NSString *cachesPath = [FileDownloadTool getTheCachePath];
    cachesPath = [cachesPath stringByAppendingString:@"/create_scenic_area_info/Basic.tpk"];
    //        NSLog(@"cachePath = %@",cachesPath);
    
    MapInfo *info = [MapInfo shareMapInfo];
    BOOL mapExist = [FileDownloadTool whetherFileExist:cachesPath];
    if (mapExist) {
        AGSLocalTiledLayer* layer = [AGSLocalTiledLayer localTiledLayerWithPath:cachesPath];
        [self.mapView addMapLayer:layer withName:@"base Tiled Layer"];
        info.isOfflineLoad = YES;
    }
    else
    {
        info.isOfflineLoad = NO;
        
        //显示地图
        NSString *baseMapUrl =@"http://218.108.4.35:6080/arcgis/rest/services/Basic/MapServer";
        AGSTiledMapServiceLayer *baseMap =[[AGSTiledMapServiceLayer alloc]initWithURL:[NSURL URLWithString:baseMapUrl]];
        //地图添加底图
        [self.mapView addMapLayer:baseMap withName:@"TiledMapLayer"];
    }
    //设置地图可两指捏拉缩放
    self.mapView.allowRotationByPinching = YES;
    //设置代理
    self.mapView.touchDelegate = self;
    self.mapView.layerDelegate =self;
    
    //设置地图可环绕
    [self.mapView enableWrapAround];
    //去掉网格线，将网格线的宽度设为0
    self.mapView.gridLineWidth = 0;
    //设置地图的背景色
    self.mapView.backgroundColor = [UIColor whiteColor];
    
    [self addSubview:self.mapView];
    
    
    
}

#pragma mark 地图代理事件
-(void)mapViewDidLoad:(AGSMapView *)mapView
{
    
    
    self.loadFinished = YES;
    MapInfo *info = [MapInfo shareMapInfo];
    info.mapSpatialReference = self.mapView.spatialReference;
    
    //注册通知，地图一显示就开始定位
    //Listen to KVO notifications for map gps's autoPanMode property
    [self.mapView.locationDisplay addObserver:self
                                   forKeyPath:@"location"
                                      options:(NSKeyValueObservingOptionNew)
                                      context:NULL];
    //Start the map's gps if it isn't enabled already
    if(!self.mapView.locationDisplay.dataSourceStarted)
        [self.mapView.locationDisplay startDataSource];
    
    self.mapView.locationDisplay.autoPanMode = AGSLocationDisplayAutoPanModeDefault;
    
    self.mapView.locationDisplay.wanderExtentFactor = 0.75;
    
    NSError *error;
    if (!info.isOfflineLoad) {
        //给地图添加上游步道,离线地图已经做好，这是有线情况，离线已经加好了
        NSString *filePath = [[NSBundle mainBundle]pathForResource:@"na" ofType:@"geodatabase"];
        AGSGDBGeodatabase *gdb = [[AGSGDBGeodatabase alloc]initWithPath:filePath error:&error];
        for (AGSFeatureTable* fTable in gdb.featureTables) {
            
            if ([fTable hasGeometry] && [fTable.tableName isEqualToString:@"游步道"]==YES) {
                
                [self.mapView addMapLayer:[[AGSFeatureTableLayer alloc]initWithFeatureTable:fTable]];
            }
        }
    }
    
    //提前添加底图上的中继点的图层（relay point）
    NSArray *modelA = [Manager relayModelArrByJsonFile];
    self.relayLayer = [AGSGraphicsLayer graphicsLayer];
    [self.mapView addMapLayer:self.relayLayer withName:@"relayLayer"];
    [self.relayLayer addGraphics:[Manager graphicArrByAttracModelArr:modelA andType:@"100"]];
    
    
    //提前添加地图上的路线图层
    self.routeLayer = [AGSGraphicsLayer graphicsLayer];
    [self.mapView addMapLayer:self.routeLayer withName:@"routeGraphicsLayer"];
    if ([singleton.eventType intValue] == 0 || [singleton.eventType intValue] == 1) {
        //访问接口，拿到官方线路的中继点坐标，标出大致线路
        if (self.officalEvR!=nil) {
             [self.routeLayer addGraphic:self.officalEvR];
//            AGSGraphicsLayer *starEnd = [AGSGraphicsLayer graphicsLayer];
//            [self.mapView addMapLayer:starEnd withName:@"startEndLayer"];
            [self.routeLayer addGraphic:self.evnStart];
            [self.routeLayer addGraphic:self.evnEnd];
        }
       
    }else
    {
        NSArray *graphicArr =[FMDataBaseTool getGraphicArr:singleton.routeId];
        [self.routeLayer addGraphics:graphicArr];
    }
    
    
    
    //提前添加个人排名的图层
    self.personRankLayer = [AGSGraphicsLayer graphicsLayer];
    [self.mapView addMapLayer:self.personRankLayer withName:@"personRankLayer"];
    
    
    [self.mapView zoomToScale:70000 animated:YES];//控制地图的显示比例，比例越大，地图越小，地点看的越补清楚
    [[NSNotificationCenter defaultCenter] postNotificationName:@"setScoreOn" object:nil];
}



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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ApplyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kApplyTableCellIdentifier forIndexPath:indexPath];
    NSLog(@"ary:%@", _Person_ary);
    PersoListModel *apply = (PersoListModel *)_Person_ary[indexPath.row];
    [cell show:apply];
    
    return cell;
    
}

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



//显示名数，根据传入参数选择显示十五个，或者前十，不包括自己
-(void)displayRankExceptSelf:(int)rankNumber
{
    int i;
    for (i=0; i<rankNumber; i++) {
        PersonScoreModel *model= (PersonScoreModel *)[_hasScoreArr objectAtIndex:i];
        if ([_myScoreModel.userId intValue] == [model.userId intValue]) {
            continue;
        }
        AGSGraphic *graphic = [self graphicWithPerson:model andTop:i+1];
        [self.personRankLayer addGraphic:graphic];
    }
}


#pragma mark 创建复合型大头针，在图片上加数字，排名，排名是按在集合里面的排列位置来的
-(AGSGraphic *)graphicWithPerson:(PersonScoreModel *)personScore andTop:(int)eventTop
{
    AGSPoint *geometery = [[AGSPoint alloc]initWithX:[personScore.pointX doubleValue] y:[personScore.pointY doubleValue] spatialReference:[AGSSpatialReference wgs84SpatialReference]];
    //gps获取的坐标转换成当前地图坐标系的坐标点
    geometery =(AGSPoint *) [[AGSGeometryEngine defaultGeometryEngine] projectGeometry:geometery toSpatialReference:self.mapView.spatialReference];
    
    AGSCompositeSymbol *cs = [AGSCompositeSymbol compositeSymbol];
    AGSPictureMarkerSymbol *pt=[AGSPictureMarkerSymbol pictureMarkerSymbolWithImageNamed:@"attractionssymbol"];
    [cs addSymbol:pt];
    
    AGSTextSymbol *ts = [[AGSTextSymbol alloc] initWithText:[NSString stringWithFormat:@"%d", eventTop] color:[UIColor blackColor]] ;
    ts.vAlignment = AGSTextSymbolVAlignmentMiddle;
    ts.hAlignment = AGSTextSymbolHAlignmentCenter;
    ts.fontSize	= 16;
    [cs addSymbol:ts];
    
    AGSTextSymbol *name = [[AGSTextSymbol alloc] initWithText:personScore.userName color:[UIColor blackColor]] ;
    name.fontFamily = @"Heiti SC";//如果显示中文的话，必须要加上这句话，设置中文的字体，不然显示不了
    name.vAlignment = AGSTextSymbolVAlignmentTop;
    name.hAlignment = AGSTextSymbolHAlignmentLeft;
    [name setOffset:CGPointMake(20.0, 10.0)];
    name.fontSize	= 12;
    [cs addSymbol:name];
    
    AGSGraphic *graphic = [[AGSGraphic alloc]initWithGeometry:geometery symbol:cs attributes:nil];
    
    return graphic;
}


-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSLog(@"reques .url = %@",request.URL.absoluteString);
    if ([request.URL.absoluteString containsString:@"event_repeater_ranking_user_info?eventId="]) {
        if ([self.delegate respondsToSelector:@selector(pushToEachScoreV:)]) {
            [self.delegate pushToEachScoreV:request.URL.absoluteString];
        }
        return NO;
    }
    return YES;
}


-(void)dealloc
{
    if(self.mapView.locationDisplay.dataSourceStarted){
        [self.mapView.locationDisplay stopDataSource];
        self.mapView.rotationAngle = 0;
        
    }
    
    [self.mapView removeMapLayer:self.routeLayer];
    [self.mapView removeMapLayer:self.relayLayer];
    [self.mapView removeMapLayer:self.personRankLayer];
    self.personRankLayer = nil;
    self.relayLayer = nil;
    self.routeLayer = nil;
    self.hasScoreArr = nil;
    self.mapView = nil;
    self.scoreWeb = nil;
    
}
/**之前显示成绩页面是用的collectionview，现在用webview
 - (UICollectionViewFlowLayout *)layout {
 if (_layout == nil) {
 _layout = [[UICollectionViewFlowLayout alloc] init];
 _layout.itemSize = CGSizeMake((self.scoreView.frame.size.width - 2*KMargin)/2,80);
 //行间距
 _layout.minimumLineSpacing = 5;
 //列间距
 _layout.minimumInteritemSpacing = 10;
 
 }
 return _layout;
 }
 
 - (UICollectionView *)scoreView {
 if (!_scoreView) {
 _scoreView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_segmentedControl.frame) + KMargin, self.frame.size.width, self.frame.size.height - CGRectGetMaxY(_segmentedControl.frame) - KMargin-64) collectionViewLayout:self.layout];
 //注册cell
 [_scoreView registerClass:[ScoreCollectionCell class] forCellWithReuseIdentifier:kScoreCollectionCellIdentifier];
 
 _scoreView.dataSource = self;
 _scoreView.delegate = self;
 
 _scoreView.backgroundColor = [UIColor colorWithRed:250/255. green:250/255. blue:250/255. alpha:0.9];
 }
 return _scoreView;
 }
 
 
 #pragma mark - UICollectionViewDataSource
 - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
 return self.scoreArr.count;
 }
 
 
 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
 ScoreCollectionCell *cell =
 [collectionView dequeueReusableCellWithReuseIdentifier:kScoreCollectionCellIdentifier forIndexPath:indexPath];
 [cell setWithScoreModel:[self.scoreArr objectAtIndex:indexPath.row]];
 return cell;
 }
 */

#pragma mark 从服务器获取申请人员信息
/*
 -(void)getApplyerListFromServer
 {
 NSString *str_sign = [NSString stringWithFormat:@"{\"organizerId\":\"%@\",\"eventId\":\"%@\"}eventApplyUserVerify",@"", singleton.eventId];
 
 
 NSString *sign = [MyMD5 md5:str_sign];
 
 NSString *para_data = [NSString stringWithFormat:@"{\\\"organizerId\\\":\\\"%@\\\",\\\"eventId\\\":\\\"%@\\\"}", @"", singleton.eventId];
 NSString *parameter = [NSString stringWithFormat:@"{\"sign\":\"%@\",\"data\":\"%@\",\"partner\":\"eventApplyUserVerify\",\"code\":\"getEventApplyUserList\",\"key\":\"eventApplyUserVerify\"}",sign, para_data];
 
 NSDictionary *paramentDic = [[NSDictionary alloc]initWithObjectsAndKeys:parameter,@"out_msg", nil];
 
 //注: POST请求的参数不写在URL的后面.
 // NSString *requestString = @"http://gwms.517gts.com/terminal/eventApplyUserVerify";
 NSString *requestString = [NSString stringWithFormat:@"%@/terminal/eventApplyUserVerify",localRequestUrl];
 // 初始化Manager
 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
 
 // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
 manager.responseSerializer = [AFHTTPResponseSerializer serializer];
 
 [manager POST:requestString parameters:paramentDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
 
 } progress:^(NSProgress * _Nonnull uploadProgress) {
 
 } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
 // 请求成功，解析数据
 //       NSLog(@"response=%@", responseObject);
 NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
 //        NSLog(@"str = %@",str);
 
 NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
 //        NSLog(@"dic=%@",dic);
 if (!dic)
 return;
 
 NSString *result_data=[dic objectForKey:@"result_data"];
 NSLog(@"result_data=%@",result_data);
 if([result_data isEqualToString:@""])
 return;
 
 //字符串再转化成json
 NSData *JSONData = [result_data dataUsingEncoding:NSUTF8StringEncoding];
 NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
 NSArray *arr = [responseJSON objectForKey:@"result"];
 if (arr.count==0)
 return;
 
 for (NSString *dic in arr) {
 NSData *JSONData1 = [dic dataUsingEncoding:NSUTF8StringEncoding];
 NSDictionary *responseJSON1 = [NSJSONSerialization JSONObjectWithData:JSONData1 options:NSJSONReadingMutableLeaves error:nil];
 
 PersoListModel *model = [[PersoListModel alloc] initWithInforDic:responseJSON1];
 
 [self.Person_ary addObject:model];
 }
 
 //等待网络请求完成后，回主线程刷新UI
 [self waitLoadApplyView];
 
 } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
 // 请求失败
 NSLog(@"%@", [error localizedDescription]);
 }];
 }
 */


 #pragma mark 在地图上显示排名等信息，前十名，自己排名前后共五名
/*
 -(void)setRankingMarksOnMap
 {
 
 [_personRankLayer removeAllGraphics];
 
 //添加自己的排名。
 //    AGSGraphic *graphic = [self graphicWithPerson:_myScoreModel];
 //    [self.personRankLayer addGraphic:graphic];
 
 //有成绩人数不足15人，全部显示
 if (_hasScoreArr.count<16) {
 [self displayRankExceptSelf:(int)_hasScoreArr.count];
 return;
 }
 
 //如果排名大于10小于14，显示15个人
 if ([_myScoreModel.eventTop intValue] >10 && [_myScoreModel.eventTop intValue] <14) {
 [self displayRankExceptSelf:15];
 return;
 }
 
 [self displayRankExceptSelf:10];
 
 if (_myScoreModel.eventTop == nil || [_myScoreModel.eventTop intValue] <11) {
 return;//如果没有成绩，或者自己的排名小于10，直接显示前十名
 }
 //自己排名＋2大于或等于总人数，显示前十名后，从最后显示5名
 if ((unsigned long)[_myScoreModel.eventTop intValue]+2 > _hasScoreArr.count || (unsigned long)[_myScoreModel.eventTop intValue]+2 == _hasScoreArr.count) {
 int i;
 for (i=_numberOfHasScore-1; i<_numberOfHasScore - 5; i--) {
 PersonScoreModel *model= (PersonScoreModel *)[_hasScoreArr objectAtIndex:i];
 AGSGraphic *graphic = [self graphicWithPerson:model];
 [self.personRankLayer addGraphic:graphic];
 }
 }
 
 //自己排名＋2小于总人数，显示前十名后，以自己排名为中心，前后各显示2名
 if ((unsigned long)[_myScoreModel.eventTop intValue]+2 < _hasScoreArr.count) {
 PersonScoreModel *model= (PersonScoreModel *)[_hasScoreArr objectAtIndex:[_myScoreModel.eventTop intValue]-3];
 AGSGraphic *graphic = [self graphicWithPerson:model];
 [self.personRankLayer addGraphic:graphic];
 
 model= (PersonScoreModel *)[_hasScoreArr objectAtIndex:[_myScoreModel.eventTop intValue]-2];
 graphic = [self graphicWithPerson:model];
 [self.personRankLayer addGraphic:graphic];
 
 model= (PersonScoreModel *)[_hasScoreArr objectAtIndex:[_myScoreModel.eventTop intValue]];
 graphic = [self graphicWithPerson:model];
 [self.personRankLayer addGraphic:graphic];
 
 model= (PersonScoreModel *)[_hasScoreArr objectAtIndex:[_myScoreModel.eventTop intValue]+1];
 graphic = [self graphicWithPerson:model];
 [self.personRankLayer addGraphic:graphic];
 }
 
 }
 */



/////////////////////////////////////////
/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */




@end
