//
//  Manager.m
//  gaotingshan
//
//  Created by Mac Book DQ02 on 16/6/12.
//  Copyright © 2016年 Xu Mengzhu. All rights reserved.
//

#import "Manager.h"

@implementation Manager

+(AFHTTPSessionManager *)initSessionManager{
    if (sessionManager == nil) {
        sessionManager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        sessionManager.responseSerializer=[AFHTTPResponseSerializer serializer];
    }
    return sessionManager;
}

+(void)startNoticeInternetStatus
{
    //1.创建网络状态监测管理者
    AFNetworkReachabilityManager *manger = [AFNetworkReachabilityManager sharedManager];
    
    //2.监听改变
    [manger setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        /*
         AFNetworkReachabilityStatusUnknown          = -1,
         AFNetworkReachabilityStatusNotReachable     = 0,
         AFNetworkReachabilityStatusReachableViaWWAN = 1,
         AFNetworkReachabilityStatusReachableViaWiFi = 2,
         */
        MapInfo *info = [MapInfo shareMapInfo];
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                info.internetStatus =AFNetworkReachabilityStatusUnknown;
                NSLog(@"未知");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                info.internetStatus =AFNetworkReachabilityStatusNotReachable;
                NSLog(@"没有网络");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                info.internetStatus =AFNetworkReachabilityStatusReachableViaWWAN;[Manager loginRequestWithUsernameAndPassword];
                NSLog(@"3G|4G");
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                info.internetStatus = AFNetworkReachabilityStatusReachableViaWiFi;
                NSLog(@"WiFi");
                [Manager loginRequestWithUsernameAndPassword];
                break;
            default:
                break;
        }
    }];
    
    
    [manger startMonitoring];
}

+(BOOL)setNetStatusOnView:(UIView *)view
{
    MapInfo *info = [MapInfo shareMapInfo];
    if (info.internetStatus == AFNetworkReachabilityStatusNotReachable) {
        [FileDownloadTool alert:@"网络无连接或超时" view:view];
        return NO;
    }
    else
    {
        return YES;
    }
}

#pragma mark 网络请求，登录请求
+(void)loginRequestWithUsernameAndPassword
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *username = [defaults objectForKey:@"userName"];
    NSString *userpwd = [defaults objectForKey:@"userPwd"];
    if (username == nil) {
        return;
    }
    NSString *loginType = @"2";
    NSString *origin = @"phone";
    NSString *type = @"Ios";
    NSString *key = @".5Xf_01KXd352s177Jx3wxXc074poII";
    NSString *time = @"yyyyMMddHHmmss";
    //sign 需要MD5加密方式. 传入字符串（time+type+key），需要用到字符串拼接。
    NSString *str = [[NSString alloc] initWithFormat:@"%@%@%@", time,type, key];
    NSString *sign = [MyMD5 md5:str];
    
    NSDictionary *dicx = @{@"type" : type, @"key" : key, @"time" : time, @"sign" : sign, @"login_type" : loginType, @"name" : username, @"pwds" : userpwd, @"origin" : origin};
    //    [MBProgressHUD showMessage:@"正在加载"];
    // 1.获得请求管理者
  //  AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
   
    // 2.发送POST请求
    NSString *postStr = [NSString stringWithFormat:@"%@/terminal/login",localRequestUrl];
    [[Manager initSessionManager] POST:postStr parameters:dicx constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"response=%@",responseObject);
        if (responseObject == nil || [responseObject bytes] == 0) {
            return;
        }
        //单例赋值
        Singleton *singleton = [Singleton defaultSingleton];
        singleton.sesskey = @"";
        NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        if (rootDic == nil) {
            return;
        }
#pragma 走在这一步，会崩溃，为什么？？？
        if ([rootDic objectForKey:@"data"] != nil && [[rootDic objectForKey:@"data"] class] != [NSNull class]) {
            singleton.reallyName = rootDic[@"data"][@"realName"];
            singleton.string = rootDic[@"status"];
            singleton.headImgUrl = rootDic[@"data"][@"headImgUrl"];
            singleton.nickName = rootDic[@"data"][@"nickName"];
            singleton.increased = rootDic[@"data"][@"increased"];
            singleton.weight = rootDic[@"data"][@"weight"];
            singleton.sex = rootDic[@"data"][@"sex"];
            singleton.deviceSn = rootDic[@"data"][@"deviceSn"];
            singleton.watchSn = rootDic[@"data"][@"braceletSn"];
        }
       
        if ([singleton.watchSn isEqualToString:@""]) {
            NSLog(@"手表为空");
        }
        
        singleton.userid = rootDic[@"userid"];
        singleton.status = rootDic[@"status"];
        
        //以下是对responseObject[@"sesskey"]字段的处理。
        NSString *str = [rootDic[@"sesskey"] stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        NSInteger count = str.length/76 + 1;
        NSMutableArray *mAry = [[NSMutableArray alloc] initWithCapacity:0];
        int index = 0;
        for (int i = 1; i <= count; i++) {
            if (i < count) {
                NSRange range = {index, 76};
                NSString *string = [str substringWithRange:range];
                index = index + 76 + 1;
                //                    NSLog(@"index:%d", index);
                [mAry addObject:string];
            }
            if (i == count) {
                //                    NSLog(@"index:%d", index);
                NSRange range = {index, str.length - index};
                NSString *string = [str substringWithRange:range];
                [mAry addObject:string];
            }
        }
        //            NSLog(@"mAry:%@", mAry);
        for (NSInteger i = 0; i < mAry.count; i++) {
            singleton.sesskey = [singleton.sesskey stringByAppendingString:mAry[i]];
        }
        NSLog(@"singleton.sesskey:%@", singleton.sesskey);
        [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"changeLeftVCLayout" object:nil]];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"登录失败");
        
        
    }];
    
}



//判断手机号
+(BOOL)checkTelNumber:(NSString*)telNumber
{
    NSString*pattern = @"^1+[3578]+\\d{9}";
    
    NSPredicate*pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern];
    
    BOOL isMatch = [pred evaluateWithObject:telNumber];
    
    return isMatch;
    
}


#pragma mark 上传地点坐标(appdelegate里面程序进入一直上传当前位置)
+(void)upoadLocationToServer:(CLLocation *)location
{
    Singleton *single = [Singleton defaultSingleton];
   // NSLog(@"single.user_id = %@",single.userid);
    /*
    AFHTTPSessionManager *manager= [Manager initSessionManager];
    
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    */
    
    NSDictionary *parameterDic = [[NSDictionary alloc]initWithObjectsAndKeys:single.userid,@"user_id",single.reallyName,@"user_name",[NSString stringWithFormat:@"%f",location.coordinate.longitude],@"axis_x",[NSString stringWithFormat:@"%f",location.coordinate.latitude],@"axis_y", nil];
    NSString *postStr = [NSString stringWithFormat:@"%@/terminal/upload/eventUserXyzLog",localRequestUrl];
    [[Manager initSessionManager] POST:postStr parameters:parameterDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
    //    NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
       // NSLog(@"response = %@",str);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"error = %@",error);
    }];
}


#pragma mark 景点详情收藏按钮点击，判断未登录跳转到登录界面，登录成功，登录界面dismiss掉
+(void)collectionBtnClicked:(UIViewController *)vc andAreaId:(NSString *)areaId
{
    Singleton *singleton = [Singleton defaultSingleton];
    if ([singleton.string isEqualToString:@"9002"]) {
        [Manager requestForCollection:vc andAreaId:areaId];
    }else
    {
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        loginVC.skipFrom = @"fromAttractionCollection";
        loginVC.vc= vc;
        loginVC.areaId = areaId;
        
        UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:loginVC];
        [vc presentViewController:naVC animated:NO completion:nil];
    }
    
}

#pragma mark 收藏的请求
+(void)requestForCollection:(UIViewController *)vc andAreaId:(NSString *)areaId
{
    Singleton *singleton = [Singleton defaultSingleton];
    
    NSDictionary *parameter = [[NSDictionary alloc]initWithObjectsAndKeys:singleton.userid,@"userId",areaId,@"areaId", nil];
    
    NSString *requestString = [NSString stringWithFormat:@"%@/terminal/scenic/area_favorite",localRequestUrl];
    /*
    // 初始化Manager
    AFHTTPSessionManager *manager = [Manager initSessionManager];
    
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    */
    
    [[Manager initSessionManager] POST:requestString parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"collection= %@",str);
        if ([str isEqualToString:@"111"]) {
            [FileDownloadTool alert:@"此前已收藏" view:vc.view];
        }else{
            [FileDownloadTool alert:@"新收藏" view:vc.view];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error=%@",error);
        [FileDownloadTool alert:@"收藏失败" view:vc.view];
    }];
    
}

#pragma mark 分享到新浪微博事件


#pragma mark --分享到朋友圈事件
+(void)shareToWXTimeLine:(NSString *)sender
{
    //朋友圈分享
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = @"智慧皋亭山－－赛事成绩";
    message.description = @"分享结果";
    
    
    [message setThumbImage:[UIImage imageNamed:@"1111"]];
    
    WXWebpageObject *pageObj = [WXWebpageObject object];
    NSString *str = [NSString stringWithFormat:@"%@&shareFlag=1",sender];
    pageObj.webpageUrl = str;
    message.mediaObject = pageObj;
    
    SendMessageToWXReq *reg = [[SendMessageToWXReq alloc]init];
    reg.bText = NO;
    reg.message = message;
    reg.scene = WXSceneTimeline;
    
    [WXApi sendReq:reg];
}


/**新改**/
#pragma mark --从服务器获取景点信息，放在图层上（搜索，电子导游标签，经典详情地图公用接口，传的参数不一样）
+(void)getInformationForType:(NSDictionary *)parameter andBlock:(modelBlock)modBlock
{
    NSString *postStr = [NSString stringWithFormat:@"%@/terminal/findMapAreaInfoByWhere",localRequestUrl];
    
    // 初始化Manager
    AFHTTPSessionManager *manager = [Manager initSessionManager];
    
    // 不加上这句话，会报“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) {
        NSMutableArray *modelArr = [[NSMutableArray alloc]initWithCapacity:10];
        NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        
        NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSArray *secondStr = [dic objectForKey:@"result"];
        
        NSLog(@"secondArr = %@",secondStr);
        for (NSString *innerStr in secondStr) {
            NSData *innerData = [innerStr dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *innerDic = [NSJSONSerialization JSONObjectWithData:innerData options:(NSJSONReadingMutableContainers) error:nil];
            if ([[innerDic objectForKey:@"potionX"]isEqualToString:@""]) {
                continue;
            }
            MarkInfoModel *model = [[MarkInfoModel alloc]init];
            model.objCode = [innerDic objectForKey:@"code"];
            model.objName = [innerDic objectForKey:@"name"];
            model.objImgUrl = [innerDic objectForKey:@"imagePath"];
            model.objAudioUrl = [innerDic objectForKey:@"audioPath"];
            model.objPoint = CGPointMake([[innerDic objectForKey:@"potionX"] doubleValue], [[innerDic objectForKey:@"potionY"] doubleValue]);
            model.objType = [innerDic objectForKey:@"type"];
            model.keyword = [innerDic objectForKey:@"keyword"];
            [modelArr addObject:model];
        }
        
        NSLog(@"modelArr=%@",modelArr);
   
        modBlock(modelArr);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"failure=%@",error);
    }];
    
}

/**0714新改**/
#pragma mark -电子导游标签页，通过获取的model数组得到graphic数组
+(NSArray *)spotsGraphicArrWithModelArr:(NSArray *)modelArr
{
    NSMutableDictionary *graphicAttributes;
    NSMutableArray *graphicArr =[[NSMutableArray alloc]initWithCapacity:10];
    for (MarkInfoModel *model in modelArr) {
        AGSPoint *point =[[AGSPoint alloc]initWithX:model.objPoint.x y:model.objPoint.y spatialReference:[AGSSpatialReference wgs84SpatialReference]];
        AGSPoint *mapPoint = [FMDataBaseTool transferToMapViewSpatialreference:point];//坐标系转换
        AGSPictureMarkerSymbol *pt=[AGSPictureMarkerSymbol pictureMarkerSymbolWithImageNamed:[NSString stringWithFormat:@"type_%@.png",model.objType]];
        
        if ([model.keyword isEqualToString:@""]) {
            //给偏好属性赋值的时候，如果是空值，不能直接赋值，所以给了一个任意值
            model.keyword = @"NW";
        }
        //初始化graphic的Attributes，给graphic架上标志位，用于区分
        graphicAttributes =[[NSMutableDictionary alloc]initWithObjectsAndKeys:model.objImgUrl, @"graphicImg",
                            model.objName, @"graphicName",
                            model.objCode, @"graphicCode",
                            model.objAudioUrl, @"graphicAudio",
                            model.objType, @"graphicType",
                            model.keyword,@"graphicKey",
                            nil];
        
        AGSGraphic * graphic = [[AGSGraphic alloc]initWithGeometry:mapPoint symbol:pt attributes:graphicAttributes];
        [graphicArr addObject:graphic];
    }
    return graphicArr;
    
}



/**新改底图**/
#pragma mark -1.将游哉皋亭的model数组里面的，全部弄成textsymbol，加到地图的底图上
#pragma mark -2.将停车场的数组放在地图上
#pragma mark -3.将30个中继点用图片标记在赛事过程管理的地图显示页上（一边查看赛事，一边可以看到经过哪些中继点）。

+(NSArray *)graphicArrByAttracModelArr:(NSArray *)modelArr   andType:(NSString *)type
{
    NSMutableArray *graphicArr =[[NSMutableArray alloc]initWithCapacity:100];
    for (MarkInfoModel *model in modelArr) {
        AGSPoint *point =[[AGSPoint alloc]initWithX:model.objPoint.x y:model.objPoint.y spatialReference:[AGSSpatialReference wgs84SpatialReference]];
        AGSPoint *mapPoint = [FMDataBaseTool transferToMapViewSpatialreference:point];
        
        if ([type isEqualToString:@"1"]) {
            //把游在皋亭的内容显示在底图上
            AGSTextSymbol *ts = [Manager textSymbolForMapBaseLayer:model];
            
            AGSGraphic * graphic = [[AGSGraphic alloc]initWithGeometry:mapPoint symbol:ts attributes:nil];
            [graphicArr addObject:graphic];
        }else if([type isEqualToString:@"5"])
        {
            //标签点击停车场，显示停车场水滴图标
            AGSCompositeSymbol *cs = [Manager compositeSymbolForParkingObj:model];
            AGSGraphic * graphic = [[AGSGraphic alloc]initWithGeometry:mapPoint symbol:cs attributes:nil];
            [graphicArr addObject:graphic];
        }
        else{
            //赛事管理页面，地图底图加上中继点
            AGSPictureMarkerSymbol *ps =[[AGSPictureMarkerSymbol alloc]initWithImage:[UIImage imageNamed:@"dev"]];
            AGSGraphic * graphic = [[AGSGraphic alloc]initWithGeometry:mapPoint symbol:ps attributes:nil];
            [graphicArr addObject:graphic];
        }
        
    }
    return graphicArr;
}

#pragma mark 创建纯文字symbol，针对底图游在皋亭，用于添加再底图上
+(AGSTextSymbol *)textSymbolForMapBaseLayer:(MarkInfoModel *)model
{
    UIColor *colo = [UIColor colorWithRed:59.0/255.0 green:115.0/255.0 blue:10.0/255.0 alpha:1];
    AGSTextSymbol *ts = [AGSTextSymbol textSymbolWithText:model.objName color:colo];
    ts.vAlignment = AGSTextSymbolVAlignmentTop;
    ts.hAlignment = AGSTextSymbolHAlignmentLeft;
    [ts setOffset:CGPointMake(15.0, 10.0)];
    ts.fontSize =12;
    ts.fontFamily = @"Heiti SC";//如果显示中文的话，必须要加上这句话，设置中文的字体，不然显示不了
    
    return ts;
}

#pragma mark 创建复合型的symbol(针对停车位，创建复合symbol)
+(AGSCompositeSymbol *)compositeSymbolForParkingObj:(MarkInfoModel *)model
{
    UIColor *color = [UIColor colorWithRed:59.0/255.0 green:115.0/255.0 blue:10.0/255.0 alpha:1];
    
    AGSCompositeSymbol *cs = [AGSCompositeSymbol compositeSymbol];
    
    AGSPictureMarkerSymbol *pt=[AGSPictureMarkerSymbol pictureMarkerSymbolWithImageNamed:@"parkingSymbol.png"];
    [cs addSymbol:pt];
    
    NSString *str = [NSString stringWithFormat:@"剩余：%@",model.unComeCount];
    AGSTextSymbol *uncome = [[AGSTextSymbol alloc] initWithText:str color:color] ;
    uncome.fontFamily = @"Heiti SC";//如果显示中文的话，必须要加上这句话，设置中文的字体，不然显示不了
    uncome.vAlignment = AGSTextSymbolVAlignmentTop;
    uncome.hAlignment = AGSTextSymbolHAlignmentLeft;
    [uncome setOffset:CGPointMake(20.0, 10.0)];
    uncome.fontSize	= 12;
    [cs addSymbol:uncome];
    
    AGSTextSymbol *ts = [[AGSTextSymbol alloc] initWithText:model.objName color:color] ;
    ts.fontFamily = @"Heiti SC";//如果显示中文的话，必须要加上这句话，设置中文的字体，不然显示不了
    ts.vAlignment = AGSTextSymbolVAlignmentBottom;
    ts.hAlignment = AGSTextSymbolHAlignmentLeft;
    [ts setOffset:CGPointMake(20.0, 10.0)];
    ts.fontSize	= 12;
    [cs addSymbol:ts];
    
    return cs;
}

#pragma mark 点击景点详情的地图按钮事件，传入当前的控制器还有景点名称，景点code
+(void)spotDetailMapClicked:(UIViewController *)vc andName:(NSString *)spotNa andCode:(NSString *)thCode
{
    GuideMapController *guideVC = [[GuideMapController alloc]init];
    guideVC.fromAttractionMap = YES;
    guideVC.spotCode = thCode;
    guideVC.spotName = spotNa;
    UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:guideVC];
    navi.navigationBar.translucent = YES;
    [vc presentViewController:navi animated:NO completion:nil];
}

#pragma mark 景点详情的导航栏字体渲染设置
+(void)setNaviAttributesWithBlo:(attributeBlock)attrBlock
{
    //改变字体颜色
    NSShadow *shadow = [[NSShadow alloc]init];
    shadow.shadowBlurRadius  = 5;
    shadow.shadowColor = [UIColor darkGrayColor];
    shadow.shadowOffset = CGSizeMake(1, 2);
    
    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    textAttrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
    textAttrs[NSStrokeWidthAttributeName] = @3;
    textAttrs[NSStrokeColorAttributeName] =[UIColor darkGrayColor];
    textAttrs[NSShadowAttributeName] = shadow;
    textAttrs[NSVerticalGlyphFormAttributeName] = @(0);
    attrBlock(textAttrs);
}


#pragma mark ---大部分页面导航栏的基础设置（背景和文字颜色）
+(void)setNavi:(UINavigationBar *)bar
{
    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    textAttrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
    
    [bar setBackgroundImage:[UIImage imageNamed:@"nav_bg"] forBarMetrics:(UIBarMetricsDefault)];
    
    [bar setTitleTextAttributes:textAttrs];
}


#pragma mark 带分类的商业点等名字中有分类，截取字符串（将括号和括号里面的内容截掉）
+(NSString *)deleteCharactersInBrackets:(NSString *)originStr
{
    NSRange foreRange = [originStr rangeOfString:@"("];
    if (foreRange.length!=0) {
        NSRange sufRange;
        sufRange.location = 0;
        sufRange.length = foreRange.location;
        NSString *str = [originStr substringWithRange:sufRange];
        return str;
    }
    return originStr;
}


#pragma mark －－json文件操作，将中继点弄成graphic，再添加到底图上
+(NSArray *)relayModelArrByJsonFile
{
    NSMutableArray *modelArr = [[NSMutableArray alloc]initWithCapacity:50];
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"geometry" ofType:@"json"];//获取文件路径为空，为什么？？
    NSData *jsonData = [NSData dataWithContentsOfFile:filePath];
    NSError *error;
    NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
    NSArray *allObjectArr = [jsonDic objectForKey:@"features"];
    for (NSDictionary *rootDic in allObjectArr) {
        MarkInfoModel *model = [[MarkInfoModel alloc]init];
        model.objName = [rootDic objectForKey:@"name"];
        model.objPoint = CGPointMake([[rootDic objectForKey:@"x"] doubleValue], [[rootDic objectForKey:@"y"] doubleValue]);
        [modelArr addObject:model];
    }
    return modelArr;
}


+(UIWebView *)screenFrameWebview
{
    UIWebView *web = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    [web setUserInteractionEnabled:YES];//是否支持交互
    [web setOpaque:NO]; //opaque是不透明的意思
    [web setScalesPageToFit:YES]; //自动缩放以适应屏幕
    web.scrollView.bounces = NO;
    web.scrollView.showsVerticalScrollIndicator = NO;
    return web;
}

+(void)alipayRequest:(NSDictionary *)parameter orderSpec:(NSString *)orderSpec flag:(int)aliFlag
{
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"duqiangts";
    
    
    NSString *postStr = [NSString stringWithFormat:@"%@/terminal/payment/getAlipaySign",localRequestUrl];
    __block NSString *orderString = nil;
    
    // 1.获得请求管理者
   /* AFHTTPSessionManager *manager = [Manager initSessionManager];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];*/
    
    [[Manager initSessionManager] POST:postStr parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSString *signedString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
       
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
         //   NSLog(@"reslutCallback = %@",resultDic);
            //需要判断支付状态，如果支付成功，需要通知“我的赛事过程管理”页面开始赛事。
            if ([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"9000"] && aliFlag == 2) {
                NSLog(@"支付成功");
                //支付宝回调的结果，表示支付成功,发送通知
                [[NSNotificationCenter defaultCenter] postNotificationName:@"paySucBegin" object:nil];
            }

        }];
    
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error = %@",error);
    }];

}

//使用KVC取值, 没有找到对应的key
- (id)valueForUndefinedKey:(NSString *)key {
    //    NSLog(@"不能识别%@", key);
    return nil;
}

#pragma mark - KVC
//使用KVC赋值, 没有找到对应的key
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
    //NSLog(@"不能识别%@", key);
    
}


//#pragma mark 设置导航栏的右边收藏和分享按钮
//+(NSArray *)setNaviRightItemsOnView:(id)vc andAction:(SEL)action
//{
//    
//    UIBarButtonItem *collectionItem = [Manager rightItemTarget:vc img:@"collection" tag:101 action:(action)];
//    
//    
//    UIBarButtonItem *fixedSpaceBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
//    fixedSpaceBarButtonItem.width = 22;
//    
//    UIBarButtonItem *shareBtnItem = [Manager rightItemTarget:vc img:@"share" tag:102 action:(action)];
//    
//    NSArray *rightBarButtonItems  = @[shareBtnItem,fixedSpaceBarButtonItem,collectionItem];//注意导航栏的右边按钮，按照数组的顺序，从右往左排，所以如果想让按钮放在前面，就要放在数组后面
//    return rightBarButtonItems;
//}
//
//#pragma mark 单个初始化UIBarButtonItem
//+(UIBarButtonItem *)rightItemTarget:(id)target img:(NSString *)imgName tag:(int)tag action:(SEL)action
//{
//    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [btn addTarget:target action:(action) forControlEvents:UIControlEventTouchUpInside];
//    btn.tag = tag;
//    [btn setImage:[UIImage imageNamed:imgName] forState:UIControlStateNormal];
//    btn.userInteractionEnabled = YES;
//    
//    [btn sizeToFit];
//    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
//    return barButtonItem;
//}


@end
