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

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

@interface UserViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@end

@implementation UserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [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.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.rebateBackView.layer.masksToBounds = YES;
    self.rebateBackView.layer.borderWidth = 1.0f;
    self.rebateBackView.layer.borderColor = kMainBlueColor.CGColor;
    self.rebateBackView.layer.cornerRadius = 20;
    [self.rebateBackView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(rebateViewClickAction:)]];
    self.userName.text = [Shoppersmanager manager].userNameString;
    self.passWord.text = [Shoppersmanager manager].passWordString;
    self.userHeader.userInteractionEnabled = YES;
    NSString *headerurl = [Shoppersmanager manager].Shoppers.employee.picture;
    [self.userHeader sd_setImageWithURL:[NSURL URLWithString:headerurl] placeholderImage:ReplaceImage];
    [self.userHeader addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(userHeaderClickAction:)]];
}

#pragma mark -查询返利金额
- (void)queryShoppersCommission
{
    [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:[NSString stringWithFormat:@"%@%@",SERVERREQUESTURL(SHOPPERSCOMMISSION),[Shoppersmanager manager].Shoppers.employee.fid] WithRequestType:1 WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
//            self.rebateLabe.text = [NSString stringWithFormat:@"¥%.2f",[returnValue[@"data"] floatValue]];
        }
    } WithErrorCodeBlock:^(id errorCodeValue) {
    } WithFailureBlock:^(id error) {
    }];
}


#pragma mark -返利余额点击
- (void)rebateViewClickAction:(UITapGestureRecognizer *)tap
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ShowMyAccountVC" object:nil];
}

#pragma mark -用户头像点击
- (void)userHeaderClickAction:(UITapGestureRecognizer *)tap
{
    UIAlertController *alertView = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIImagePickerController *PcCamera = [[UIImagePickerController alloc]init];
    PcCamera.delegate = self;
    [DeviceDirectionManager instance].isHorizontal=YES;
    [alertView addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //拍照
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            [PcCamera setSourceType:UIImagePickerControllerSourceTypeCamera];
            PcCamera.allowsEditing = YES;
            [self presentViewController:PcCamera animated:YES completion:nil];
        }
        else
        {
            [DeviceDirectionManager instance].isHorizontal=NO;
            [self ErrorMBProgressView:@"相机无法使用"];
        }
    }]];
    [alertView addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //从相册中选择
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            [PcCamera setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            PcCamera.allowsEditing = YES;
            [self presentViewController:PcCamera animated:YES completion:nil];
        }
        else
        {
            [DeviceDirectionManager instance].isHorizontal=NO;
            [self ErrorMBProgressView:@"相册无法打开"];
        }
    }]];
    [alertView addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [DeviceDirectionManager instance].isHorizontal=NO;
        [alertView dismissViewControllerAnimated:YES completion:nil];
    }]];
    [self presentViewController:alertView animated:YES completion:nil];
}

#pragma mark -拍照、从相册选择
#pragma -mark -UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [DeviceDirectionManager instance].isHorizontal=NO;
    [self dismissViewControllerAnimated:YES completion:nil];
    UIImage *Headimage = [info objectForKey:UIImagePickerControllerOriginalImage];
    __weak typeof(self) weskSelf = self;
    //修改并保存头像
    [self uploadUserHeader:Headimage completeBlock:^(NSString *string) {
        weskSelf.userHeader.image = Headimage;
        [Shoppersmanager manager].Shoppers.employee.picture = string;
    }];
}

#pragma mark -保存选中头像、并上传
- (void)uploadUserHeader:(UIImage *)image completeBlock:(void(^)(NSString *string))complete
{
    WS(weakSelf);
    NSData *data = UIImageJPEGRepresentation(image, 0.5);
    [[NetworkRequestClassManager Manager] UploadImageWithURL:SERVERREQUESTURL(UPLOADHEADER) WithRequestType:1 WithImageDatas:data WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            [weakSelf modifyshoppersInformation:returnValue[@"data"] complete:^{
                 complete(returnValue[@"data"]);
            }];
        }else
        {
            [weakSelf ErrorMBProgressView:returnValue[@"message"]];
        }
    } WithprogressBlock:^(double progress) {
        
        if (progress >= 1) {
            weakSelf.TCHud.labelText = @"上传完成";
            [weakSelf RemoveMBProgressHUDLoding];
        }else
        {
            [weakSelf ShowProgressView:progress];
        }
    } WithErrorCodeBlock:^(id errorCodeValue) {
        weakSelf.TCHud.labelText = @"上传失败";
        [weakSelf RemoveMBProgressHUDLoding];
    } WithFailureBlock:^(NSError *error) {
        weakSelf.TCHud.labelText = @"上传失败";
        [weakSelf RemoveMBProgressHUDLoding];
    }];
}


#pragma mark -上传完成修改导购个人信息
- (void)modifyshoppersInformation:(NSString *)headerurl complete:(void(^)())block
{
    [self CreateMBProgressHUDLoding];
    RsEmployeeRequest *employ = [[RsEmployeeRequest alloc]init];
    employ.employee = [Shoppersmanager manager].Shoppers.employee;
    employ.employee.picture = headerurl;
    WS(weakSelf);
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:SERVERREQUESTURL(MODITYSHOPPERSINFORMATION) WithRequestType:0 WithParameter:employ WithReturnValueBlock:^(id returnValue) {
        
        [weakSelf RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            block();
            [weakSelf SuccessMBProgressView:@"修改成功"];
        }else
        {
            [weakSelf ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        [weakSelf RemoveMBProgressHUDLoding];
    } WithFailureBlock:^(NSError *error) {
        [weakSelf RemoveMBProgressHUDLoding];
    }];
}

#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:SERVERREQUESTURL(CANCELLOGIN) WithRequestType:1 WithParameter:nil WithReturnValueBlock:^(id returnValue) {
            
            [weakSelf RemoveMBProgressHUDLoding];
            if ([returnValue[@"code"] isEqualToNumber:@0]) {
                
                [Shoppersmanager manager].currentCustomer = NO;
                [Customermanager manager].model = nil;
                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];
    LoginInfo *login = [[LoginInfo alloc]init];
    login.username = self.userName.text;
    login.password = self.passWord.text;
    WS(weakSelf);
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:SERVERREQUESTURL(LOGIN) WithRequestType:0 WithParameter:login WithReturnValueBlock:^(id returnValue) {
        
        [weakSelf RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            [weakSelf SuccessMBProgressView:@"登陆成功"];
            LoginResult *result = [[LoginResult alloc] initWithDictionary:returnValue[@"data"] error:nil];
            [Shoppersmanager manager].userNameString = weakSelf.userName.text;
            [Shoppersmanager manager].passWordString = weakSelf.passWord.text;
            [Shoppersmanager manager].currentCustomer = NO;
            [Shoppersmanager manager].Shoppers = result;
            [[NSNotificationCenter defaultCenter] postNotificationName:@"CHANGESHOPPERSNAME" object:result.employee.realName];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"CHANGECUSTOMERNAME" object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"EMPTYCUSTOMERNAME" object:nil];//情况当前客户数据
            //保存用户名密码
            [[NSUserDefaults standardUserDefaults] setObject:weakSelf.userName.text forKey:USERNAME];
            [[NSUserDefaults standardUserDefaults] setObject:weakSelf.passWord.text forKey:PASSWORD];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
            
        }else
        {
            [weakSelf ErrorMBProgressView:returnValue[@"message"]];
            [weakSelf recoveryUsernamePasswrod];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
        NSLog(@"%@",errorCodeValue);
        
    } WithFailureBlock:^(id error) {
        
        [weakSelf RemoveMBProgressHUDLoding];
        [weakSelf 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.
}

@end