//
//  KWMEditAddressVC.m
//  iCemarose
//
//  Created by HouWeiBin on 16/9/5.
//  Copyright © 2016年 kollway. All rights reserved.
//

#import "KWMEditAddressVC.h"
#import "KWMStringUtil.h"

@interface KWMEditAddressVC ()

@end

@implementation KWMEditAddressVC{
    BUYAddress *requestAddress;
}

+(NSString *)kwmTag{
    return @"KWMEditAddressVC";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"选择地址";
    self.client.customerToken = [BUYCustomerToken customerTokenWithJSONDictionary:[[NSUserDefaults standardUserDefaults] objectForKey:@"token"]];
    [self initTitle];
    [self updateAddress];
    [self initTextField];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onClickBackgroundView:)];
    [self.view addGestureRecognizer:tapGesture];
}

- (void)onClickBackgroundView:(UITapGestureRecognizer *)tapGesture{
    [self.tfCountry resignFirstResponder];
    [self.tfProvince resignFirstResponder];
    [self.tfCity resignFirstResponder];
    [self.tfAddress resignFirstResponder];
    [self.tfAddressDetail resignFirstResponder];
    [self.tfZip resignFirstResponder];
    [self.tfName resignFirstResponder];
    [self.tfPhone resignFirstResponder];
}


-(void)initTextField{
    //http://www.cocoachina.com/bbs/read.php?tid-250044-page-8.html  #78
    //tf为无边框模式时,输入中文会导致文字下沉的问题。
    self.tfName.borderStyle = UITextBorderStyleNone;
    self.tfPhone.borderStyle = UITextBorderStyleNone;
    self.tfCountry.borderStyle = UITextBorderStyleNone;
    self.tfProvince.borderStyle = UITextBorderStyleNone;
    self.tfCity.borderStyle = UITextBorderStyleNone;
    self.tfAddress.borderStyle = UITextBorderStyleNone;
    self.tfAddressDetail.borderStyle = UITextBorderStyleNone;
    self.tfZip.borderStyle = UITextBorderStyleNone;
    
    self.tfName.delegate = self;
    self.tfPhone.delegate = self;
    self.tfCountry.delegate = self;
    self.tfProvince.delegate = self;
    self.tfCity.delegate = self;
    self.tfAddress.delegate = self;
    self.tfAddressDetail.delegate = self;
    self.tfZip.delegate = self;
    
    [self.tfProvince setTextFiledCountLimit:10];
    [self.tfCity setTextFiledCountLimit:10];
    [self.tfName setTextFiledCountLimit:10];
    [self.tfAddress setTextFiledCountLimit:50];
    [self.tfAddressDetail setTextFiledCountLimit:50];
    
    self.tfCountry.tag = 0;
    self.tfProvince.tag = 1;
    self.tfCity.tag = 2;
    self.tfAddress.tag = 3;
    self.tfAddressDetail.tag = 4;
    self.tfZip.tag = 5;
    self.tfName.tag = 6;
    self.tfPhone.tag = 7;
}

- (void)initTitle{
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"存储" style:UIBarButtonItemStylePlain target:self action:@selector(clickRightButton)];
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(clickLeftButton)];
    self.navigationItem.rightBarButtonItem = rightButton;
    self.navigationItem.leftBarButtonItem = leftButton;
    [self.navigationItem hidesBackButton];
}

- (void)updateAddress{
    if (_address) {
        self.tfName.text = _address.lastName;
        self.tfPhone.text = _address.phone;
        self.tfCountry.text = _address.country;
        self.tfProvince.text = _address.province;
        self.tfCity.text = _address.city;
        self.tfAddress.text = _address.address1;
        self.tfAddressDetail.text = _address.address2;
        self.tfZip.text = _address.zip;
    }
}

//点击存储按钮
-(void)clickRightButton{
    if([KWMStringUtil isEmpty:self.tfCountry.text]){
        [self showToast:@"请输入国家"];
    }else if([KWMStringUtil isEmpty:self.tfProvince.text]){
        [self showToast:@"请输入省份"];
    }else if([KWMStringUtil isEmpty:self.tfCity.text]){
        [self showToast:@"请输入城市"];
    }else if([KWMStringUtil isEmpty:self.tfAddress.text]){
        [self showToast:@"请输入地址"];
    }else if([KWMStringUtil isEmpty:self.tfZip.text]){
        [self showToast:@"请输入邮政编码"];
    }else if([KWMStringUtil isEmpty:self.tfName.text]){
        [self showToast:@"请输入姓名"];
    }else if([KWMStringUtil isEmpty:self.tfPhone.text]){
        [self showToast:@"请输入手机号"];
    }else{
        if(self.address == nil){
            [self addAddress];
        }else{
            [self editAddress];
        }
//        [self performSelector:@selector(delayMethod) withObject:nil afterDelay:0.3f];
    }
}

- (void)delayMethod {
     [self showToast:@"存储成功"];
     [[self navigationController] popViewControllerAnimated:YES];
}


//点击取消按钮
-(void)clickLeftButton{
    [[self navigationController] popViewControllerAnimated:YES];
}

-(BUYAddress *)getAddress{
    if(self.address!=nil){
        requestAddress = self.address;
    }else{
        requestAddress = [[BUYAddress alloc] initWithModelManager:self.client.modelManager JSONDictionary:nil];
    }
    NSString *country = [self.tfCountry.text trim];
    requestAddress.lastName = [self.tfName.text trim];
    requestAddress.phone = [self.tfPhone.text trim];
    requestAddress.province = [self.tfProvince.text trim];
    requestAddress.provinceCode = 0;
    requestAddress.city = [self.tfCity.text trim];
    requestAddress.address1 = [self.tfAddress.text trim];
    requestAddress.address2 = [self.tfAddressDetail.text trim];
    requestAddress.country = [country isEqualToString:@"中国"] ? @"China" : country;
    requestAddress.countryCode = @"";
    requestAddress.zip = [self.tfZip.text trim];
    requestAddress.firstName = [(requestAddress.firstName?requestAddress.firstName:@"") trim];
    return requestAddress;
}

-(void)showAddressError:(NSError *)error{
    if(error && error.userInfo){
        NSString *errorInfoString = [NSString stringWithFormat:@"%@",error.userInfo];
        if(errorInfoString){
            if([errorInfoString rangeOfString:@"province"].location != NSNotFound &&
               [errorInfoString rangeOfString:@"is not valid"].location != NSNotFound){
                [self showToast:@"请填写正确的省份,例如美国的亚拉巴马州则填写:Alabama"];
                return;
            }
            if([errorInfoString rangeOfString:@"country"].location != NSNotFound &&
               [errorInfoString rangeOfString:@"is not a valid"].location != NSNotFound){
                [self showToast:@"请填写正确的国家,例如美国则填写:United States"];
                return;
            }
        }
    }
    [self showToast:@"更新地址失败"];
}


-(void)addAddress{
    [self showLoading];
    [self.client createAddress:[self getAddress] callback:^(BUYAddress *address, NSError *error) {
        [self hideLoading];
        if(error!=nil){
            [self showAddressError:error];
        }else if(address!=nil){
            self.address = address;
            [self updateCustomerAddress];
            [self showToast:@"更新地址成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
    }];
}

-(void)editAddress{
    [self showLoading];
    [self.client updateAddress:[self getAddress] callback:^(BUYAddress *address, NSError *error) {
        [self hideLoading];
        NSLog(@"error  = %@",error);
        if (error != nil) {
            [self showAddressError:error];
        }else if(address != nil){
            [self updateCustomerAddress];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
    }];
}




- (void)updateCustomerAddress{
    [self showLoading];
    [self.client getCustomerCallback:^(BUYCustomer * _Nullable customer, NSError * _Nullable error) {
        [self showToast:@"更新地址成功"];
        [self hideLoading];
        if (error == nil && customer != nil) {
            [[NSUserDefaults standardUserDefaults] setObject:customer.JSONDictionary forKey:@"customer"];
        }
        if (error != nil) {
            [self showError:error];
        }
    }];
}




- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
//    return ![string isEqualToString:@" "];
    return YES;
}

#pragma mark - UITextFieldDelegate
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    NSInteger tag = textField.tag;
    NSInteger removeTag = tag - 2;
    if(removeTag < 0){
        removeTag = 0;
    }
    self.marginTopOfCountry.constant = 30 - 57 * removeTag;
    [UIView animateWithDuration:0.5 animations:^{
        [self.view layoutIfNeeded];
    }];
    
    return YES;
}

//键盘弹出
-(void)keyboardWillHide:(NSNotification *)notification{
    self.marginTopOfCountry.constant = 30;
    [UIView animateWithDuration:0.5 animations:^{
        [self.view layoutIfNeeded];
    }];
    
}




@end