//
//  SmartWatchesViC.m
//  gaotingshan
//
//  Created by MacBook Dq01 on 16/4/28.
//  Copyright © 2016年 Xu Mengzhu. All rights reserved.
//

#import "SmartWatchesViC.h"
#import "AFNetworking.h"
#import "QRCodeScanVC.h"


#define kMargin 10
#define kScreenwidth [UIScreen mainScreen].bounds.size.width
#define kScreenheight [UIScreen mainScreen].bounds.size.height
#define kheight kScreenheight*0.045
#define kSureBtnHeight kScreenheight*0.06
#define bgVieHeight kScreenheight*0.18
#define twoDimensionCodeBtnHeightWidth kScreenwidth*0.4
#define twoDimensionCodeBtnMarginHeight kScreenheight*0.15

@interface SmartWatchesViC () <QRCodeScanVCDelegate> {
    NSString *device_type;
    UITextField *inputTF;
    UILabel *sublabel3;
}

@end

@implementation SmartWatchesViC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.frame = [UIScreen mainScreen].bounds;
    self.view.backgroundColor = [UIColor colorWithRed:241/255. green:241/255. blue:241/255. alpha:0.9];
    self.navigationItem.title = @"绑定智能手表";
    self.view.backgroundColor = [UIColor whiteColor];
    
//     [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];
    
    
    //设置导航栏左边按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav_back"] landscapeImagePhone:nil style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItemIsClicked)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    //UI布局
    [self createSubview];
    
}

#pragma mark - UI布局
- (void)createSubview {
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(kMargin, kMargin, kScreenwidth - 2*kMargin, bgVieHeight)];
    bgView.userInteractionEnabled = YES;
    bgView.backgroundColor = [UIColor colorWithRed:241/255. green:241/255. blue:241/255. alpha:0.999];
    [self.view addSubview:bgView];
    
    UILabel *subLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(kMargin, kMargin, bgView.frame.size.width - 2*kMargin, kheight)];
    subLabel1.text = @"输入序列号绑定";
    subLabel1.font = [UIFont systemFontOfSize:16];
    subLabel1.textAlignment = NSTextAlignmentLeft;
    //    subLabel1.backgroundColor = [UIColor redColor];
    [bgView addSubview:subLabel1];
    
    inputTF = [[UITextField alloc] initWithFrame:CGRectMake(kMargin, CGRectGetMaxY(subLabel1.frame), bgView.frame.size.width - 2*kMargin, kheight)];
    [inputTF setBorderStyle:UITextBorderStyleNone];
    inputTF.layer.borderWidth = 0.5;
    inputTF.layer.cornerRadius = 5.0;
    inputTF.layer.borderColor = [[UIColor greenColor] CGColor];
    inputTF.backgroundColor = [UIColor whiteColor];
    [bgView addSubview:inputTF];
    
    UILabel *subLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(kMargin, CGRectGetMaxY(inputTF.frame), bgView.frame.size.width/2, kheight)];
    subLabel2.text = @"（序列号见智能手表背面）";
    subLabel2.font = [UIFont systemFontOfSize:10];
    subLabel2.textAlignment = NSTextAlignmentLeft;
    subLabel2.textColor = [UIColor grayColor];
    [bgView addSubview:subLabel2];
#pragma 用于提示用户。
    sublabel3 = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(subLabel2.frame), CGRectGetMaxY(inputTF.frame), bgView.frame.size.width/2 - kMargin, kheight)];
    sublabel3.textAlignment = NSTextAlignmentRight;
    sublabel3.font = [UIFont systemFontOfSize:13];
    sublabel3.textColor = [UIColor redColor];
    [bgView addSubview:sublabel3];
    
    //确定Button
    UIButton *sureBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    sureBtn.frame = CGRectMake(kMargin, CGRectGetMaxY(bgView.frame) + kMargin, kScreenwidth - 2*kMargin, kSureBtnHeight);
    sureBtn.backgroundColor = [UIColor blackColor];
    [sureBtn setTitle:@"确定" forState:(UIControlStateNormal)];
    [sureBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    sureBtn.titleLabel.font = [UIFont systemFontOfSize:20];
    [sureBtn addTarget:self action:@selector(sureBtnIsClicked:) forControlEvents:UIControlEventTouchUpInside];
    [sureBtn addTarget:self action:@selector(sureBtnIsClicked:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:sureBtn];
    
    //扫描二维码按钮
    UIButton *twoDimensionCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    twoDimensionCodeBtn.frame = CGRectMake((kScreenwidth - twoDimensionCodeBtnHeightWidth)/2.0, CGRectGetMaxY(sureBtn.frame) + twoDimensionCodeBtnMarginHeight, twoDimensionCodeBtnHeightWidth, twoDimensionCodeBtnHeightWidth);
    [twoDimensionCodeBtn setImage:[UIImage imageNamed:@"erweima"] forState:(UIControlStateNormal)];
    //添加点击事件 调用手机摄像头。
    [twoDimensionCodeBtn addTarget:self action:@selector(twoDimensionCodeBtnHeightWidthIsClicked) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:twoDimensionCodeBtn];
    
}


#pragma mark - 点击sureBtn后，事件的响应。
- (void)sureBtnIsClicked:(UIButton *)sender {
    if ([inputTF.text isEqualToString:@""]) {
        sublabel3.text = @"手表序列号不能为空";
        return;
    }
    sublabel3.text = @"";

    //发送请求给服务器，（如果登录成功，跳转到“管理我的登山设备”页面）否则，（弹出提示卡号不正确）
     Singleton *singleton = [Singleton defaultSingleton];
    NSDictionary *dicx;
    dicx = @{@"braceletSn" : inputTF.text,@"user_id":singleton.userid,@"user_name":singleton.nickName};
   
    // 1.获得请求管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer= [AFHTTPRequestSerializer serializer];
 
    NSString *mainUrl = [NSString stringWithFormat:@"%@/terminal/bindBracelet",localRequestUrl];
    // 2.发送POST请求
    [manager POST:mainUrl parameters:dicx constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        
        NSLog(@"%@", responseObject);
        if ([responseObject[@"code"] isEqualToString:@"4001"]) {
            sublabel3.text = @"此手表不存在";
        } else if ([responseObject[@"code"] isEqualToString:@"6001"]) {
            sublabel3.text = @"无效的手表号";
        } else if ([responseObject[@"code"] isEqualToString:@"6003"]) {
            sublabel3.text = @"此手表已经绑定过了";
        } else if ([responseObject[@"code"] isEqualToString:@"6004"]) {
            sublabel3.text = @"已经绑定过手表了";
        } else if ([responseObject[@"code"] isEqualToString:@"1006"]){
            sublabel3.text = @"绑定成功";
            singleton.watchSn = inputTF.text;
            
            //发送通知到“managementDeviceVC”页面，重新加载webview。
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadWebview" object:nil];
            
            //发送通知到“MyVC”页面， 重新加载webview。
            [[NSNotificationCenter defaultCenter] postNotificationName:@"reLoadMyVCWebView" object:nil];
            
            //返回上一个页面。
            [self dismissViewControllerAnimated:NO completion:nil];
        }else if ([responseObject[@"code"] isEqualToString:@"6005"]){
            sublabel3.text = @"该手表未绑定过赛事";
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error=%@",error);
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"绑定智能手表失败！" message:@"请重新绑定" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"好" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
        [alertVc addAction:action];
        [self presentViewController:alertVc animated:YES completion:nil];
        
    }];
    
}

#pragma mark - 二维码Btn被点击
- (void)twoDimensionCodeBtnHeightWidthIsClicked {
    //跳到扫描二维码页面
    QRCodeScanVC *codeVC = [[QRCodeScanVC alloc] init];
    UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:codeVC];
    codeVC.delegate = self;
    codeVC.fromWhat = @"watch";
    [self presentViewController:navc animated:YES completion:nil];
    
}


#pragma mark - 导航栏左边按钮被点击
- (void)leftBarButtonItemIsClicked {
    //发送通知给hearStepVC页面
    [[NSNotificationCenter defaultCenter] postNotificationName:@"rePrompt" object:nil];

    [self dismissViewControllerAnimated:NO completion:nil];
    
   }

//- (void)viewController:(QRCodeScanVC *)viewController
//             passValue:(NSString *)string {
//    inputTF.text = string;
//}

-(void)passValueToWatch:(NSString *)watchNumber
{
    [inputTF becomeFirstResponder];
    inputTF.text = watchNumber;
}

/////////////////////////
- (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
