//
//  ICRLoginViewController.m
//  Cruiser
//
//  Created by Xummer on 3/22/15.
//  Copyright (c) 2015 Xummer. All rights reserved.
//

#import "APService.h"
#import "ICRLoginContentView.h"
#import "ICRLoginViewController.h"

#define LOGIN_CONTAINER_LEFT_MARGIN (20)
#define LOGIN_CONTAINER_HEIGHT (450)

@interface ICRLoginViewController () <BMKMapViewDelegate, BMKLocationServiceDelegate, BMKGeoCodeSearchDelegate> {
    CGFloat m_fDefaultContainerY;
}
@property (strong, nonatomic) ICRLoginContentView *m_containerView;
@property (strong, nonatomic) BMKLocationService *locService;
@property (strong, nonatomic) BMKMapView *mapView;
@property (strong, nonatomic) BMKGeoCodeSearch *geocodesearch;
@property (assign, nonatomic) CGFloat coordinateX;
@property (assign, nonatomic) CGFloat coordinateY;
@property (copy, nonatomic) NSString *city;

@end

@implementation ICRLoginViewController

#pragma mark - Life Cycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupSubviews];
}

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

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];

    if (m_fDefaultContainerY == 0) {
        m_fDefaultContainerY = _m_containerView.y;
    }
}

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

    NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
    [notiCenter addObserver:self selector:@selector(inputTextEditChanged:) name:UITextFieldTextDidChangeNotification object:nil];
}

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

    NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
    [notiCenter removeObserver:self];
}

#pragma mark - Private Method
- (void)setupSubviews
{
    //    self.mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0,self.view.width , 50)];
    //
    //    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    //    self.geocodesearch = [[BMKGeoCodeSearch alloc]init];
    //    self.geocodesearch.delegate = self;
    //
    //    self.locService = [[BMKLocationService alloc]init];
    //    [_locService startUserLocationService];
    //    _locService.delegate = self;
    //
    UIImageView *bg = [[UIImageView alloc] initWithFrame:self.view.bounds];
    bg.image = [UIImage imageNamed:@"login_bg"];
    [bg autoresizingWithStrechFullSize];

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onBGTapped:)];
    bg.userInteractionEnabled = YES;
    [bg addGestureRecognizer:tapGesture];

    [self.view addSubview:bg];

    self.m_containerView = [[ICRLoginContentView alloc] initWithFrame:(CGRect) {
        .origin.x = LOGIN_CONTAINER_LEFT_MARGIN, .origin.y = (self.view.height - LOGIN_CONTAINER_HEIGHT) * .5f, .size.width = self.view.width - 2 * LOGIN_CONTAINER_LEFT_MARGIN, .size.height = LOGIN_CONTAINER_HEIGHT
    }
                                                            showCCode:YES];
    [_m_containerView autoresizingWithVerticalCenter];

    [_m_containerView.m_loginBtn addTarget:self action:@selector(onLoginTapped:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:_m_containerView];
    // ICRDataBaseController *dataBC = [ICRDataBaseController sharedController];
    NSString *dbPath = [ICRDataBaseController GetDataBasePath];
    CLog(@"dbpath = %@", dbPath);
    _m_containerView.m_cCodeTextF.placeholder = @"请输入企业验证码";
    _m_containerView.m_userNameTextF.placeholder = @"请输入用户名";
    _m_containerView.m_passwordTextF.placeholder = @"请输入密码";
    _m_containerView.m_cCodeTextF.text = @"211534962";

    //
    //#if DEBUG
    //    self.m_containerView.m_cCodeTextF.text = @"923";//
    //    self.m_containerView.m_userNameTextF.text = @"admin";//@"admin2";//
    //    self.m_containerView.m_passwordTextF.text = @"thoradmin";//@"admin2";//
    //    [self.m_containerView checkLoginEnable];
    //#else
    //
    //#endif

    ICRUserUtil *userU = [ICRUserUtil sharedInstance];
    if (userU.f_isLogout) {
        self.m_containerView.m_cCodeTextF.text = userU.f_authenticode;
        self.m_containerView.m_userNameTextF.text = userU.f_user_loginName;
        self.m_containerView.m_passwordTextF.text = userU.f_user_password;
    }

    [self.m_containerView checkLoginEnable];
}

#pragma mark - Logic

#pragma mark - Actions
- (void)onBGTapped:(__unused id)sender
{
    [self.view endEditing:YES];
}

- (void)onLoginTapped:(__unused id)sender
{

    NSString *nsRegisterCode = self.m_containerView.m_cCodeTextF.text;
    NSString *nsUserName = self.m_containerView.m_userNameTextF.text;
    NSString *nsPassword = self.m_containerView.m_passwordTextF.text;
    void (^succ)(id) = ^(id data) {
        NSLog(@"%@",data);
        [IBTLoadingView hideHUDWithText:nil];
        ICRUserUtil *userUtil = [ICRUserUtil sharedInstance];
        userUtil.bAutoLogin = @([_m_containerView isAutoLogin]);
        [userUtil saveArchive];
        ICRAppViewControllerManager *mgr = [ICRAppViewControllerManager getAppViewControllerManager];
        [mgr openMainFrame];
        //极光别名
        NSSet *setTags = [NSSet setWithArray:@[ @"" ]];
        [APService setTags:setTags alias:userUtil.f_user_uuid callbackSelector:nil object:nil];
    };

    void (^fail)(id) = ^(NSError *data) {
        [IBTLoadingView hideHUDWithText:data.localizedDescription];
    };
    [IBTLoadingView showProgressLabel:@"正在登录"];
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    [httpCtrl doLoginWithUserName:nsUserName password:nsPassword registerCode:nsRegisterCode success:succ failure:fail];
}

#pragma mark - TextObserver
- (void)inputTextEditChanged:(NSNotification *)obj
{
    [self.m_containerView checkLoginEnable];
}

#pragma mark - Keyboard
- (void)keyboardWillShow:(NSNotification *)note
{
    // get keyboard size and loctaion
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardBounds];
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];

    // Need to translate the bounds to account for rotation.
    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];

    // animations settings
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];

    // set views with new info
    self.m_containerView.y = -50.0f;

    // commit animations
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)note
{
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];

    // animations settings
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];

    // set views with new info
    self.m_containerView.y = m_fDefaultContainerY;

    // commit animations
    [UIView commitAnimations];
}

@end
