//
//  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"
#import <BaiduMapAPI/BMapKit.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) {

        [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) = ^(id data) {
        [IBTLoadingView hideHUDWithText:@"登录失败"];
        //[IBTLoadingView showTextOnly: data inView:self.view];
    };

    [IBTLoadingView showProgressLabel:@"正在登录"];
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    [httpCtrl doLoginWithUserName:nsUserName password:nsPassword registerCode:nsRegisterCode success:succ failure:fail];
}

///**
// *在地图View将要启动定位时，会调用此函数
// *@param mapView 地图View
// */
//- (void)willStartLocatingUser
//{
//    NSLog(@"start locate");
//
//}
//- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
//{
//    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
//    self.coordinateX = userLocation.location.coordinate.latitude;
//    self.coordinateY = userLocation.location.coordinate.longitude;
//    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
//    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){_coordinateX, _coordinateY};
//    reverseGeocodeSearchOption.reverseGeoPoint = pt;
//    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
//    if(flag)
//    {
//
//        NSLog(@"反geo检索发送成功");
//    }
//    else
//    {
//        NSLog(@"反geo检索发送失败");
//    }
//
//    [self.locService stopUserLocationService];
//}
//-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
//{
//    if (error == 0) {
//        //CLog(@"%@%@",result.location,result.address);
//    }
//}
#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
