//
//  LoginViewController.m
//  gaotingshan
//
//  Created by MacBook Dq01 on 16/3/17.
//  Copyright © 2016年 Mac Book DQ02. All rights reserved.
//  用于处理用户登录 注册 找回密码等操作的。

#import "LoginViewController.h"
#import "registerViewController.h"
#import "lookForPasswordViewController.h"
#import "AFNetworking.h"
#import "LeftDrawerViewController.h"
#import "MyMD5.h"
#import "Singleton.h"
#import "MMDrawerController.h"
#import "AppDelegate.h"
#import "UIView+UIView_Extension.h"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
#define KMargin 20
#define HeightWidth kScreenWidth*0.4
#define bgImageViewHeight 100

#define NUMBERS @"0123456789"

@interface LoginViewController () <UITextFieldDelegate> {
    Singleton *singleton;
    //未登录状态下（以下4个字段）
    NSString *type;
    NSString *key;
    NSString *time;
    NSString *sign;
    //登录字段：4个（登录类型，登录源，用户名，密码）
    NSString *loginType;
    NSString *origin;
    
    UITextField *phoneTF;
    UITextField *passwordTF;
    //用于存放加密字符串
    NSMutableArray *mAry;
    
}

@property (nonatomic, strong) UIImageView *topImageView;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //创建单例.
    singleton = [Singleton defaultSingleton];
    self.navigationItem.title = @"登录";
    self.view.backgroundColor = [UIColor colorWithRed:250/255. green:250/255. blue:250/255. alpha:0.99];
    
//    [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 = [Manager rightItemTarget:self img:@"nav_back" tag:1000000 action:@selector(LeftBtnBackIsClicked)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav_back.png"] landscapeImagePhone:nil style:UIBarButtonItemStylePlain target:self action:@selector(LeftBtnBackIsClicked)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
//  登录页面的UI布局（一个大的bgImageView，两个小的imageView，两个textfiled， 一个登录button， 找回密码button， 新用户注册button）
    _topImageView = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - HeightWidth)/2.0, KMargin, HeightWidth, HeightWidth)];
//    _topImageView.center = CGPointMake(kScreenWidth/2.0, 64 + KMargin);
    _topImageView.image = [UIImage imageNamed:@"loginicon.png"];
    [self.view addSubview:_topImageView];
    
    UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(KMargin, CGRectGetMaxY(_topImageView.frame) + KMargin, [UIScreen mainScreen].bounds.size.width - 2*KMargin, bgImageViewHeight)];
//    bgImageView.backgroundColor = [UIColor greenColor];
    bgImageView.userInteractionEnabled = YES;
    [self.view addSubview:bgImageView];
    
    UIImageView *phoneImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 35, 35)];
    phoneImageView.image = [UIImage imageNamed:@"phone-30"];
    phoneImageView.contentMode = UIViewContentModeCenter;
    NSLog(@"%lf", phoneImageView.height);
    //    phoneImageView.backgroundColor = [UIColor brownColor];
    //    [bgImageView addSubview:phoneImageView];
    
    phoneTF = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, bgImageView.width, (bgImageView.height - KMargin) / 2)];
    NSLog(@"%lf,%lf,%lf,%lf", phoneTF.x,phoneTF.y,phoneTF.width,phoneTF.height);
    phoneTF.placeholder = @"请输入手机号：";
    //    phoneTF.borderStyle = UITextBorderStyleRoundedRect;
    phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    phoneTF.delegate = self;
    phoneTF.backgroundColor = [UIColor whiteColor];
    phoneTF.leftView = phoneImageView;
    phoneTF.leftViewMode = UITextFieldViewModeAlways;
    [bgImageView addSubview:phoneTF];
    
    UIImageView *passwordIamgeView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 35, 35)];
    passwordIamgeView.image = [UIImage imageNamed:@"pass-30"];
    passwordIamgeView.contentMode = UIViewContentModeCenter;
    //    passwordIamgeView.backgroundColor = [UIColor brownColor];
    //    [bgImageView addSubview:passwordIamgeView];
    passwordTF = [[UITextField alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(phoneTF.frame) + KMargin, bgImageView.width, (bgImageView.height - KMargin) / 2)];
    passwordTF.placeholder = @"请输入密码：";
    //设置是否密文输入
    passwordTF.secureTextEntry = YES;
    //    passwordTF.borderStyle = UITextBorderStyleRoundedRect;
    passwordTF.keyboardType = UIKeyboardTypeDefault;
    passwordTF.backgroundColor = [UIColor whiteColor];
    passwordTF.leftView = passwordIamgeView;
    passwordTF.leftViewMode = UITextFieldViewModeAlways;
    [bgImageView addSubview:passwordTF];
    
    
    //登录按钮
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    loginBtn.frame = CGRectMake((KMargin*3)/2, CGRectGetMaxY(bgImageView.frame) + (KMargin*3)/2, [UIScreen mainScreen].bounds.size.width - KMargin*3, 2*KMargin);
    [loginBtn setImage:[UIImage imageNamed:@"login_default.png"] forState:(UIControlStateNormal)];
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [loginBtn addTarget:self action:@selector(loginButton:) forControlEvents:UIControlEventTouchUpInside];
//    loginBtn.backgroundColor = [UIColor greenColor];
    [self.view addSubview:loginBtn];
    
    //找回密码button
    UIButton *lookForPwBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    lookForPwBtn.frame = CGRectMake(loginBtn.frame.origin.x, CGRectGetMaxY(loginBtn.frame) + KMargin/2, loginBtn.frame.size.width/2, KMargin);
    [lookForPwBtn setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
//    lookForPwBtn.backgroundColor = [UIColor cyanColor];
    [lookForPwBtn setTitle:@"找回密码" forState:UIControlStateNormal];
    lookForPwBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    lookForPwBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [lookForPwBtn addTarget:self action:@selector(lookForPassWordIsClicked:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:lookForPwBtn];
    
    //注册新用户button
    UIButton *registerNewBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    registerNewBtn.frame = CGRectMake(CGRectGetMaxX(lookForPwBtn.frame), CGRectGetMaxY(loginBtn.frame) + KMargin/2, loginBtn.frame.size.width/2, KMargin);
    [registerNewBtn setTitle:@"新用户注册" forState:UIControlStateNormal];
    registerNewBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    registerNewBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [registerNewBtn setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
//    registerNewBtn.backgroundColor = [UIColor cyanColor];
    [registerNewBtn addTarget:self action:@selector(registerNewButton:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:registerNewBtn];
    
    
}

#pragma mark - 点击导航栏左边的返回按钮。
- (void)LeftBtnBackIsClicked {
    [self dismissViewControllerAnimated:NO completion:^{
        
    }];
}

#pragma mark - 点击新用户注册的按钮，跳转到注册页面
- (void)registerNewButton:(UIButton *)sender {
    registerViewController *registerVC = [[registerViewController alloc] init];
    [self.navigationController pushViewController:registerVC animated:YES];

}

#pragma mark - 点击登录按钮
- (void)loginButton:(UIButton *)sender {
    //添加蒙板
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:YES];
    hud.labelText = @"正在登录...";
    
    NSDictionary *dicx;
    loginType = @"2";
    origin = @"phone";
    type = @"Ios";
    key = @".5Xf_01KXd352s177Jx3wxXc074poII";
    time = @"yyyyMMddHHmmss";
    //sign 需要MD5加密方式. 传入字符串（time+type+key），需要用到字符串拼接。
    NSString *str = [[NSString alloc] initWithFormat:@"%@%@%@", time,type, key];
    sign = [MyMD5 md5:str];
    
    dicx = @{@"type" : type, @"key" : key, @"time" : time, @"sign" : sign, @"login_type" : loginType, @"name" : phoneTF.text, @"pwds" : passwordTF.text, @"origin" : origin};
    //    [MBProgressHUD showMessage:@"正在加载"];
    // 1.获得请求管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    manager.responseSerializer=[AFHTTPResponseSerializer serializer];

    NSString *postStr = [NSString stringWithFormat:@"%@/terminal/login",localRequestUrl];
    // 2.发送POST请求
    [manager POST:postStr parameters:dicx constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //蒙板消失
        [hud hide:YES];
        NSLog(@"登录：%@", responseObject);
        //传值(利用block传值没有成功)
        //      self.block(responseObject[@"status"]);
        //服务器返回的字段“status”对应的值判断是否登录成功（9002代表成功，9003代表失败）
        if ([responseObject[@"status"] isEqualToString:@"9002"]) {
            NSLog(@"登录成功");
            //单例赋值
            singleton.sesskey = @"";
            singleton.reallyName = responseObject[@"data"][@"realName"];
            singleton.string = responseObject[@"status"];
            singleton.headImgUrl = responseObject[@"data"][@"headImgUrl"];
            singleton.nickName = responseObject[@"data"][@"nickName"];
            singleton.increased = responseObject[@"data"][@"increased"];
            singleton.weight = responseObject[@"data"][@"weight"];
            singleton.sex = responseObject[@"data"][@"sex"];
            singleton.deviceSn = responseObject[@"data"][@"deviceSn"];
            singleton.watchSn = responseObject[@"data"][@"braceletSn"];
            singleton.userid = responseObject[@"userid"];
            singleton.status = responseObject[@"status"];

            
            //以下是对responseObject[@"sesskey"]字段的处理。
            NSString *str = [responseObject[@"sesskey"] stringByReplacingOccurrencesOfString:@"\n" withString:@""];
            NSInteger count = str.length/76 + 1;
            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];
                }
            }
            for (NSInteger i = 0; i < mAry.count; i++) {
                singleton.sesskey = [singleton.sesskey stringByAppendingString:mAry[i]];
            }
            NSLog(@"singleton.sesskey:%@", singleton.sesskey);
            
                   
            //当登录成功后，发送通知给LeftVC（界面更换）。
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeLeftVCLayout" object:nil];

            //20160520 xmz 修改如果是从首页的竞赛详情跳转过来的，直接通知竞赛详情页，刷新视图,
            if ([self.skipFrom isEqualToString:@"FromCompeteDetail"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"freshCompeteDetailC" object:nil];
                singleton.eventId = self.fromCompeteEventID;
            }
          
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setObject:phoneTF.text forKey:@"userName"];
            [defaults setObject:passwordTF.text forKey:@"userPwd"];
                       
            [self dismissViewControllerAnimated:YES completion:^{
                if ([self.skipFrom isEqualToString:@"SpotDetaiComment"])
                {//从首页景点详情页面，跳转至此登录界面，发送通知给景点详情页面，通知刷新webview
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"freshSpotDetailWebview" object:nil];
                }
                //20160521 xmz 修改，有问题，竞赛详情页面的参数不知道怎么传
                if([self.skipFrom isEqualToString:@"FromMyOutApply"])
                {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeMyVCToCompete" object:nil];
                }else if([self.skipFrom isEqualToString:@"fromAttractionCollection"])
                {
                    [Manager requestForCollection:self.vc andAreaId:self.areaId];
                }


            }];
            
            
            
        } else {
            //蒙板消失
            [hud hide:YES];
            
            //弹出提示框 “用户名或密码不正确”
            UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"用户名或密码不正确" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"好" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alertVc addAction:action];
            [self presentViewController:alertVc animated:YES completion:nil];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"登录失败");
        //蒙板消失
        [hud hide:YES];
        [FileDownloadTool alert:@"网络无连接或超时" view:self.view];
    }];
    
}


#pragma mark - 点击找回密码按钮,跳转到找回密码页面。
- (void)lookForPassWordIsClicked:(UIButton *)sender {
    lookForPasswordViewController *lookForVC = [[lookForPasswordViewController alloc] init];
    [self.navigationController pushViewController:lookForVC animated:YES];
}

#pragma mark - UITextFieldDelegate motheds
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    /**第一种方式*/
    //    NSCharacterSet *set = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];
    //    NSString *filtered = [[string componentsSeparatedByCharactersInSet:set] componentsJoinedByString:phoneTF.text];
    //    BOOL basicTest = [string isEqualToString:filtered];
    //    if (!basicTest) {
    //        //弹出提示框 "请输入数字"
    //        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];
    ////      [phoneTF resignFirstResponder];
    //    }
    //
    //    return YES;
    
    /**第二种方式*/
    return [self validateNumber:string];
    
}

- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0  || phoneTF.text.length >= 11) {
            res = NO;
            break;
        }

        i++;
    }
    
    return res;
}




- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    phoneTF.enabled = YES;
    phoneTF.userInteractionEnabled = YES;

}

#pragma mark - block传值方法实现（没有成功）
- (void)passValue:(BlockStatus)block {
    self.block = block;
}





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