//
//  LoginViewController.m
//  Lighting
//
//  Created by 曹云霄 on 16/4/27.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "LoginViewController.h"
#import "CustomTabbarController.h"
#import "AppDelegate.h"
#import "authenticateView.h"
#import "FollowHeartViewController.h"

@interface LoginViewController ()<RightVCselectedDelegate>

@property (nonatomic,strong) MMDrawerController *drawerController;
@property (nonatomic,strong) CustomTabbarController *customtabbar;
@property (nonatomic,strong) FollowHeartViewController *followHeartView;

/**
 *  验证身份View
 */
@property (nonatomic,strong) authenticateView *identityView;

/**
 *  重置密码View
 */
@property (nonatomic,strong) authenticateView *resetPasswordView;

/**
 *  定时器
 */
@property (nonatomic,strong) NSTimer *sendTimer;

/**
 *  记录返回的验证码
 */
@property (nonatomic,copy) NSString *verifyCode;


@end

@implementation LoginViewController


- (CustomTabbarController *)customtabbar
{
    if (_customtabbar == nil) {
        
        _customtabbar = [[CustomTabbarController alloc]init];
    }
    return _customtabbar;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    
    [self uiConfigAction];
    
}


#pragma mark - 布局
- (void)uiConfigAction
{
    self.loginButton.layer.masksToBounds = YES;
    self.loginButton.layer.cornerRadius = kCornerRadius;
    self.userNameBackview.layer.masksToBounds = YES;
    self.userNameBackview.layer.cornerRadius = kCornerRadius;
    self.passWordBackview.layer.masksToBounds = YES;
    self.passWordBackview.layer.cornerRadius = kCornerRadius;
    self.userNameLoginView.layer.masksToBounds = YES;
    self.userNameLoginView.layer.cornerRadius = 10;
    self.forgotPasswordButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    self.followHeartView=[[FollowHeartViewController alloc]init];
    self.userName.text = @"demo1";
    self.passWord.text = @"123456";
    
}


#pragma mark -登陆
- (IBAction)LoginButtonClick:(UIButton *)sender {

//    [self SetTheRootViewController];
//    return;
    
    if (self.userName.text.length == 0) {

        [self ErrorMBProgressView:@"用户名不能为空"];
        return;
        
    }else if (self.passWord.text.length == 0)
    {
        [self ErrorMBProgressView:@"密码不能为空"];
        return;
    }
    
    [self judgeUserNameAndPassword];
}

#pragma mark -设置根视图控制器
- (void)SetTheRootViewController
{
        RightViewController *rightVC = [[RightViewController alloc]init];
        rightVC.delegate = self;
        self.drawerController = [[MMDrawerController alloc]initWithCenterViewController:self.customtabbar rightDrawerViewController:rightVC];
        [self.drawerController setMaximumRightDrawerWidth:RightWidth];
        [self.drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeAll];
        [self.drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
        SHARED_APPDELEGATE.mmdrawer = self.drawerController;
        SHARED_APPDELEGATE.window.rootViewController = self.drawerController;
}


#pragma mark -判断用户名密码是否正确
- (void)judgeUserNameAndPassword
{
    [self CreateMBProgressHUDLoding];
    NSString *URL = [NSString stringWithFormat:@"%@%@",ServerAddress,@"/employee/login"];
    LoginInfo *login = [[LoginInfo alloc]init];
    login.username = self.userName.text;
    login.password = self.passWord.text;
    
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:URL WithRequestType:0 WithParameter:login WithReturnValueBlock:^(id returnValue) {
        
        [self RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            //保持导购信息
            LoginResult *result = [[LoginResult alloc]initWithDictionary:returnValue[@"data"] error:nil];
            [Shoppersmanager manager].Shoppers = result;
            [Shoppersmanager manager].userNameString = self.userName.text;
            [Shoppersmanager manager].passWordString = self.passWord.text;
            
            [self SetTheRootViewController];
        }else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
        NSLog(@"%@",errorCodeValue);
        
    } WithFailureBlock:^(id error) {
        
        [self RemoveMBProgressHUDLoding];
        
    }];
}



#pragma mark -RightVCselectedDelegate 方法
- (void)SelectedControllerWithIndex:(NSString *)Name
{

    NSInteger selectedIndex;
    if ([Name isEqualToString:@"体验中心"]) {
    [SHARED_APPDELEGATE.window.rootViewController.view addSubview:self.followHeartView.view];
//        selectedIndex = 6;
        
    }else if ([Name isEqualToString:@"场景库"])
    {
       selectedIndex = 5;
    }else if ([Name isEqualToString:@"产品库"])
    {
        selectedIndex = 4;
    }else if ([Name isEqualToString:@"客户管理"])
    {
       selectedIndex = 3;
    }else if ([Name isEqualToString:@"所有客户"])
    {
        selectedIndex = 2;
    }else if ([Name isEqualToString:@"客户订单"])
    {
        selectedIndex = 1;
    }else if ([Name isEqualToString:@"关于"])
    {
        selectedIndex = 0;
    }

   self.customtabbar.selectedIndex = selectedIndex;
}



#pragma mark -忘记密码
- (IBAction)ForgotpasswordButtonClick:(UIButton *)sender {
    
    
    self.identityView = [[[NSBundle mainBundle] loadNibNamed:@"authenticateView" owner:self options:nil]firstObject];
    
    //判断登陆界面是否已经输入了用户名，如果有则直接引用，否则报错
    if (self.userName.text.length != 0) {
        
        self.identityView.userName.text = self.userName.text;
    } else {
        
        [self ErrorMBProgressView:@"请填写您的用户名"];
        self.passWord.text = @"";
        return;
    }
    
    
    self.identityView.layer.masksToBounds = YES;
    self.identityView.layer.cornerRadius = 10;
    [self.identityView.backLoginButton addTarget:self action:@selector(BackloginButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.identityView.nextButton addTarget:self action:@selector(NextButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.identityView.SendButton addTarget:self action:@selector(SendButtonClick) forControlEvents:UIControlEventTouchUpInside];
    self.identityView.alpha = 0;
    self.identityView.frame = self.userNameLoginView.frame;
    [self.view addSubview:self.identityView];
    [UIView animateWithDuration:0.2 animations:^{
        
        self.identityView.alpha = 1;
        
    }];
}

#pragma mark -发送验证码
- (void)SendButtonClick
{
    NSString *inputPhoneNumber = self.identityView.bindingPhoneNumber.text;
    if (inputPhoneNumber.length == 0) {
        
        [self ErrorMBProgressView:@"手机号不能为空"];
        return;
    }
    if (![HENLENSONG isValidateMobile:inputPhoneNumber]) {
        
        [self ErrorMBProgressView:@"手机号码格式不正确"];
        return;
    }
    
    
    [self CreateMBProgressHUDLoding];
    //发送验证码
    [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:[NSString stringWithFormat:@"%@%@",ServerAddress,@"/system/sendSms"] WithRequestType:0 WithParameter:[NSDictionary dictionaryWithObjectsAndKeys:inputPhoneNumber,@"mobilephone", nil] WithReturnValueBlock:^(id returnValue) {
        
        //解析返回的验证码，并存储到变量
//        NSLog(@"%@",returnValue);
        self.verifyCode = @"1234";
        
        
        [self RemoveMBProgressHUDLoding];
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
        
    } WithFailureBlock:^(id error) {
        
//        NSLog(@"%@",error);
        self.verifyCode = @"1234";
        [self RemoveMBProgressHUDLoding];
        
    }];
    
    [self.identityView.SendButton setTitle:@"60" forState:UIControlStateNormal];
    self.identityView.SendButton.enabled = NO;
    self.sendTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(SendbuttonChangetitle) userInfo:nil repeats:YES];
}

#pragma mark -倒计时
- (void)SendbuttonChangetitle
{
    
    NSInteger number = [self.identityView.SendButton.currentTitle integerValue];
    if (number <= 0) {
        
        [self.identityView.SendButton setTitle:@"发送" forState:UIControlStateNormal];
        self.identityView.SendButton.enabled = YES;
        [self.sendTimer invalidate];
        return;
    }
    number --;
    [self.identityView.SendButton setTitle:[NSString stringWithFormat:@"%ld",number] forState:UIControlStateNormal];
    
}


#pragma mark -返回登陆界面
- (void)BackloginButtonClick
{
    
    [UIView animateWithDuration:0.2 animations:^{
        
        self.identityView.alpha = 0;
        
    }completion:^(BOOL finished) {
        
        [self.identityView removeFromSuperview];
        
    }];
}



#pragma mark -下一步（重置密码界面）
- (void)NextButtonClick
{
    // 验证码必须填写
    if (self.identityView.verificationCode.text.length == 0) {
        
        [self ErrorMBProgressView:@"验证码不能为空"];
        return;
    } else {
        
        if ( [self.identityView.verificationCode.text isEqualToString: self.verifyCode] ) {
            [self.sendTimer invalidate];
            self.resetPasswordView = [[[NSBundle mainBundle] loadNibNamed:@"authenticateView" owner:self options:nil]lastObject];
            self.resetPasswordView.layer.masksToBounds = YES;
            self.resetPasswordView.layer.cornerRadius = 10;
            self.resetPasswordView.frame = self.userNameLoginView.frame;
            [self.resetPasswordView.backValidationView addTarget:self action:@selector(backButonClick) forControlEvents:UIControlEventTouchUpInside];
            [self.resetPasswordView.resetPasswordNextButton addTarget:self action:@selector(ChangPassWordRequest) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:self.resetPasswordView];
            self.resetPasswordView.alpha = 0;
            
            [UIView animateWithDuration:0.2 animations:^{
                
                self.resetPasswordView.alpha = 1;
            }];
        } else {
            [self ErrorMBProgressView:@"验证码不正确！"];
            return;
        }
    }
}


#pragma mark -修改密码
- (void)ChangPassWordRequest
{
    
    if (self.resetPasswordView.newpass.text.length == 0) {
        
        [self ErrorMBProgressView:@"新密码为空"];
        return;
        
    }else if (self.resetPasswordView.confirmNewpass.text.length == 0)
    {
        [self ErrorMBProgressView:@"确认密码为空"];
        return;
    }
    
    if (![self.resetPasswordView.newpass.text isEqualToString:self.resetPasswordView.confirmNewpass.text]) {
        
        [self ErrorMBProgressView:@"两次密码不相同"];
        return;
    }

    [self CreateMBProgressHUDLoding];
    //重置密码接口
    ResetPasswordRequest *passwrod = [[ResetPasswordRequest alloc]init];
    passwrod.fnewPassword = @"123456";
    passwrod.username = @"sh1";
    passwrod.smsCode = @"1234";//验证码
    
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:[NSString stringWithFormat:@"%@%@",ServerAddress,@"/employee/resetPassword"] WithRequestType:0 WithParameter:passwrod WithReturnValueBlock:^(id returnValue) {
        
        [self RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            [self ErrorMBProgressView:returnValue[@"message"]];
            
        }else
        {
           [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
    } WithFailureBlock:^(id error) {
        
        [self RemoveMBProgressHUDLoding];
        
    }];
    
}



#pragma mark -返回验证信息界面
- (void)backButonClick
{
    [UIView animateWithDuration:0.2 animations:^{
        
        self.resetPasswordView.alpha = 0;
        
    } completion:^(BOOL finished) {
        
        [self.resetPasswordView removeFromSuperview];
    }];
    
    // 重置发送按钮
    [self.identityView.SendButton setTitle:@"发送" forState:UIControlStateNormal];
    self.identityView.SendButton.enabled = YES;
    [self.sendTimer invalidate];
    
    // 清空验证码
    self.identityView.verificationCode.text = @"";
}







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