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

#import "UserViewController.h"
#import "ChangePasswordViewController.h"
#import "LoginViewController.h"

@interface UserViewController ()

@end

@implementation UserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self uiConfigAction];
}

#pragma mark -UI
- (void)uiConfigAction
{
    self.userNameBack.layer.masksToBounds = YES;
    self.userNameBack.layer.cornerRadius = kCornerRadius;
    self.userNameBack.layer.borderWidth = 0.5;
    self.userNameBack.layer.borderColor = kMainBlueColor.CGColor;
    self.passWordBack.layer.masksToBounds = YES;
    self.passWordBack.layer.cornerRadius = kCornerRadius;
    self.passWordBack.layer.borderWidth = 0.5;
    self.passWordBack.layer.borderColor = kMainBlueColor.CGColor;
    self.cancellationButton.layer.masksToBounds = YES;
    self.cancellationButton.layer.cornerRadius = kCornerRadius;
    self.switchUser.layer.masksToBounds = YES;
    self.switchUser.layer.cornerRadius = kCornerRadius;
    self.changePassword.layer.masksToBounds = YES;
    self.changePassword.layer.cornerRadius = kCornerRadius;
    self.changePassword.layer.borderWidth = 0.5;
    self.changePassword.layer.borderColor = kMainBlueColor.CGColor;
    
    self.userName.text = [Shoppersmanager manager].userNameString;
    self.passWord.text = [Shoppersmanager manager].passWordString;
    
}




#pragma mark -修改密码
- (IBAction)ChangPasswordButtonClick:(UIButton *)sender {
    
    
    if ([self.delegate respondsToSelector:@selector(changPasswordButtonClick)]) {
        
        [self.delegate changPasswordButtonClick];
        
    }
}


#pragma mark -注销
- (IBAction)cancellationButtonClick:(UIButton *)sender {
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"注销将清空用户数据，是否继续?" preferredStyle:UIAlertControllerStyleAlert];
    
    __weak typeof(self) weakSelf = self;
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        [weakSelf CreateMBProgressHUDLoding];
        [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:[NSString stringWithFormat:@"%@%@",ServerAddress,@"/employee/logout"] WithRequestType:1 WithParameter:nil WithReturnValueBlock:^(id returnValue) {
            
            [weakSelf RemoveMBProgressHUDLoding];
            if ([returnValue[@"code"] isEqualToNumber:@0]) {
                
                UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                LoginViewController *loginVC = [storyboard instantiateViewControllerWithIdentifier:@"Login"];
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:USERNAME];
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:PASSWORD];
                [weakSelf restoreRootViewController:loginVC];
            }else
            {
                [weakSelf promptCustomerWithString:@"注销失败"];
            }
            
        } WithErrorCodeBlock:^(id errorCodeValue) {
            
        } WithFailureBlock:^(id error) {
            [weakSelf RemoveMBProgressHUDLoding];
        }];
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}


#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:UIViewAnimationOptionTransitionFlipFromBottom
                    animations:animation
                    completion:nil];
}


#pragma mark -切换账户
- (IBAction)switchUserButtonClick:(UIButton *)sender {
    
    
    if (self.userName.text.length == 0) {
        
        [self ErrorMBProgressView:@"用户名不能为空"];
        return;
    }
    if (self.passWord.text.length == 0) {
        
        [self ErrorMBProgressView:@"密码不能为空"];
        return;
    }
    
    [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].userNameString = self.userName.text;
            [Shoppersmanager manager].passWordString = self.passWord.text;
            [Shoppersmanager manager].Shoppers = result;
            
        }else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
            [self recoveryUsernamePasswrod];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
        NSLog(@"%@",errorCodeValue);
        
    } WithFailureBlock:^(id error) {
        
        [self RemoveMBProgressHUDLoding];
        [self recoveryUsernamePasswrod];
        
    }];
}


#pragma mark -切换失败后账户密码复原
- (void)recoveryUsernamePasswrod
{
    self.userName.text = [Shoppersmanager manager].userNameString;
    self.passWord.text = [Shoppersmanager manager].passWordString;
}





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