//
//  LoginViewController.m
//  RealEstateManagement
//
//  Created by Z on 16/6/24.
//  Copyright © 2016年 上海勾芒信息科技. All rights reserved.
//

#import "LoginViewController.h"
#import "IQUITextFieldView+Additions.h"
#import "LoginViewModel.h"
#import "RootNavigationController.h"
#import "UpdateAlertView.h"
@interface LoginViewController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *textFieldName;
@property (weak, nonatomic) IBOutlet UITextField *textFieldPWD;
@property (weak, nonatomic) IBOutlet UIButton *btnLogin;
@property (weak, nonatomic) IBOutlet UIButton *btnShop;
@property (weak, nonatomic) IBOutlet UIButton *btnMall;
@property (weak, nonatomic) IBOutlet UIImageView *imgBg;
@property (weak, nonatomic) IBOutlet UILabel *bottomInfo;
@property (strong, nonatomic) LoginViewModel *viewModel;
@property (strong, nonatomic) ZJUpdateManager *update;
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self checkUpdate];
    if (AppGlobal.isMall) {
        self.btnMall.selected = YES;
    } else {
        self.btnShop.selected = YES;
    }
    self.textFieldName.keyboardDistanceFromTextField = 60;
    self.textFieldPWD.keyboardDistanceFromTextField = 60;
    self.bottomInfo.text = [NSString stringWithFormat:@"上海海鼎信息工程股份有限公司  V%@", APP_VERSION];
    self.textFieldName.text = AppGlobal.savedName;
    self.textFieldPWD.text = AppGlobal.savedPWD;
    [self configUIWithTargetType];
}

/**
 根据target的类型配置不同的界面样式
 */
- (void)configUIWithTargetType {
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)checkUpdate {
    [self.update checkOnVC:self complete:^(BOOL isLatest) {
        if (self.textFieldName.text.length > 0 && self.textFieldPWD.text.length >0) {
            [self ActionLogin:nil];
        }
    }];
}

//登录
- (IBAction)ActionLogin:(UIButton *)sender {
    kCanNotBeNil(self.textFieldName.text, @"请输入用户名！");
    kCanNotBeNil(self.textFieldPWD.text, @"请输入密码！");
    
    [MBProgressHUD j_loading:@"登陆中…"];
    self.viewModel.loginRequest.principal = self.textFieldName.text;
    self.viewModel.loginRequest.password = self.textFieldPWD.text;
    self.viewModel.loginRequest.type = AppGlobal.isMall ? LoginTypeMall : LoginTypeTenant;
    WS(weakSelf);
    [self.viewModel login:^(id responseObject, NSError *error) {
//        [MBProgressHUD j_hideLoadingView];
        [MBProgressHUD j_success:@"登录成功！" complete:^{
            [weakSelf.viewModel openMain];
        }];
        AppGlobal.savedPWD = weakSelf.textFieldPWD.text;
        AppGlobal.savedName = weakSelf.textFieldName.text;
        [AppGlobal saveBaseInfo];
    }];
}

//tag 0 商户／ 1 内部
- (IBAction)actionSwitch:(UIButton *)sender {
    AppGlobal.isMall = sender.tag == 1 ? YES : NO;
}

- (void)loginSuccessAction {
   
}

ZJLazy(LoginViewModel, viewModel);
ZJLazy(ZJUpdateManager, update);

@end
