//
//  WatchLoginViewController.m
//  Car
//
//  Created by Javen on 2017/1/10.
//  Copyright © 2017年 上海勾芒信息科技. All rights reserved.
//

#import "WatchLoginViewController.h"
#import "HttpCilent.h"
@interface WatchLoginViewController ()

@end

@implementation WatchLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}
- (IBAction)actionLogin:(id)sender {
  [self httpAllowLogin];
}

- (void)httpAllowLogin {
  NSString *device = [self getStringAfter:@"deviceId=" string:self.LoginUrl];
  NSString *token = [self getStringAfter:@"token=" string:self.LoginUrl];
  WS(weakSelf);
  if (device == nil || token == nil) {
    [MBProgressHUD j_error:@"设备信息异常！" complete:^{
      [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    
  }
  NSDictionary *param = @{@"deviceId":device,
                          @"token":token};
  [kHttp GET:kWatchLogin parameters:param complete:^(id  _Nullable response, NSError * _Nullable error) {
    if (kRsSuccess(response)) {
      [MBProgressHUD j_success:@"登录成功！" complete:^{
        //连续返回两级
        long index = [[weakSelf.navigationController viewControllers] indexOfObject:weakSelf];
        [weakSelf.navigationController
         popToViewController:[weakSelf.navigationController.viewControllers
                              objectAtIndex:index - 2]
         animated:YES];
      }];
      
    }else{
      kShowRsMsg(response);
      
    }

  }];
}


/**
 从prefix后开始截取连续字符串（字符串中可包涵数字字母）

 @param prefix 从哪里开始截取
 @param string 需要截取的字符串
 @return 截取后的字符串
 */
- (NSString *)getStringAfter:(NSString *)prefix string:(NSString *)string {
  NSString *grex = [NSString stringWithFormat:@"%@[a-z0-9A-Z]*",prefix];
  
  NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:grex options:NSRegularExpressionCaseInsensitive error:nil];
  
  NSArray * matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
  if (matches.count == 1) {
    NSTextCheckingResult *result = matches[0];
    NSString *tempString = [string substringWithRange:result.range];
    NSString *matchedString = [tempString componentsSeparatedByString:@"="][1];
    return matchedString;
  }
  CLog(@"无法匹配到prefix：%@ \n string = %@",prefix, string);
  return 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.
}
*/

@end
