//
//  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 "SceneLibraryViewController.h"
#import "ProductLibraryViewController.h"
#import "AllCustomerViewController.h"
#import "CustomerOrderViewController.h"
#import <Bugly/Bugly.h>
#import "LearningCenterMainViewController.h"


@interface LoginViewController ()<RightVCselectedDelegate>

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

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

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

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

/**
 *  用户名
 */
@property (nonatomic,copy) NSString *userNameString;
/**
 *  密码
 */
@property (nonatomic,copy) NSString *passWordString;

/**
 * companyName
 */
@property (weak, nonatomic) IBOutlet UIImageView *companyName;

/**
 *  背景大图
 */
@property (weak, nonatomic) IBOutlet UIImageView *backImageView;

/**
 *  版本号
 */
@property (weak, nonatomic) IBOutlet UILabel *versionlabel;



@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];
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self exitApplication];
//    });

}

//#pragma mark - 强制退出app
//- (void)exitApplication {
//    
//    [UIView beginAnimations:@"exitApplication" context:nil];
//    [UIView setAnimationDuration:0.5];
//    [UIView setAnimationDelegate:self];
//    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:SHARED_APPDELEGATE.window cache:NO];
//    [UIView setAnimationDidStopSelector:@selector(animationFinished:finished:context:)];
//    SHARED_APPDELEGATE.window.bounds = CGRectMake(0, 0, 0, 0);
//    [UIView commitAnimations];
//}
//
//- (void)animationFinished:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
//    if ([animationID compare:@"exitApplication"] == 0) {
//        exit(0);
//    }
//}



#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.userNameString = [[NSUserDefaults standardUserDefaults] objectForKey:USERNAME];
    self.passWordString = [[NSUserDefaults standardUserDefaults] objectForKey:PASSWORD];
    self.userName.text = self.userNameString;
    self.passWord.text = self.passWordString;
    //版本更新
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(detectionUpdateVersion) name:UPLOADVERSION object:nil];
    self.versionlabel.text = [self getAppVersion];
    [self detectionUpdateVersion];
}


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


    if ([[self class] isBlankString:self.userName.text]) {
        [XBLoadingView showHUDViewWithText:@"用户名不能为空"];
        return;
    }else if ([[self class] isBlankString:self.passWord.text])
    {
        [XBLoadingView showHUDViewWithText:@"密码不能为空"];
        return;
    }
    [self judgeUserNameAndPassword];
    
}

#pragma mark -设置根视图控制器
- (void)SetTheRootViewController
{
    RightViewController *rightVC = [[[self class] getMainStoryboardClass] instantiateViewControllerWithIdentifier:@"RightViewController"];
    rightVC.delegate = self;
    UINavigationController *rightNav = [[UINavigationController alloc]initWithRootViewController:rightVC];
    self.drawerController = [[MMDrawerController alloc]initWithCenterViewController:self.customtabbar rightDrawerViewController:rightNav];
    [self.drawerController setMaximumRightDrawerWidth:RightWidth];
    [self.drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeAll];
    [self.drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
    SHARED_APPDELEGATE.mmdrawer = self.drawerController;
    [self restoreRootViewController:self.drawerController];
    SHARED_APPDELEGATE.Mytabbar = self.customtabbar;
}



#pragma mark -切换rootViewcontroller
- (void)restoreRootViewController:(UIViewController *)rootViewController
{
    typedef void (^Animation)(void);
    UIWindow* window = SHARED_APPDELEGATE.window;
    rootViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    Animation animation = ^{
        BOOL oldState = [UIView areAnimationsEnabled];
        [UIView setAnimationsEnabled:NO];
        window.rootViewController = rootViewController;
        [UIView setAnimationsEnabled:oldState];
    };
    
    [UIView transitionWithView:window
                      duration:0.5f
                       options:UIViewAnimationOptionTransitionFlipFromTop
                    animations:animation
                    completion:nil];
}


#pragma mark -判断用户名密码是否正确
- (void)judgeUserNameAndPassword
{
    [XBLoadingView showHUDViewWithDefault];
    LoginInfo *login = [[LoginInfo alloc]init];
    login.username = self.userName.text;
    login.password = self.passWord.text;
    WS(weakSelf);
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:SERVERREQUESTURL(LOGIN)  WithRequestType:ZERO WithParameter:login WithReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            //设置检测用户标示
            [Bugly setUserIdentifier:self.userName.text];
            //保持导购信息
            LoginResult *result = [[LoginResult alloc]initWithDictionary:returnValue[@"data"] error:nil];
            [Shoppersmanager manager].Shoppers = result;
            [Shoppersmanager manager].userNameString = weakSelf.userName.text;
            [Shoppersmanager manager].passWordString = weakSelf.passWord.text;
            //保存用户名密码
            [[NSUserDefaults standardUserDefaults] setObject:weakSelf.userName.text forKey:USERNAME];
            [[NSUserDefaults standardUserDefaults] setObject:weakSelf.passWord.text forKey:PASSWORD];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [weakSelf SetTheRootViewController];
        }else
        {
            [XBLoadingView showHUDViewWithText:returnValue[@"message"]];
        }
    }WithFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}


#pragma mark -RightVCselectedDelegate 方法
- (void)SelectedControllerWithIndex:(NSString *)Name
{
    SHARED_APPDELEGATE.lineView.hidden = YES;
    NSInteger selectedIndex = 0;
    if ([Name isEqualToString:@"体验中心"]) {
 
        [[NSNotificationCenter defaultCenter] postNotificationName:OPENFOLLOWHEARTVC object:nil];
        return;
        
    }else if ([Name isEqualToString:@"场景库"])
    {
        selectedIndex = 6;
        SceneLibraryViewController *sceneVC = [SHARED_APPDELEGATE.allControllerArray objectAtIndex_opple:6];
        sceneVC.conditionModel.styleEquals = nil;
        sceneVC.conditionModel.spaceEquals = nil;
        [sceneVC.styleButton setTitle:@"风格" forState:UIControlStateNormal];
        [sceneVC.spaceButton setTitle:@"空间" forState:UIControlStateNormal];
        [sceneVC.seceneLibararyCollectionView.mj_header beginRefreshing];
       
    }else if ([Name isEqualToString:@"产品库"])
    {
        selectedIndex = 7;
        ProductLibraryViewController *productVC = [SHARED_APPDELEGATE.allControllerArray objectAtIndex_opple:7];
        //默认加载全部数据
        productVC.barcode = nil;
        productVC.selectedCode = nil;
        productVC.condtionModel = nil;
        [productVC.productCollectionView.mj_header beginRefreshing];
    }else if ([Name isEqualToString:@"所有客户"])
    {
        selectedIndex = 8;
        AllCustomerViewController *AllcustomerVC = [SHARED_APPDELEGATE.allControllerArray objectAtIndex_opple:8];
        AllcustomerVC.searchTextfield.text = nil;
        AllcustomerVC.conditionModel = nil;
        [AllcustomerVC.allCustomerTableview.mj_header beginRefreshing];
    }else if ([Name isEqualToString:@"客户订单"])
    {
        selectedIndex = 9;
        CustomerOrderViewController *customerVC = [SHARED_APPDELEGATE.allControllerArray objectAtIndex_opple:9];
        customerVC.searchCustomerOrder.text = nil;
        [customerVC.styleButton setTitle:@"全部订单" forState:UIControlStateNormal];
        customerVC.model.consumerNameOrMobileEquals = nil;
        customerVC.model.orderStateEquals = nil;
        [customerVC.customerOrderTableView.mj_header beginRefreshing];
    }else if ([Name isEqualToString:@"学习中心"])
    {
        selectedIndex = 10;
        
    }else if ([Name isEqualToString:@"关于"])
    {
        selectedIndex = 11;
    }
   self.customtabbar.selectedIndex = selectedIndex;
}



#pragma mark -忘记密码
- (IBAction)ForgotpasswordButtonClick:(UIButton *)sender {
    self.identityView = [[[NSBundle mainBundle] loadNibNamed:@"authenticateView" owner:self options:nil]firstObject];
    //判断登陆界面是否已经输入了用户名,如果有则直接引用,否则报错
    if (![[self class] isBlankString:self.userName.text]) {
        self.identityView.userName.text = self.userName.text;
    } else {
        
        [XBLoadingView showHUDViewWithText:@"请填写您的用户名"];
        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
{
    WS(weakSelf);
    NSString *inputPhoneNumber = self.identityView.bindingPhoneNumber.text;
    if ([[self class] isBlankString:inputPhoneNumber]) {
        [XBLoadingView showHUDViewWithText:@"手机号不能为空"];
        return;
    }
    if (![HENLENSONG isValidateMobile:inputPhoneNumber]) {
        [XBLoadingView showHUDViewWithText:@"手机号码格式不正确"];
        return;
    }
    [XBLoadingView showHUDViewWithDefault];
    //发送验证码
    NSString *urlString = [NSString stringWithFormat:SERVERREQUESTURL(SENDSMS),inputPhoneNumber,self.identityView.userName.text];
    [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:urlString  WithRequestType:ONE WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        [XBLoadingView hideHUDViewWithDefault];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            [XBLoadingView showHUDViewWithText:@"发送验证码成功"];
            [weakSelf.identityView.SendButton setTitle:@"60" forState:UIControlStateNormal];
            weakSelf.identityView.SendButton.enabled = NO;
            weakSelf.sendTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(SendbuttonChangetitle) userInfo:nil repeats:YES];
        }else
        {
            [XBLoadingView showHUDViewWithText:returnValue[@"message"]];
        }
    }WithFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

#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 class] isBlankString:self.identityView.verificationCode.text]) {
        [XBLoadingView showHUDViewWithText:@"验证码不能为空"];
        return;
        
    } else {
        
        [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;
        }];
    }
}


#pragma mark -修改密码
- (void)ChangPassWordRequest
{
    if ([[self class] isBlankString:self.resetPasswordView.newpass.text]) {
        [XBLoadingView showHUDViewWithText:@"新密码为空"];return;
    }
    if ([[self class] isBlankString:self.resetPasswordView.confirmNewpass.text]){
        [XBLoadingView showHUDViewWithText:@"确认密码为空"];return;
    }
    if (![self.resetPasswordView.newpass.text isEqualToString:self.resetPasswordView.confirmNewpass.text]) {
        [XBLoadingView showHUDViewWithText:@"两次密码不相同"];return;
    }
    [XBLoadingView showHUDViewWithDefault];
    //重置密码接口
    ResetPasswordRequest *passwrod = [[ResetPasswordRequest alloc]init];
    passwrod.fnewPassword = self.resetPasswordView.newpass.text;
    passwrod.username = self.userName.text;
    passwrod.smsCode = self.identityView.verificationCode.text;
    WS(weakSelf);
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:SERVERREQUESTURL(RESETPASSWORD)  WithRequestType:ZERO WithParameter:passwrod WithReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            [XBLoadingView showHUDViewWithText:@"重置密码成功"];
            weakSelf.passWord.text = weakSelf.resetPasswordView.newpass.text;
            [weakSelf judgeUserNameAndPassword];
        }else
        {
           [XBLoadingView showHUDViewWithText:returnValue[@"message"]];
        }
    } WithFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
        [XBLoadingView hideHUDViewWithDefault];
    }];
}



#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 = @"";
}

#pragma mark - 检测更新
- (void)detectionUpdateVersion
{
    NSString *path = [[NSBundle mainBundle]pathForResource:@"Info" ofType:@"plist"];
    NSDictionary* content =[NSDictionary dictionaryWithContentsOfFile:path];
    NSString *version = [content valueForKey:@"CFBundleShortVersionString"];
    //获取服务端版本大小
    WS(weakSelf);
    NSString *string = [NSString stringWithFormat:@"/employee/getUpgrade?apptype=IOS&version=%@",version];
    [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:SERVERREQUESTURL(string)  WithRequestType:ONE WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            NSDictionary *dict = returnValue[@"data"];
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"发现新版本%@,快去更新吧!",dict[@"version"]] preferredStyle:UIAlertControllerStyleAlert];
            [alertVC addAction:[UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:dict[@"url"]]];
//                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-services://?action=download-manifest&url=http://www.pgyer.com/app/plist/95fcb4e47cf3d6c7309a2760ccccde66"]];
            }]];
            //是否强制更新
            if (![dict[@"forceupdate"] isEqualToString:@"1"]) {
                [alertVC addAction:[UIAlertAction actionWithTitle:@"以后再说" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    [weakSelf dismissViewControllerAnimated:YES completion:nil];
                }]];
            }
            [weakSelf presentViewController:alertVC animated:YES completion:nil];
        }
    } WithFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

@end