//
//  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"
#import "JPUSHService.h"


@interface UserViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@end

@implementation UserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self uiConfigAction];
    [self addGestureRecognizer];
}

#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.guideIntegralView.layer.masksToBounds = YES;
    self.guideIntegralView.layer.borderWidth = 1.0f;
    self.guideIntegralView.layer.borderColor = kMainBlueColor.CGColor;
    self.guideIntegralView.layer.cornerRadius = 20;
    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:GuideReplaceImage];
}

#pragma mark - 添加添加手势
- (void)addGestureRecognizer
{
    [self.rebateBackView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(rebateViewClickAction:)]];
    [self.guideIntegralView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(guideIntegralViewClickAction:)]];
    [self.userHeader addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(userHeaderClickAction:)]];
}

#pragma mark -我的账户点击
- (void)rebateViewClickAction:(UITapGestureRecognizer *)tap
{
    SHARED_APPDELEGATE.tabBarController.selectedIndex = 4;
    [SHARED_APPDELEGATE.tabBarController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 我的积分
- (void)guideIntegralViewClickAction:(UITapGestureRecognizer *)sender
{
    SHARED_APPDELEGATE.tabBarController.selectedIndex = 5;
    [SHARED_APPDELEGATE.tabBarController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -用户头像点击
- (void)userHeaderClickAction:(UITapGestureRecognizer *)tap
{
    // 判断应用是否有使用相机的权限
    if([BaseViewController determineCameraPermissions]){
        UIImagePickerController *PcCamera = [[UIImagePickerController alloc]init];
        PcCamera.delegate = self;
        [DeviceDirectionManager instance].isHorizontal=YES;
        WS(weakSelf);
        ShowAlertView(@"请选择", nil, @[@"拍照",@"从相册选择",@"取消"], UIAlertControllerStyleAlert, ^(NSInteger index) {
            if (index == ZERO) {
                //拍照
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                    [PcCamera setSourceType:UIImagePickerControllerSourceTypeCamera];
                    PcCamera.allowsEditing = YES;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf presentViewController:PcCamera animated:YES completion:nil];
                    });
                }
                else
                {
                    [XBLoadingView showHUDViewWithText:@"相机无法使用"];
                    [DeviceDirectionManager instance].isHorizontal=NO;
                }
            }else if (index == ONE) {
                //从相册中选择
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                    [PcCamera setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
                    PcCamera.allowsEditing = YES;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf presentViewController:PcCamera animated:YES completion:nil];
                    });
                }
                else
                {
                    [XBLoadingView showHUDViewWithText:@"相册无法打开"];
                    [DeviceDirectionManager instance].isHorizontal=NO;
                }
            }else {
                [DeviceDirectionManager instance].isHorizontal=NO;
            }
        });
    }
 }

#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];
    WS(weakSelf);
    //修改并保存头像
    [self uploadUserHeader:Headimage completeBlock:^(NSString *string) {
        weakSelf.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);
    XBLoadingView *progressView = [XBLoadingView showHUDViewProgressLabel:@"上传头像中"];
    [HTTP uploadImageWithURL:SERVERREQUESTURL(UPLOADHEADER) withRequestType:ONE withImageDatas:data withParameter:nil withReturnValueBlock:^(id returnValue) {
        
        if (RESULT(returnValue)) {
            [weakSelf modifyshoppersInformation:RESPONSE(returnValue) complete:^{
                 complete(RESPONSE(returnValue));
            }];
        }else
        {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    } withprogressBlock:^(double progress) {
        
        if (progress >= 1) {
            dispatch_async(dispatch_get_main_queue(), ^{
                progressView.labelText = @"上传完成";
                [progressView hide:YES afterDelay:1];
            });
 
        }else{
            progressView.progress = progress;
        }
    } withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}


#pragma mark -上传完成修改导购个人信息
- (void)modifyshoppersInformation:(NSString *)headerurl complete:(void(^)())block
{
    [XBLoadingView showHUDViewWithDefault];
    RsEmployeeRequest *employ = [[RsEmployeeRequest alloc]init];
    employ.employee = [Shoppersmanager manager].shoppers.employee;
    employ.employee.picture = headerurl;
    [HTTP networkRequestWithURL:SERVERREQUESTURL(MODITYshoppersINFORMATION)  withRequestType:ZERO withParameter:employ withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            block();
            [XBLoadingView showHUDViewWithSuccessText:@"修改成功" completeBlock:nil];
        }else
        {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    }withFailureBlock:^(NSError *error) {
        [XBLoadingView hideHUDViewWithDefault];
    }];
}

#pragma mark -修改密码
- (IBAction)ChangPasswordButtonClick:(UIButton *)sender {

    if ([self.delegate respondsToSelector:@selector(changPasswordButtonClick)]) {
        [self.delegate changPasswordButtonClick];
    }
}

#pragma mark -注销《切换用户》
- (IBAction)cancellationButtonClick:(UIButton *)sender {
    
    WS(weakSelf);
    ShowAlertView(@"提示", @"切换用户将清空用户数据，是否继续?", @[@"确认",@"取消"], UIAlertControllerStyleAlert, ^(NSInteger index) {
        if (index == ONE) {
            return;
        }
        //清除极光别名
        [JPUSHService setTags:nil alias:@"" callbackSelector:nil object:nil];
        [XBLoadingView showHUDViewWithDefault];
        [HTTP networkWithDictionaryRequestWithURL:SERVERREQUESTURL(CANCELLOGIN)  withRequestType:ONE withParameter:nil withReturnValueBlock:^(id returnValue) {
            
            [XBLoadingView hideHUDViewWithDefault];
            if (RESULT(returnValue)) {
                
                [Shoppersmanager manager].currentCustomer = NO;
                [Customermanager manager].model = nil;
                LoginViewController *loginVC = [[[weakSelf class] getMainStoryboardClass] instantiateViewControllerWithIdentifier:@"Login"];
                [[weakSelf class] deleteAccountAndPassWord];
                [weakSelf restoreRootViewController:loginVC];
                
            }else
            {
                ShowAlertView(@"提示", @"切换用户失败", @[@"我知道了"], UIAlertControllerStyleAlert, nil);
            }
        } withFailureBlock:^(id error) {
            [XBLoadingView hideHUDViewWithDefault];
        }];
    });
}


#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 class] isBlankString:self.userName.text]) {
        
        [XBLoadingView showHUDViewWithText:@"用户名不能为空"];return;
    }
    if ([[self class] isBlankString:self.passWord.text]) {
        
        [XBLoadingView showHUDViewWithText:@"密码不能为空"];return;
    }
    [XBLoadingView showHUDViewWithDefault];
    LoginInfo *login = [[LoginInfo alloc]init];
    login.username = self.userName.text;
    login.password = self.passWord.text;
    WS(weakSelf);
    [HTTP networkRequestWithURL:SERVERREQUESTURL(LOGIN)  withRequestType:ZERO withParameter:login withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            
            [XBLoadingView showHUDViewWithSuccessText:@"登陆成功" completeBlock:nil];
            LoginResult *result = [[LoginResult alloc] initWithDictionary:RESPONSE(returnValue) error:nil];
            [Shoppersmanager manager].userNameString = weakSelf.userName.text;
            [Shoppersmanager manager].passWordString = weakSelf.passWord.text;
            [Shoppersmanager manager].currentCustomer = NO;
            [Shoppersmanager manager].shoppers = result;
            [Notification postNotificationName:CHANGEshoppersNAME object:result.employee.realName];
            [Notification postNotificationName:@"CHANGECUSTOMERNAME" object:nil];
            [Notification postNotificationName:@"EMPTYCUSTOMERNAME" object:nil];//清空当前客户数据
            //保存用户名密码
            [[weakSelf class] saveAccountAndPassWord:weakSelf.userName.text AndPassword:weakSelf.passWord.text];
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
            
        }else
        {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
            [weakSelf recoveryUsernamePasswrod];
        }
    } withFailureBlock:^(id error) {
        
        [XBLoadingView hideHUDViewWithDefault];
        [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
