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

#import "MyEventProcessManagementVC.h"



#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
#define KMargin 10
#define kHeight 30
#define kClickViewWH kScreenWidth*0.157
#define kClickLabelWH kScreenWidth*0.16
#define kClickBtnWH kScreenWidth*0.107



@interface MyEventProcessManagementVC () {
    Singleton *singleton;
}

@property (nonatomic, strong) NSString *start_type;
//用于显示_status == 0时 点击开始按钮label上面显示的值
@property (nonatomic, assign) NSInteger beginSecond;
@property (nonatomic, assign) NSInteger beginMinute;
@property (nonatomic, assign) NSInteger beginHour;

//用于显示_status == 1时 页面进入后label上面显示的值
@property (nonatomic, assign) NSInteger beginningSecond;
@property (nonatomic, assign) NSInteger beginningMinute;
@property (nonatomic, assign) NSInteger beginningHour;

@property (nonatomic, strong) UIButton *noBeginBtn;
@property (nonatomic, strong) UIButton *beginBtn;
@property (nonatomic, strong) UILabel *clickLabel;
@property (nonatomic, strong) UIImageView *clickImageView;

//点击开始按钮触发的计时器
@property (nonatomic, strong) NSTimer *beginTimer;
//赛事正在进行中，进入该页面触发的计时器
@property (nonatomic, strong) NSTimer *beginningTimer;

//用来存储服务器时间
@property (nonatomic, strong) NSNumber *server_time;

@property (nonatomic, assign) int threadFlag;

@end

@implementation MyEventProcessManagementVC

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _beginSecond = 0;
    _beginMinute = 0;
    _beginHour = 0;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    

    //接受通知，地图显示后，就拉取一次成绩
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(firstShow) name:@"setScoreOn" object:nil];
    _threadFlag = 1;
    self.isInFunction = YES;
    //视图进入后，开始网络请求，成绩列表的请求
     dispatch_queue_t queque = dispatch_queue_create("getScoreList", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queque, ^{
        int i = 19;
        while (_threadFlag) {
            i++;
            if (i==20) {
                if (!self.isInFunction) {
                     NSLog(@"20秒");
                     [self getScoreListFromServer];
                }
               
                i=0;
                
                continue;
            }
            sleep(1);
        }
        NSLog(@"线程结束");
    });
    
    singleton = [Singleton defaultSingleton];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"我的赛事过程管理";
 

//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav_bg"] forBarMetrics:(UIBarMetricsDefault)];
//    //改变字体颜色
//    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
//    textAttrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
//    self.navigationController.navigationBar.titleTextAttributes = textAttrs;
    
    
    [Manager setNavi:self.navigationController.navigationBar];
    
    
    
#pragma - 设置导航栏左边的按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav_back"] landscapeImagePhone:nil style:UIBarButtonItemStylePlain target:self action:@selector(leftBarBtnItemIsClicked:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
#pragma mark --设置导航栏右边朋友圈分享按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"share"] landscapeImagePhone:nil style:UIBarButtonItemStylePlain target:self action:@selector(rightBarBtnItemClicked:)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem.image = nil;

    
    //UI布局，闹钟
    _clickImageView = [[UIImageView alloc] initWithFrame:CGRectMake(KMargin, 0, kClickViewWH, kClickViewWH)];
    _clickImageView.image = [UIImage imageNamed:@"gameicon"];
    [self.view addSubview:_clickImageView];
    
    //显示时间，默认显示00:00：00
    _clickLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_clickImageView.frame), 0, (kScreenWidth - 2*KMargin)/2, kClickLabelWH)];

    _clickLabel.text = [NSString stringWithFormat:@"%.2ld:%.2ld:%.2ld", (long)_beginHour, (long)_beginMinute, (long)_beginSecond];
    _clickLabel.textAlignment = NSTextAlignmentCenter;
    _clickLabel.font = [UIFont systemFontOfSize:30];

    [self.view addSubview:_clickLabel];
    
    //创建显示，地图，成绩列表，和申请人员的整体视图
    _noBegin = [[NoBeginView alloc] initWithFrame:CGRectMake(KMargin, CGRectGetMaxY(_clickImageView.frame), kScreenWidth - 2*KMargin, kScreenHeight - 64)];
    _noBegin.officalEvR = self.officalEventRoute;//官方赛事的路线
    _noBegin.evnStart  = self.evpStart;//官方赛事起点
    _noBegin.evnEnd = self.evpEnd;//官方赛事终点
    
    _noBegin.delegate = self;
    [self.view addSubview:_noBegin];
    
    _beginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _beginBtn.frame = CGRectMake(CGRectGetMaxX(_clickLabel.frame) + KMargin, KMargin, (kScreenWidth - 2*KMargin)/3, kClickBtnWH);
    
    if (_status == 0 && self.isTure) {
        //未开始状态，赛事是自己创建
         [_beginBtn setImage:[UIImage imageNamed:@"startgameno.png"] forState:(UIControlStateNormal)];
         [_beginBtn setImage:[UIImage imageNamed:@"stopgameno.png"] forState:(UIControlStateSelected)];
         [_beginBtn addTarget:self action:@selector(beginBtnIsClicked:) forControlEvents:(UIControlEventTouchUpInside)];
        
         [self.view addSubview:_beginBtn];
    } else if (_status == 1) {
        //进行中
        if (self.isTure) {
            //1.添加结束按钮
            [_beginBtn setImage:[UIImage imageNamed:@"stopgameno.png"] forState:(UIControlStateNormal)];
            [_beginBtn addTarget:self action:@selector(stopBtnIsClicked:) forControlEvents:(UIControlEventTouchUpInside)];
            [self.view addSubview:_beginBtn];
        }
          //2.计算时间差值（服务器时间－赛事正真开始时间），并显示在label上
        [self calTimeinterval];
          //3._begingTimer计时器开始工作
        _beginningTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(beginningTimerBegins:) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_beginningTimer forMode:NSDefaultRunLoopMode];
    }
    
    //支付相关
    self.payFlag = @"0";//设置支付标志位
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(beginCompeteEvent) name:@"paySucBegin" object:nil];
    
}

-(void)rightBarBtnItemClicked:(UIBarButtonItem *)sender
{
    if (self.noBegin.segmentedControl.selectedSegmentIndex!=1) {
        return;
    }
    if ([WXApi isWXAppInstalled] && [WXApi isWXAppSupportApi])
    {
        //朋友圈分享
        /*  WXMediaMessage *message = [WXMediaMessage message];
         message.title = @"智慧皋亭山－－赛事成绩";
         message.description = @"分享结果";
         
         
         [message setThumbImage:[UIImage imageNamed:@"1111"]];
         
         WXWebpageObject *pageObj = [WXWebpageObject object];
         NSString *str = [NSString stringWithFormat:@"%@&shareFlag=1",self.webView.request.URL.absoluteString];
         pageObj.webpageUrl = str;
         message.mediaObject = pageObj;
         
         SendMessageToWXReq *reg = [[SendMessageToWXReq alloc]init];
         reg.bText = NO;
         reg.message = message;
         reg.scene = WXSceneTimeline;
         
         [WXApi sendReq:reg];*/
        [Manager shareToWXTimeLine:self.noBegin.scoreWeb.request.URL.absoluteString];
      
    }else
    {
        [FileDownloadTool alert:@"您还没安装微信" view:self.view];
    }
    
    
}


#pragma mark 懒加载
-(NSMutableArray *)tmpScoreArr
{
    if (_tmpScoreArr == nil) {
        _tmpScoreArr = [[NSMutableArray alloc]initWithCapacity:100];
    }
    return _tmpScoreArr;
}

-(MBProgressHUD *)hud
{
    if (!_hud) {
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        _hud = [MBProgressHUD showHUDAddedTo:window animated:YES];
        _hud.labelText = @"支付成功，赛事即将开始...";
    }
    return _hud;
}
#pragma mark --地图加载完毕后，第一次显示点位 
-(void)firstShow
{
    NSLog(@"地图加载显示成绩");
    [self getScoreListFromServer];
}

#pragma mark 从服务器获取成绩列表数据
-(void)getScoreListFromServer
{
    self.isInFunction = YES;
    [self.tmpScoreArr removeAllObjects];//每次请求都把数据清空，重新请求
    
    //成绩列表。参数拼接
    //创建单例实例 赋值
    singleton = [Singleton defaultSingleton];
    //    NSLog(@"eventId:%@ userid:%@", singleton.eventId, singleton.userid);
    //    getUserEventResult
   
    NSString *str_sign = [NSString stringWithFormat:@"{\"deviceSn\":\"%@\",\"eventId\":\"%@\",\"repeaterSn\":\"%@\"}eventApplyUserVerify", singleton.deviceSn, singleton.eventId,@""];
    
    
    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 = [NSString stringWithFormat:@"%@/terminal/eventApplyUserVerify",localRequestUrl];
    // 初始化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);
      dispatch_queue_t queque = dispatch_queue_create("analysisScore", DISPATCH_QUEUE_CONCURRENT);
        dispatch_async(queque, ^{
            [self analysisScoreData:responseObject];
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 请求失败
        NSLog(@"%@", [error localizedDescription]);
        self.isInFunction = NO;
    }];
    
}

#pragma mark --大批量数据解析，放在子线程里面做
-(void)analysisScoreData:(id)responseObject
{
     sleep(10);
    NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
    NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
    
    if (!dic) {
        self.isInFunction = NO;
        return;
    }
    
    
    NSString *result_data=[dic objectForKey:@"result_data"];
    NSLog(@"result_data=%@",result_data);
    
    if([result_data isEqualToString:@""]){
        self.isInFunction = NO;
        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)
    {
        //表示没有数据，result为空，直接return掉
        self.isInFunction = NO;
        return;
    }
    
    int i=0;
    for (NSString *scoreDicStr in arr) {
        NSData *scoreDicData = [scoreDicStr dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *scoreDic = [NSJSONSerialization JSONObjectWithData:scoreDicData options:NSJSONReadingMutableLeaves error:nil];
        //找出自己的成绩，
        if ([[NSString stringWithFormat:@"%@",[scoreDic objectForKey:@"userId"]] isEqualToString:singleton.userid]) {
            _myScoreModel = [[PersonScoreModel alloc]initWithInforDic:scoreDic];//存储自己的成绩
        }
        //只取有成绩的，没成绩的直接舍掉
        if ([scoreDic objectForKey:@"eventTime"] !=nil) {
            i++;
            PersonScoreModel *scoreModel = [[PersonScoreModel alloc]initWithInforDic:scoreDic];
            [self.tmpScoreArr addObject:scoreModel];
        }
        
    }
    
    if (self.tmpScoreArr.count == 0) {
        //表示🈶️数据返回，但是人员都没有成绩，直接return掉,防止数据为空报错
        self.isInFunction = NO;
        return;
    }
    //对数组进行排序，没排名的，已经被过滤掉了
    self.sortedScoreArr = [self.tmpScoreArr sortedArrayUsingComparator:^NSComparisonResult(PersonScoreModel *p1, PersonScoreModel *p2){
        return [p1.eventSeconds compare:p2.eventSeconds];
    }];
    
    [self performSelectorOnMainThread:@selector(setOnView:) withObject:nil waitUntilDone:YES];
}


#pragma mark --将结果传递给nobegin视图
-(void)setOnView:(int)count
{
    //将信息传给nobeginView，用于在地图上显示
    [_noBegin setWithAllScore:_sortedScoreArr my:_myScoreModel andNumber:(int)_sortedScoreArr.count];
    [_noBegin getDataFromMyEventProgressVC];
    self.isInFunction = NO;
}


#pragma mark －－－模拟假数据，大数据量接收，显示地图上
/**成绩假数据*
-(void)readJsonSet
{
    [self.scoreLock lock];
    [_tmpScoreArr removeAllObjects];//每次请求都把数据清空，重新请求
 
    //获取json文件的地址
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"score" ofType:@"json"];
    NSData *jsonData = [NSData dataWithContentsOfFile:filePath];
    NSError *error;
    NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
    NSArray *allObject = [jsonDic objectForKey:@"result"];
    NSLog(@"allObj.count = %ld",allObject.count);
    int i =0;
    for (NSDictionary *dic in allObject)
    {
        //将数据放进数组里面
        //找出自己的成绩，
        if ([[NSString stringWithFormat:@"%@",[dic objectForKey:@"userId"]] isEqualToString:singleton.userid]) {
            _myScoreModel = [[PersonScoreModel alloc]initWithInforDic:dic];//存储自己的成绩
        }
        //只取有成绩的，没成绩的直接舍掉
        if ([dic objectForKey:@"eventTime"] !=nil) {
            i++;
            PersonScoreModel *scoreModel = [[PersonScoreModel alloc]initWithInforDic:dic];
            [self.tmpScoreArr addObject:scoreModel];
        }
    }
    
    self.totalP = i;
    if (self.tmpScoreArr.count == 0) {
        //表示🈶️数据返回，但是人员都没有成绩，直接return掉,防止数据为空报错
         [self.scoreLock unlock];
        return;
    }
    //对数组进行排序，没排名的，已经被过滤掉了
    self.sortedScoreArr = [self.tmpScoreArr sortedArrayUsingComparator:^NSComparisonResult(PersonScoreModel *p1, PersonScoreModel *p2){
        return [p1.eventSeconds compare:p2.eventSeconds];
    }];
    
    [self.scoreLock unlock];
    //将信息传给nobeginView，用于在地图上显示
    [self performSelectorOnMainThread:@selector(hahaha) withObject:nil waitUntilDone:YES];
}


-(void)hahaha
{
    
    [_noBegin setWithAllScore:_sortedScoreArr my:_myScoreModel andNumber:self.totalP];
    [_noBegin getDataFromMyEventProgressVC];
}
**成绩假数据*/

#pragma mark --nobegin视图的代理，事件
-(void)pushToEachScoreV:(NSString *)requestUrl
{
    EachScoreVC *eachScore = [[EachScoreVC alloc] init];
    eachScore.requestUrl= requestUrl;
    CustomNavViewController *nav = [[CustomNavViewController alloc] initWithRootViewController:eachScore];
    [self presentViewController:nav animated:YES completion:nil];
}

-(void)rightNaviShow:(long)flag
{
    if (flag==1) {
        self.navigationItem.rightBarButtonItem.image = [UIImage imageNamed:@"share"];
    }else
    {
        self.navigationItem.rightBarButtonItem.image = nil;
    }
}


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

#pragma mark - 获取服务器时间
- (NSNumber *)AccessToServerTime {
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/terminal/systime",localRequestUrl]];
    //注: 使用NSURLRequest的HTTPMethod不能修改, 就没有办法做POST请求, 所以使用NSMutableURLRequest
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    //请求方式
    request.HTTPMethod = @"POST";
    //发送同步请求.
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    //数据转化.
    NSNumber *server_time = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    
    //存储一下服务器时间
    return server_time;
}


#pragma mark - 开始比赛按钮被点击
- (void)beginBtnIsClicked:(UIButton *)sender {
    self.server_time = [self AccessToServerTime];
    
    if ([self.server_time integerValue] < [self.eventStartTime integerValue]) {
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"抱歉，还没到开始时间" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertVc addAction:action1];
        [self presentViewController:alertVc animated:YES completion:nil];
        sender.selected = NO;
        return;
    }
    if (!sender.selected) {
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"您确定开始比赛吗？" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            [self startSendRequestToServer];
            
        }];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        }];
        
        [alertVc addAction:action1];
        [alertVc addAction:action2];
        [self presentViewController:alertVc animated:YES completion:nil];
    }else
    {
        [self stopBtnIsClicked:sender];
    }
    
    
}

#pragma mark --收到支付成功回调的通知，改变支付标示，并且重新发起开始赛事的请求。
-(void)beginCompeteEvent
{
    [self.hud show:YES];
    NSLog(@"支付成功");
    self.payFlag = @"1";
    [self startSendRequestToServer];
}

//改动2016－17
- (void)startSendRequestToServer {
    //发送请求给服务器。
    NSDictionary *dicx;
    self.start_type = @"1";
    dicx = @{@"type" : self.start_type, @"id" : singleton.eventId, @"user_id" : singleton.userid,@"pay_flag":self.payFlag};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:[NSString stringWithFormat:@"%@/terminal/eventstartend",localRequestUrl] parameters:dicx progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *server_data = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
        NSLog(@"server_data:%@", server_data);
        
        //通过返回值先判断是否支付，没支付，提示支付，支付过直接开始赛事
        if ([[server_data objectForKey:@"status"] isEqualToString:@"9003"] && [[server_data objectForKey:@"code"] isEqualToString:@"5000"]) {
            //表示没支付过，需要提示支付
            UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"赛事需要付费开始，现在去支付吗？" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                //发送支付请求，请求支付宝
                NSString *amount = [server_data objectForKey:@"amount"];
                [self createOrderAndPay:amount];
            }];
            UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            }];
            
            [alertVc addAction:action1];
            [alertVc addAction:action2];
            [self presentViewController:alertVc animated:YES completion:nil];
        }else
        {
            [self.hud hide:YES];
            _beginSecond =0;
            _beginMinute = 0;
            _beginHour = 0;
            _beginTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(beginTimerBegins:) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer:_beginTimer forMode:NSDefaultRunLoopMode];
            _beginBtn.selected = !_beginBtn.selected;
        }
       
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self.hud hide:YES];
        NSLog(@"error：%@", error);
    }];

}

#pragma mark --支付宝订单拼装，发送请求
-(void)createOrderAndPay:(NSString *)amount
{
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    order.partner = @"2088021830678838";
    order.sellerID = @"gaotingshan517@163.com";
    order.outTradeNO = [self generateTradeNO]; //订单ID（由商家自行制定）
    order.subject = @"团队付费"; //商品标题
    order.body = @"团队付费"; //商品描述
    order.totalFee = [NSString stringWithFormat:@"%.2f",[amount doubleValue]]; //商品价格
   // order.totalFee = [NSString stringWithFormat:@"%.2f",0.01]; //商品价格
    order.notifyURL =  @"http://www.xxx.com"; //回调URL
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showURL = @"m.alipay.com";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    NSLog(@"orderSpec = %@",orderSpec);
    
    NSDictionary *parameterDic = [[NSDictionary alloc]initWithObjectsAndKeys:orderSpec,@"orderInfo", nil];
    
    [Manager alipayRequest:parameterDic orderSpec:orderSpec flag:2];
}

#pragma mark   ==============产生随机订单号==============


- (NSString *)generateTradeNO
{
    static int kNumber = 15;
    
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand((unsigned)time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}

#pragma mark -  _beginTimer计时器处理
- (void)beginTimerBegins:(NSTimer *)sender {
    
    _beginSecond ++;
    if (_beginSecond >= 60) {
        _beginSecond = 0;
        _beginMinute ++;
    }
    if (_beginMinute >= 60) {
        _beginMinute = 0;
        _beginHour ++;
    }
    _clickLabel.text = [NSString stringWithFormat:@"%.2ld:%.2ld:%.2ld", (long)_beginHour, (long)_beginMinute, (long)_beginSecond];

    
}

#pragma mark - beginningTimer计时器的处理方法
- (void)beginningTimerBegins:(NSTimer *)sender {
    _beginningSecond ++;
    if (_beginningSecond >= 60) {
        _beginningSecond = 0;
        _beginningMinute ++;
    }
    if (_beginningMinute >= 60) {
        _beginningMinute = 0;
        _beginningHour ++;
    }
    _clickLabel.text = [NSString stringWithFormat:@"%.2ld:%.2ld:%.2ld", (long)_beginningHour, (long)_beginningMinute, (long)_beginningSecond];
    
}


#pragma mark - 结束比赛按钮被点击
- (void)stopBtnIsClicked:(UIButton *)sender {
    //改动2016-17 加提示框
    //弹出提示框 “结束按钮提示”
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"您确定要结束比赛吗？" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self stopBtnSendRequestServer];
        
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alertVc addAction:action1];
    [alertVc addAction:action2];
    [self presentViewController:alertVc animated:YES completion:nil];
    
}

//改动 2016-17
- (void)stopBtnSendRequestServer {
    //结束比赛按钮被点击， 重新设置图片 － 6.16 
    [_beginBtn setImage:[UIImage imageNamed:@"stopgameno.png"] forState:(UIControlStateNormal)];
    
    //发送请求给服务器。
    NSDictionary *dicx;
    self.start_type = @"2";
    dicx = @{@"type" : self.start_type, @"id" : singleton.eventId, @"user_id" : singleton.userid};
    NSString *postStr = [NSString stringWithFormat:@"%@/terminal/eventstartend",localRequestUrl];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:postStr parameters:dicx progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *server_data = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
        NSLog(@"end_server_data:%@", server_data);
        if ([singleton.string isEqualToString:@"9002"] && [server_data[@"code"] isEqualToString:@"1004"]) {
            //停止计时器
            if ([_beginTimer isValid]){
                 [_beginTimer invalidate];
                _beginTimer = nil;
            }
            if ([_beginningTimer isValid]){
                [_beginningTimer invalidate];
                _beginningTimer = nil;
            }
            
            [_beginBtn setImage:[UIImage imageNamed:@"gameover"] forState:(UIControlStateNormal)];//按钮变成已经结束按钮
            _beginBtn.enabled = NO;
        } else {
            //弹出提示框 “网络超时，请检查网络！”
            UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"网络超时，请检查网络！" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alertVc addAction:action];
            [self presentViewController:alertVc animated:YES completion:nil];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error：%@", error);
    }];

}

#pragma mark - 服务器时间与赛事真正开始时间差值计算
-(void)calTimeinterval
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/terminal/systime",localRequestUrl]];
    //注: 使用NSURLRequest的HTTPMethod不能修改, 就没有办法做POST请求, 所以使用NSMutableURLRequest
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    //请求方式
    request.HTTPMethod = @"POST";
    //发送同步请求.
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSNumber *NowNumber = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    NSLog(@"NowNumber:%@", NowNumber);
    NSDate *Nowdate = [NSDate dateWithTimeIntervalSince1970:NowNumber.integerValue];
    
    NSDate *realDate = [NSDate dateWithTimeIntervalSince1970:[_realStartTime integerValue]];
    // 当前日历
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // 需要对比的时间数据
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth
    | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    // 对比时间差
    NSDateComponents *dateCom = [calendar components:unit fromDate:realDate toDate:Nowdate options:0];
    NSLog(@"相差：%ld hour %ld minute %ld second",(long)dateCom.hour,(long)dateCom.minute,(long)dateCom.second);

    _beginningHour = dateCom.hour;
    _beginningMinute = dateCom.minute;
    _beginningSecond = dateCom.second;
    //5.秒 分 时 在label显示
    _clickLabel.text = [NSString stringWithFormat:@"%.2ld:%.2ld:%.2ld", (long)_beginningHour, (long)_beginningMinute, (long)_beginningSecond];
}

#pragma mark - 导航栏返回按钮被点击
- (void)leftBarBtnItemIsClicked:(UIBarButtonItem *)sender {
   
    _threadFlag = 0;
    
    //通知“竞赛详情” “我的赛事安排”页面
    [[NSNotificationCenter defaultCenter] postNotificationName:@"reLoadFromMyCompeteSchedule" object:self.fromFlag];
    //reLoadFromMyCompeteSchedule
    
    //停用计时器
    [_beginTimer invalidate];
    _beginTimer = nil;
    [_beginningTimer invalidate];
     _beginningTimer = nil;
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"setScoreOn" object:nil];
    if (_noBegin.segmentedControl.selectedSegmentIndex == 1) {
        //表示在停在成绩页面
        if ([_noBegin.scoreWeb canGoBack]) {
            [_noBegin.scoreWeb goBack];
        }else
        {
            //重新开启上一页面
            [self dismissViewControllerAnimated:NO completion:nil];
        }
    }else{
        //重新开启上一页面
        [self dismissViewControllerAnimated:NO completion:nil];
    }
   
    
}


-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"setScoreOn" object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"paySucBegin" 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.
}
*/

//    NSLog(@"%ld %ld %ld %ld",self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height);
//        NSTimeInterval intervals = [_startDate timeIntervalSinceDate:Nowdate];
//        NSLog(@"intervals:%.0lf", intervals);
//        NSDate *ddddd= [NSDate dateWithTimeIntervalSince1970:intervals];
//        NSLog(@"ddddd:%@", ddddd);

//- (void)AccessToServerTime {
//    NSData *responseObject = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://gwms.517gts.com/terminal/systime"]];
////    NSNumber *server_number = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
//    NSLog(@"server_number:%@", responseObject);
//}




//- (void)AccessToServerTime {
    //    // 1.获得请求管理者(为了获取服务器时间)
    ////    NSString *server_time;
    //    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //    [manager POST:@"http://gwms.517gts.com/terminal/systime" parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    //                  
    //    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    ////        NSLog(@"服务器时间responseObject:%@", responseObject);
    //        //NSLog(@"responseObject:%@", [responseObject class]);
    //
    //        NSNumber *NowNumber = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
    //        NSLog(@"NowNumber:%@", NowNumber);
    ////        NSDate *Nowdate = [NSDate dateWithTimeIntervalSince1970:NowNumber.floatValue];
    ////        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    ////        [dateFormatter setDateFormat:@"YYYYMMddHHmmss"];
    ////        NSString *serverTime =[dateFormatter stringFromDate:Nowdate];
    ////        NSLog(@"serverTime:%@", serverTime);
    //        self.server_time = responseObject;
    //    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    //        NSLog(@"error：%@", error);
    //    }];
    //}

@end
