//
//  ModifyPWDViewController.m
//  TaiZhouTobacco_assets
//
//  Created by JianjiYuan on 14-5-20.
//  Copyright (c) 2014年 JianjiYuan. All rights reserved.
//

#import "ModifyPWDViewController.h"
#import "BRNetworkMgr.h"
#import "UITextField+EdgeInset.h"
#import "NSString+MD5.h"

@interface ModifyPWDViewController () < UITextFieldDelegate, BRNetworkMgrDelegate ,UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>
{
    
    UIImageView *imageVBg;
    
}
@property (nonatomic, strong) UITableView *tableVContent;

@property (nonatomic, strong) UIImageView *imageVLogo;
@property (nonatomic, strong) UITextField *textFOldPwd;
@property (nonatomic, strong) UITextField *textFNewPwd;
@property (nonatomic, strong) UITextField *textFConfirmNewPwd;
@property (nonatomic, strong) UIButton *btnModifyPwd;
@property (nonatomic, strong) UIButton *btnCancel;
@property (nonatomic,assign)  BOOL hasChanged;




- (void)btnModifyPwdClick:(id)sender;
- (void)btnCancelClick:(id)sender;

@end

@implementation ModifyPWDViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

//- (void)viewDidLoad
//{
//    [super viewDidLoad];
//    // Do any additional setup after loading the view from its nib.
//    self.title = @"修改密码";//////未显示
//    self.navigationItem.hidesBackButton = YES;
//    self.navigationItem.leftBarButtonItems = nil;
//    
//    self.navigationController.navigationBarHidden = YES;
//    
//    imageVBg = [UIImageView newAutoLayoutView];
//    imageVBg.image = [UIImage imageNamed:@"Login/mainbg_login.png"];
//    [self.view addSubview:imageVBg];
//    
//    [self setViewLayoutConstraint];
//    
//    [self registObserverOfTextInputView];
//    
//}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"修改密码";
    self.view.backgroundColor=[UIColor whiteColor];
    [self setViewLayoutConstraint];
    
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationItem.hidesBackButton = NO;
    
    self.navigationController.navigationBarHidden = NO ;

   // [self.navigationItem.rightBarButtonItem ]
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setViewLayoutConstraint
{
//    [imageVBg autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
//    [self.imageVLogo autoPinToTopLayoutGuideOfViewController:self withInset:100];
//    //[self.imageVLogo autoPinToTopLayoutGuideOfViewController:self withInset:60];
//    [self.imageVLogo autoSetDimensionsToSize:CGSizeMake(138, 64.5)];
//    [self.imageVLogo autoAlignAxisToSuperviewAxis:ALAxisVertical];
//    
//    [self.textFOldPwd autoSetDimensionsToSize:CGSizeMake(280, 35)];
//    [self.textFOldPwd autoAlignAxisToSuperviewAxis:ALAxisVertical];
//    [self.textFOldPwd autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.imageVLogo withOffset:20 relation:NSLayoutRelationLessThanOrEqual];
//    [self.textFOldPwd autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.imageVLogo withOffset:10 relation:NSLayoutRelationGreaterThanOrEqual];
//    
//    [self.textFNewPwd autoSetDimensionsToSize:CGSizeMake(280, 35)];
//    [self.textFNewPwd autoAlignAxisToSuperviewAxis:ALAxisVertical];
//    [self.textFNewPwd autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.textFOldPwd withOffset:20 relation:NSLayoutRelationLessThanOrEqual];
//    [self.textFNewPwd autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.textFOldPwd withOffset:10 relation:NSLayoutRelationGreaterThanOrEqual];
//    
//    [self.textFConfirmNewPwd autoSetDimensionsToSize:CGSizeMake(280, 35)];
//    [self.textFConfirmNewPwd autoAlignAxisToSuperviewAxis:ALAxisVertical];
//    [self.textFConfirmNewPwd autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.textFNewPwd withOffset:20 relation:NSLayoutRelationLessThanOrEqual];
//    [self.textFConfirmNewPwd autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.textFNewPwd withOffset:10 relation:NSLayoutRelationGreaterThanOrEqual];
//    
//    [self.btnModifyPwd autoSetDimensionsToSize:CGSizeMake((280-20)/2, 35)];
//    [self.btnModifyPwd autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:20];
//    [self.btnModifyPwd autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.textFConfirmNewPwd withOffset:40 relation:NSLayoutRelationLessThanOrEqual];
//    [self.btnModifyPwd autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.textFConfirmNewPwd withOffset:10 relation:NSLayoutRelationGreaterThanOrEqual];
//    
//    [self.btnCancel autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:self.btnModifyPwd withOffset:20];
//    [self.btnCancel autoAlignAxis:ALAxisHorizontal toSameAxisOfView:self.btnModifyPwd];
//    [self.btnCancel autoSetDimensionsToSize:CGSizeMake((280-20)/2, 35)];
    
    [self.tableVContent autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 0, 0) ];
  //  [self.tableVContent autoSetDimension:ALDimensionHeight toSize:165];
//    [self.btnModifyPwd autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:20];
//    [self.btnModifyPwd autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:20];
//    [self.btnModifyPwd autoSetDimension:ALDimensionHeight toSize:35];
//    [self.btnModifyPwd autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.tableVContent withOffset:8];
//    
    
}

- (BOOL)checkInputInvalid
{
    
    if (_textFOldPwd.text.length == 0) {
        [UIApplication showToastViewMessage:@"密码不能为空"];
        [_textFOldPwd becomeFirstResponder];
        return NO;
    }else if (_textFNewPwd.text.length == 0) {
        [UIApplication showToastViewMessage:@"请输入新密码"];
        [_textFNewPwd becomeFirstResponder];
        return NO;
    }else if (_textFConfirmNewPwd.text.length == 0) {
        [UIApplication showToastViewMessage:@"请输入确认新密码"];
        [_textFConfirmNewPwd becomeFirstResponder];
        return NO;
    }else if ([_textFOldPwd.text isEqualToString:_textFNewPwd.text]) {
        [UIApplication showToastViewMessage:@"新旧密码不能一样"];
        [_textFOldPwd becomeFirstResponder];
        return NO;
    }else if (![_textFNewPwd.text isEqualToString:_textFConfirmNewPwd.text]) {
        [UIApplication showToastViewMessage:@"确认密码与新密码不一致！"];
        [_textFConfirmNewPwd becomeFirstResponder];
        return NO;
    }
   // NSLog(@"输入的修改密码为： %@",_textFConfirmNewPwd.text);
    [self.view endEditing:YES];
    
    return YES;
}
-(void)btnBackClick:(id)sender
{
    if(self.hasChanged==YES)
    {
    
            [UIApplication showAlertViewWithTitle:@"警告" message:@"未提交修改，是否放弃已编辑的数据" delegate:self tag:100 cancelButtonTitle:@"放弃并返回" otherButtonTitles:@"继续编辑", nil];
    }
    else
         [self.navigationController popViewControllerAnimated:YES];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag == 100)
    {
        if(buttonIndex==0)
        
        [self.navigationController popViewControllerAnimated:YES];

    }
}


- (void)btnModifyPwdClick:(id)sender
{
    if ([self checkInputInvalid]) {
        [UIApplication showLoadingView:kTextShowInProgress];
        
       // NSString *interface = @"changePassword";
        //changePasswordEX
        NSString *interface = @"changePasswordEX";

        NSDictionary *dict = [UIApplication getObjectType:Dictionary key:kDictAutoLoginInfo];
        NSString *userName = @"";
        if ([dict valueForKey:kUserName]) {
            userName = [dict valueForKey:kUserName];
        }

        NSDictionary *dicParam = @{@"oldPassword":[[NSString stringWithFormat:@"%@%@",userName,_textFOldPwd.text]  MD5Digest],
                                   @"newPassword":[[NSString stringWithFormat:@"%@%@",userName,_textFNewPwd.text]  MD5Digest]};
//        AFHTTPRequestOperation *operation = [self.networkMgr operationWithURL:kBaseURL(interface)
//                                                                               interface:interface
//                                                                                  params:dicParam
//                                                                                dataType:BRNetMgrDataTypeJSON
//                                                                                  method:BRNetMgrMethodPost];
        AFHTTPRequestOperation *operation = [self.networkMgr operationWithURL:kBaseEXURL(interface)
                                                                    interface:interface
                                                                       params:dicParam
                                                                     dataType:BRNetMgrDataTypeJSON
                                                                       method:BRNetMgrMethodPost];
        [self.networkMgr startOperation:operation];

    }
    
}

#pragma mark =============  BRNetworkMgr Delegate  =============
- (void)httpOperationSuccess:(AFHTTPRequestOperation *)operation
                      result:(NSDictionary *)result
{
    [UIApplication showToastViewMessage:@"密码修改成功！"];
    
    //[self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)httpOperationFailed:(AFHTTPRequestOperation *)operation
                      error:(NSError *)error
{
    
}

- (void)btnCancelClick:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark =============  UITextField Delegate  =============

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    
    self.hasChanged=YES;
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([textField isEqual:_textFOldPwd]) {
        [_textFNewPwd becomeFirstResponder];
        return NO;
    }else if ([textField isEqual:_textFNewPwd]) {
        [_textFConfirmNewPwd becomeFirstResponder];
        return NO;
    }else if ([textField isEqual:_textFConfirmNewPwd]) {
        [self btnModifyPwdClick:nil];
    }
    return YES;
}



-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.textFOldPwd resignFirstResponder];
    [self.textFNewPwd resignFirstResponder];
    [self.textFConfirmNewPwd resignFirstResponder];
    
}






#pragma mark =============  LazyLoad Properties  =============

//- (UIImageView *)imageVLogo
//{//LOGIN。。。。
//    if (!_imageVLogo) {
//        self.imageVLogo = [UIImageView newAutoLayoutView];
//      //  _imageVLogo.image = [UIImage imageNamed:@"Login/logo_login.png"];
//        _imageVLogo.autoresizingMask = UIViewAutoresizingNone;
//        [self.view addSubview:_imageVLogo];
//    }
//    return _imageVLogo;
//}

//- (UITextField *)textFOldPwd
//{
//    if (!_textFOldPwd) {
//        self.textFOldPwd = [UITextField newAutoLayoutView];
//        _textFOldPwd.background = [UIImage imageNamed:@"Login/textfield_login.png"];
//        _textFOldPwd.placeholder = @"旧密码";
//        _textFOldPwd.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
//        _textFOldPwd.returnKeyType = UIReturnKeyNext;
//        [_textFOldPwd customLeftEdge:10];
//        _textFOldPwd.textColor=[UIColor blackColor];
//        _textFOldPwd.secureTextEntry = YES;
//        
//      //  [self.view addSubview:_textFOldPwd];
//    }
//    return _textFOldPwd;
//}

//- (UITextField *)textFNewPwd
//{
//    if (!_textFNewPwd) {
//        self.textFNewPwd = [UITextField newAutoLayoutView];
//        _textFNewPwd.background = [UIImage imageNamed:@"Login/textfield_login.png"];
//        _textFNewPwd.placeholder = @"新密码";
//        _textFNewPwd.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
//        _textFNewPwd.returnKeyType = UIReturnKeyNext;
//        [_textFNewPwd customLeftEdge:10];
//        _textFNewPwd.textColor = [UIColor blackColor];
//        _textFNewPwd.secureTextEntry = YES;
//
//        [self.view addSubview:_textFNewPwd];
//    }
//    return _textFNewPwd;
//}

//- (UITextField *)textFConfirmNewPwd
//{
//    if (!_textFConfirmNewPwd) {
//        self.textFConfirmNewPwd = [UITextField newAutoLayoutView];
//        _textFConfirmNewPwd.background = [UIImage imageNamed:@"Login/textfield_login.png"];
//        _textFConfirmNewPwd.placeholder = @"确认新密码";
//        _textFConfirmNewPwd.textColor = [UIColor whiteColor];
//        _textFConfirmNewPwd.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
//        _textFConfirmNewPwd.returnKeyType = UIReturnKeyDone;
//        [_textFConfirmNewPwd customLeftEdge:10];
//        _textFConfirmNewPwd.secureTextEntry = YES;
//        _textFConfirmNewPwd.textColor=[UIColor blackColor];
//        [self.view addSubview:_textFConfirmNewPwd];
//    }
//    return _textFConfirmNewPwd;
//}

//- (UIButton *)btnModifyPwd
//{
//    if (!_btnModifyPwd) {
//        self.btnModifyPwd = [UIButton buttonWithType:UIButtonTypeCustom];
//        _btnModifyPwd.translatesAutoresizingMaskIntoConstraints = NO;
//        [_btnModifyPwd setTitle:@"修 改" forState:UIControlStateNormal];
//        [_btnModifyPwd setTitleColor:RGBColor(54, 182, 242, 1) forState:UIControlStateNormal];
//        _btnModifyPwd.layer.borderColor = RGBColor(54, 182, 242, 1).CGColor;
//        _btnModifyPwd.layer.borderWidth = 1;
//        [_btnModifyPwd addTarget:self action:@selector(btnModifyPwdClick:) forControlEvents:UIControlEventTouchUpInside];
//        [self.view addSubview:_btnModifyPwd];
//    }
//    return _btnModifyPwd;
//}
//
//- (UIButton *)btnCancel
//{
//    if (!_btnCancel) {
//        self.btnCancel = [UIButton buttonWithType:UIButtonTypeCustom];
//        _btnCancel.translatesAutoresizingMaskIntoConstraints = NO;
////        _btnCancel.backgroundColor = RGBColor(0, 120, 193, 1);
//        [_btnCancel setBackgroundImage:[UIImage imageWithColor:RGBColor(54, 182, 242, 1)] forState:UIControlStateNormal];
//        [_btnCancel setTitle:@"取 消" forState:UIControlStateNormal];
//        [_btnCancel setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//        [_btnCancel addTarget:self action:@selector(btnCancelClick:) forControlEvents:UIControlEventTouchUpInside];
//        [self.view addSubview:_btnCancel];
//    }
//    return _btnCancel;
//}

- (UIButton *)btnModifyPwd
{
    if (!_btnModifyPwd) {
        self.btnModifyPwd = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnModifyPwd.translatesAutoresizingMaskIntoConstraints = NO;
        _btnModifyPwd.backgroundColor = [UIColor clearColor];
        [_btnModifyPwd setTitle:@"保存" forState:UIControlStateNormal];
        [_btnModifyPwd setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_btnModifyPwd setBackgroundImage:[UIImage imageNamed:@"Login/btn_login.png"] forState:UIControlStateNormal];
        [_btnModifyPwd addTarget:self action:@selector(btnModifyPwdClick:) forControlEvents:UIControlEventTouchUpInside];
       // [self.view addSubview:_btnModifyPwd];
    }
    return _btnModifyPwd;
}


#pragma mark =============  Properties Lazy Load  =============
- (UITableView *)tableVContent
{
    if (_tableVContent) {
        return _tableVContent;
    }
    self.tableVContent = [UITableView newAutoLayoutView];
    _tableVContent.backgroundColor = [UIColor whiteColor];
    
    _tableVContent.delegate = self;
    
    _tableVContent.dataSource = self;
    _tableVContent.separatorStyle = UITableViewCellSeparatorStyleNone;

      _tableVContent.separatorColor=RGBColor(153, 153, 153, 0.8 );
    
    
    // _tableVContent.separatorInset=UIEdgeInsetsMake(0, 10, 0, 10);
    
    
    [self.view addSubview:_tableVContent];
    return _tableVContent;
}



#pragma mark =============  UITableView DataSource  =============

- (void)configureCell:(UITableViewCell *)cell forIndexPath:(NSIndexPath *)indexPath
{
    cell.textLabel.textColor = [UIColor colorWithRed:0.2314 green:0.7098 blue:0.9373 alpha:1];
    switch (indexPath.row) {
        case 0:
        {
            cell.textLabel.font = [UIFont boldSystemFontOfSize:17];
            
            cell.textLabel.text=@"旧密码：";
            cell.selectionStyle = UITableViewCellSelectionStyleNone;

            self.textFOldPwd=[[UITextField alloc] initWithFrame:CGRectMake(110, 0, 200, 44)];
            
            self.textFOldPwd.backgroundColor=[UIColor clearColor];
            self.textFOldPwd.returnKeyType=UIReturnKeyNext;
            self.textFOldPwd.textColor=[UIColor blackColor];
            self.textFOldPwd.secureTextEntry=YES;
            self.textFOldPwd.contentHorizontalAlignment=UIControlContentVerticalAlignmentCenter;
            self.textFOldPwd.delegate=self;
            
            [cell.contentView addSubview:self.textFOldPwd];
            
            
        }
            break;
        case 1:
        {
            cell.textLabel.font = [UIFont boldSystemFontOfSize:17];
            
            cell.textLabel.text=@"新密码：";
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            self.textFNewPwd=[[UITextField alloc] initWithFrame:CGRectMake(110, 0, 200, 44)];
            
            self.textFNewPwd.backgroundColor=[UIColor clearColor];
            self.textFNewPwd.returnKeyType=UIReturnKeyNext;
            self.textFNewPwd.textColor=[UIColor blackColor];
            self.textFNewPwd.secureTextEntry=YES;
            self.textFNewPwd.delegate=self;
            self.textFNewPwd.contentHorizontalAlignment=UIControlContentVerticalAlignmentCenter;
            [cell.contentView addSubview:self.textFNewPwd];

        }
            break;
        case 2:
        {
            cell.textLabel.font = [UIFont boldSystemFontOfSize:17];
            
            cell.textLabel.text=@"确认新密码：";
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            self.textFConfirmNewPwd=[[UITextField alloc] initWithFrame:CGRectMake(110, 0, 200, 44)];
            
            self.textFConfirmNewPwd.backgroundColor=[UIColor clearColor];
            
            self.textFConfirmNewPwd.returnKeyType = UIReturnKeyDone;
      
            self.textFConfirmNewPwd.secureTextEntry=YES;
            self.textFConfirmNewPwd.textColor=[UIColor blackColor];
            self.textFConfirmNewPwd.delegate=self;
            self.textFConfirmNewPwd.contentHorizontalAlignment=UIControlContentVerticalAlignmentCenter;
            [cell.contentView addSubview:self.textFConfirmNewPwd];

        }
        case 3:
        {
            [cell.contentView addSubview:self.btnModifyPwd];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;

            [self.btnModifyPwd autoPinEdge:ALEdgeBottom toEdge:ALEdgeBottom ofView:cell.contentView withOffset:5];
            
            [self.btnModifyPwd autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:cell.contentView     withOffset:10];
            [self.btnModifyPwd autoPinEdge:ALEdgeRight toEdge:ALEdgeRight ofView:cell.contentView     withOffset:-10];
            
            [self.btnModifyPwd autoSetDimension:ALDimensionHeight toSize:40];
            
            
            
            
        }
            break;
            
        default:
            break;
    }
    
    if(indexPath.row==0 || indexPath.row==1 || indexPath.row==2)
    {
    UIView *viewLine = [[UIView alloc] initWithFrame:CGRectMake(10, 43, 300, 1.1)];
    viewLine.backgroundColor=RGBColor(153, 153, 153,0.5 );
    [cell.contentView addSubview:viewLine];
    }
    
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    
    [self configureCell:cell forIndexPath:indexPath];
    
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return 4;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row==3 )
        
        return 88;
    else
        
        return 44;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
    
}

#pragma mark =============  UITableView Delegate  =============
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    DLog(@"You Click At Section: %d Row: %d", (int)indexPath.section, (int)indexPath.row);
   
    
}





@end
