//
//  SettingViewController.m
//  ALand
//
//  Created by Z on 16/4/21.
//  Copyright © 2016年 Z. All rights reserved.
//

#import "SettingViewController.h"
#import "SDImageCache.h"
#import "ChangeUserSignatureViewController.h"
#import "SelectPhotoView.h"
#import "CoverShadowView.h"
#import "ChangePasswordViewController.h"
#import "AboutViewController.h"
@interface SettingViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *imageViewIcon;
@property (weak, nonatomic) IBOutlet UILabel *signature;//个性签名
@property (weak, nonatomic) IBOutlet UILabel *phoneNumber;

@property (nonatomic, strong) SelectPhotoView *photoView;
@property (nonatomic, strong) CoverShadowView *shadowView;

@property (weak, nonatomic) IBOutlet UIView *viewMessage;
@property (weak, nonatomic) IBOutlet UIView *viewWithdraw;
@property (weak, nonatomic) IBOutlet UIView *viewPhoneNum;

@end

@implementation SettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setDefaults];
    [self setInfos];
    [self.viewMessage removeFromSuperview];
    [self.viewWithdraw removeFromSuperview];
    [self.viewPhoneNum removeFromSuperview];
    // Do any additional setup after loading the view from its nib.
}

- (void)setDefaults {
    if ([UserInfo shareInstance].mobilephone.length > 10) {
        
        NSString *cutPhoneNumber = [[UserInfo shareInstance].mobilephone substringWithRange:NSMakeRange(7, 4)];
        self.phoneNumber.text = [NSString stringWithFormat:@"手机号码（%@）", cutPhoneNumber];
    }
    self.title = @"设置";
    
    self.imageViewIcon.layer.cornerRadius = self.imageViewIcon.width/2;
    self.imageViewIcon.layer.masksToBounds = YES;
}



#pragma mark - action

- (IBAction)actionAbout:(id)sender {
    AboutViewController *aboutVC = [[AboutViewController alloc] init];
    aboutVC.isShowNavigationBar = YES;
    aboutVC.title = @"关于";
    [self.navigationController pushViewController:aboutVC animated:YES];
}

- (IBAction)loginOut:(id)sender
{
    [[HTTPCilent shareCilent] GET:@"app/resellerLogout" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        WS(weakSelf)
        if ([responseObject[@"code"] isEqualToNumber:@0]) {
            
            [MBProgressHUD Javen_showSuccess:@"注销成功！" onView:weakSelf.view delay:0.5 complete:^{
                [MobClick profileSignOff];
                [self.tabBarController dismissViewControllerAnimated:YES completion:nil];
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"passWord"];
                
            }];
            
        }else{
            [MBProgressHUD Javen_showError:@"注销异常" onView:weakSelf.view delay:0.5 complete:nil];
            
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}

- (IBAction)actionClearCache:(id)sender
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    WS(weakSelf)
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
        [hud hide:YES];
        
        [MBProgressHUD Javen_showSuccess:@"清理成功！" onView:weakSelf.view delay:0.7 complete:nil];
        
    }];
}

- (IBAction)actionChangIcon:(id)sender
{
    [self show];
}

/** chage signature */
- (IBAction)actionSetSignature:(id)sender
{
    ChangeUserSignatureViewController *changeSignatureVC = [[ChangeUserSignatureViewController alloc] init];
    changeSignatureVC.isShowNavigationBar = YES;
    changeSignatureVC.title = @"设置签名";
    changeSignatureVC.reseller = self.reseller;
    [self PushViewController:changeSignatureVC animated:YES];
}

- (IBAction)actionChangePassword:(id)sender
{
    ChangePasswordViewController *changeVC = [[ChangePasswordViewController alloc] init];
    changeVC.isShowNavigationBar = YES;
    [self.navigationController pushViewController:changeVC animated:YES];
}

- (SelectPhotoView *)photoView
{
    if (!_photoView) {
        _photoView = [SelectPhotoView viewWithNibName:@"SelectPhotoView"];
        _photoView.frame = CGRectMake(0, kHeight, kWidth, 100);
        _shadowView = [[CoverShadowView alloc] initOnTopWithHeight:kHeight];
        [self.view.window addSubview:_shadowView];
        [_shadowView addSubview:_photoView];
        
        WS(weakSelf)
        //拍照
        _photoView.takePhotoBlock = ^{
            [weakSelf takePhotoAction];
            
        };
        
        //相册
        _photoView.galleryBlock = ^{
            [weakSelf gallery];
        };
        
        //阴影点击事件
        _shadowView.tapAction = ^{
            [weakSelf hide];
        };
        
    }
    
    return _photoView;
}



- (void)takePhotoAction {
    [self hide];
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"找不到相机" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    } else {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        //        picker.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
        picker.videoQuality = UIImagePickerControllerQualityTypeLow;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

- (void)gallery {
    [self hide];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES;//是否可以编辑
        //打开相册选择照片
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        // 模态进入相册
        [self presentViewController:picker animated:YES completion:nil];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //得到图片
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];

    [MBProgressHUD Javen_showMessage:@"修改中" onView:self.view];
    
    //上传七牛
    WS(weakSelf)
    [[JavenQNManager shareInstance] upLoadImage:image isMD5Name:YES name:nil commpelete:^(NSString *key) {
        
        self.reseller.portrait = [NSString stringWithFormat:@"http://7xtefo.com2.z0.glb.qiniucdn.com/%@", key];
        NSDictionary *params = [self getParamsWithReseller:self.reseller];
        
        //上传成功之后把URL传给aland服务器
        [weakSelf changeResellerInfoWithDic:params];
        
    }];
    
    
    // 模态返回
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

//生成上传图片URL的参数
- (NSDictionary *)getParamsWithReseller:(JavenResellerBigModel *)resellerModel {
//    resellerModel.ownerOrg = nil;
    UserInfo *user = [UserInfo shareInstance];
    NSDictionary *reseller = [resellerModel dictionaryRepresentation];
    NSDictionary *params = @{@"operCtx" : @{@"time" : [[NSDate date] timeStampNumber],
                                            @"domain" : kDomain,
                                            @"operator" : @{@"id" : user.uuid,
                                                            @"fullName" : user.name}},
                             @"reseller" : reseller};
    return params;
}

/** 把修改的信息上传到服务器 */
- (void)changeResellerInfoWithDic:(NSDictionary *)params
{
    WS(weakSelf)
    [[HTTPCilent shareCilent] POST:@"reseller/save" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        [MBProgressHUD hideHUDForView:weakSelf.view];
        
        if ([responseObject[@"code"] isEqualToNumber:@0]) {
            [MBProgressHUD Javen_showSuccess:@"修改成功！" onView:weakSelf.view  delay:0.7 complete:^{
                [weakSelf setUpdata];
            }];
        }else{
            [MBProgressHUD Javen_showError:responseObject[@"message"] onView:weakSelf.view delay:0.7 complete:nil];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
}


/**
 *  显示阴影和底部的弹框
 */
- (void)show {
    [self.photoView showView];
    [self.shadowView show];
}

- (void)hide {
    [self.photoView hideView];
    [self.shadowView hide];
}



- (void)setUpdata {
    WS(weakSelf)
    [[HTTPCilent shareCilent] GET:[NSString stringWithFormat:@"reseller/get/%@", [UserInfo shareInstance].uuid] parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        if ([responseObject[@"code"] isEqualToNumber:@0]) {
            weakSelf.reseller = [JavenResellerBigModel modelObjectWithDictionary:responseObject[@"reseller"]];
            
            [weakSelf setInfos];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}


- (void)changeSignature:(NSString *)signature {
    [MBProgressHUD Javen_showMessage:@"修改中" onView:self.view];
    self.reseller.internalBaseClassDescription = signature;
    NSDictionary *params = [self getParamsWithReseller:self.reseller];
    [self changeResellerInfoWithDic:params];
}

- (void)setInfos {
    [self.imageViewIcon sd_setImageWithURL:[NSURL URLWithString:self.reseller.portrait] placeholderImage:kUserIconPlaceHolderImage];
    self.signature.text = self.reseller.internalBaseClassDescription;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setUpdata];
}

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