//
//  GTOSignViewController.m
//  total
//  签到
//  Created by freecui on 15/10/14.
//  Copyright (c) 2015年 free. All rights reserved.
//

#import "GTOBusinessSignInViewController.h"
#import "GXFBottomView.h"
#import "GTOBusinessSignInfo.h"
@interface GTOBusinessSignInViewController ()<GXFBottomViewDelegate,BMKMapViewDelegate,BMKLocationServiceDelegate>
@property (strong, nonatomic) BMKLocationService *locService;
@property (strong, nonatomic) BMKMapView* mapView;

@property (strong, nonatomic) IBTUILabel *coordinateLbl;
@property (strong, nonatomic)  IBTUILabel *timeLbl;
@property (strong, nonatomic)  IBTUILabel *storeLbl;
@property (strong, nonatomic) GTOBusinessSignInfo *sigInfo;
@property (assign, nonatomic) BOOL is_relocated;
//@property (strong, nonatomic) NSString *locationX;
//@property (strong, nonatomic) NSString *locationY;
#define LOCATED_TIME @"locatedTime"
typedef NS_ENUM(NSUInteger,kBottomTag) {
    kBottomBackTag = 0,
    kBottomLocatedTag
};
@end

@implementation GTOBusinessSignInViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"签 到";
    self.is_relocated = NO;
    // [self p_initData];
    [self p_initWithSubViews];
}

-(void)viewWillAppear:(BOOL)animated {
    [_mapView viewWillAppear];
    //    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    //    _locService.delegate = self;
}

-(void)viewWillDisappear:(BOOL)animated {
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
    _locService.delegate = nil;
}
- (void)p_initWithSubViews {
    
    CGFloat totalH = self.view.height - 64;
    self.mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0,self.view.width , totalH * 0.6)];
    [self.view addSubview:_mapView];
    self.locService = [[BMKLocationService alloc]init];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    _locService.delegate = self;
    [_locService startUserLocationService];
    
    
    //        [self displayAnnotationWithLatitude:locationX andLongitude:locationY];
    //            _mapView.centerCoordinate = CLLocationCoordinate2DMake(31.2357360000,121.5292150000);
    //            //增加大头针
    //            BMKPointAnnotation *pointAnnotation = [[BMKPointAnnotation alloc]init];
    //            CLLocationCoordinate2D coor;
    //            coor.latitude = 31.2357360000;
    //            coor.longitude = 121.5292150000;
    //            pointAnnotation.coordinate = coor;
    //            [_mapView addAnnotation:pointAnnotation];
    //            _mapView.zoomLevel = 19;
    
    
    
    
    
    UIView *currentV = [[UIView alloc]initWithFrame:CGRectMake(0, _mapView.bottom, self.view.width, 44)];
    currentV.backgroundColor = XXFBgColor;
    IBTUILabel *addressLbl = [[IBTUILabel alloc]initWithFrame:CGRectMake(10, 0, currentV.width * 0.5 - 10, currentV.height) text:@"定位位置" font:[UIFont systemFontOfSize:19] tintColor:[UIColor blackColor] backgroundColor:XXFBgColor textAlignment:NSTextAlignmentLeft];
    CGFloat btnW = 44;
    IBTUILabel *locationLbl = [[IBTUILabel alloc]initWithFrame:CGRectMake(addressLbl.right, 0, currentV.width * 0.5 - 10 - btnW, currentV.height) text:@"重新定位" font:[UIFont systemFontOfSize:16] tintColor:GTO_BLUE_DEEP_COLOR backgroundColor:XXFBgColor textAlignment:NSTextAlignmentRight];
    UIButton *locationBtn = [[UIButton alloc]initWithFrame:CGRectMake(locationLbl.right, locationLbl.y, btnW, locationLbl.height)];
    [locationBtn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];//icon_nav_start
    [locationBtn addTarget:self action:@selector(relocationClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:currentV];
    [currentV addSubview:addressLbl];
    [currentV addSubview:locationLbl];
    [currentV addSubview:locationBtn];
    
    
    CGFloat addressValueVH = totalH - currentV.bottom - BottomViewHeight - 20;
    UIView *addressValueV = [[UIView alloc]initWithFrame:CGRectMake(10, currentV.bottom, self.view.width - 20,addressValueVH)];
    addressValueV.backgroundColor = [UIColor whiteColor];
    CGFloat lblH = (addressValueVH - 12.0 ) / 3.0;
    IBTUILabel *coordinateLbl = [[IBTUILabel alloc]initWithFrame:CGRectMake(0, 6,addressValueV.width, lblH) text:[NSString stringWithFormat:@"定位坐标： %@",@"31.235000,121.529000"] font:[UIFont systemFontOfSize:17] tintColor:GTO_GRAY_TINT_COLOR backgroundColor:nil textAlignment:NSTextAlignmentLeft];
    IBTUILabel *timeLbl = [[IBTUILabel alloc]initWithFrame:CGRectMake(0, coordinateLbl.bottom,addressValueV.width, lblH) text:[NSString stringWithFormat:@"定位时间： %@",[[NSDate date] httpParameterString]] font:[UIFont systemFontOfSize:17] tintColor:GTO_GRAY_TINT_COLOR backgroundColor:nil textAlignment:NSTextAlignmentLeft];
    //    IBTUILabel *storeLbl = [[IBTUILabel alloc]initWithFrame:CGRectMake(0, timeLbl.bottom,addressValueV.width, lblH) text:[NSString stringWithFormat:@"附近油站： %@",@""] font:[UIFont systemFontOfSize:17] tintColor:GTO_GRAY_TINT_COLOR backgroundColor:nil textAlignment:NSTextAlignmentLeft];
    
    self.coordinateLbl = coordinateLbl;
    self.timeLbl = timeLbl;
    //self.storeLbl = storeLbl;
    [addressValueV addSubview:_coordinateLbl];
    [addressValueV addSubview:_timeLbl];
    [addressValueV addSubview:_storeLbl];
    [self.view addSubview:addressValueV];
    
    GXFBottomView *bottomV;
    //
    if (self.latitudeX && self.longitudeY) {
        CGFloat locationX = [self.latitudeX floatValue];
        CGFloat locationY = [self.longitudeY floatValue];
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        NSString *time = [userDefault objectForKey:LOCATED_TIME];
        [self displayAnnotationWithLatitude:locationX andLongitude:locationY];
        self.coordinateLbl.text = [NSString stringWithFormat:@"定位坐标： %.6lf,%.6lf",locationX,locationY];
        self.timeLbl.text = [NSString stringWithFormat:@"定位时间： %@",time];
        
        bottomV = [[GXFBottomView alloc]initOneButtonWithFrame:CGRectMake(0, addressValueV.bottom  +20, self.view.width, BottomViewHeight) buttonColor:GTO_RED_COLOR buttonTitle:@"返回"];
        bottomV.tag = kBottomBackTag;
    } else {
        bottomV = [[GXFBottomView alloc]initOneButtonWithFrame:CGRectMake(0, addressValueV.bottom  +20, self.view.width, BottomViewHeight) buttonColor:GTO_RED_COLOR buttonTitle:@"签 到"];
        bottomV.tag = kBottomLocatedTag;
    }
    bottomV.backgroundColor = XXFBgColor;
    bottomV.delegate = self;
    [self.view addSubview:bottomV];
    
}

#pragma button cllicked
- (void)relocationClicked {
    self.is_relocated = YES;
    [_locService startUserLocationService];
    
    //  [self PopViewControllerAnimated:NO];
}
#pragma  GXFBottomViewDelegate
- (void)bottomView:(GXFBottomView *)bottomView oneButtonClicked:(UIButton *)oneBtn {
    switch (bottomView.tag) {
        case kBottomBackTag:
        {
            [self PopViewControllerAnimated:YES];
        }
            break;
        case kBottomLocatedTag:
        {
            if (!self.latitudeX || !self.longitudeY) {
                [IBTLoadingView showTextOnly:@"定位失败" inView:self.view];
                return;
            } else {
                
                [self httpSignIn];
                
//                [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(viewPop) userInfo:nil repeats:NO];
                
            }
            
        }
            break;
        default:
            break;
    }
}
- (void) httpSignIn {
    void (^success)(id) = ^(id data) {
        if ([data[@"success"] integerValue] == 1) {
            [IBTLoadingView showTextOnly:@"签到成功"];
            [self PopViewControllerAnimated:YES];
        } else {
            [IBTLoadingView showTextOnly:data[@"message"]];
        }
    };
    void (^failure)(id) = ^(id data) {
        
        [IBTLoadingView showTextOnly:@"签到失败"];
    };
    self.sigInfo = [GTOBusinessSignInfo DBObject];
    _sigInfo.signerUuid = [[ICRUserUtil sharedInstance] f_user_uuid];
    _sigInfo.signInTime = [[NSDate date] httpParameterString];
    _sigInfo.type = @"in";
    _sigInfo.longitude = _longitudeY;
    _sigInfo.latitude =_latitudeX;
    //_sigInfo.storeUuid = @"";
    NSDictionary *dict = [_sigInfo dictForCommit];
    ICRHTTPController *httpC = [ICRHTTPController sharedController];
    [httpC getSignInIdWithDictionary:dict success:success failure:failure];
    
}
/**
 *在地图View将要启动定位时，会调用此函数
 *@param mapView 地图View
 */
- (void)willStartLocatingUser
{
    
    NSLog(@"start locate");
    
}
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    
    if (_is_relocated) {
        [IBTLoadingView showTextOnly:@"重新定位成功"];
    }
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setObject:[[NSDate date] httpParameterString] forKey:LOCATED_TIME];
    
    self.latitudeX = [NSString stringWithFormat:@"%.6f",userLocation.location.coordinate.latitude];
    self.longitudeY = [NSString stringWithFormat:@"%.6f",userLocation.location.coordinate.longitude];
    self.coordinateLbl.text = [NSString stringWithFormat:@"定位坐标: %@ ,%@",self.latitudeX,self.longitudeY];
    self.timeLbl.text = [NSString stringWithFormat:@"定位时间：%@",[[NSDate date] httpParameterString]];
    
    
    [self displayAnnotationWithLatitude:userLocation.location.coordinate.latitude andLongitude:userLocation.location.coordinate.longitude];
    
    [_mapView updateLocationData:userLocation];
    
    [_locService stopUserLocationService];
    self.is_relocated = NO;
    
}
- (void)displayAnnotationWithLatitude: (CGFloat)latitude
                         andLongitude: (CGFloat)longitude {
    _mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
    _mapView.showsUserLocation = YES;//显示定位图层
    _mapView.centerCoordinate = CLLocationCoordinate2DMake(latitude,longitude);
    //增加大头针
    BMKPointAnnotation *pointAnnotation = [[BMKPointAnnotation alloc]init];
    CLLocationCoordinate2D coor;
    coor.latitude = latitude;
    coor.longitude = longitude;
    pointAnnotation.coordinate = coor;
    [_mapView addAnnotation:pointAnnotation];
    _mapView.zoomLevel = 17;
    
}
/**
 *在地图View停止定位后，会调用此函数
 *@param mapView 地图View
 */
- (void)didStopLocatingUser
{
    NSLog(@"stop locate");
}

/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"location error");
}

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



@end
