//
//  CoordinateAcquisitionViewController.m
//  Palmwms
//
//  Created by 曹云霄 on 16/8/25.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "CoordinateAcquisitionViewController.h"
#import "SearchViewController.h"
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import "CustomBMKAnnotationView.h"
#import "UserPaopaoView.h"


#define USERLOCATIONID @"userlocation"

@interface CoordinateAcquisitionViewController ()<UITextFieldDelegate,BMKMapViewDelegate,BMKLocationServiceDelegate>


@property (strong, nonatomic) BMKLocationService *locService;
@property (strong, nonatomic) BMKMapView* mapView;
@property (nonatomic,strong) BMKLocationViewDisplayParam *displayLocation;


/**
 *  选择客户
 */
@property (weak, nonatomic) IBOutlet UITextField *inputUserInformationField;

/**
 *  采集
 */
@property (weak, nonatomic) IBOutlet UIButton *collectCoordinateButton;

/**
 *  保存用户大头针对象
 */
@property (nonatomic,strong) BMKPointAnnotation *userPointAnnotation;

/**
 *  当前选中的客户
 */
@property (nonatomic,strong) Customer *currentUser;

@end

@implementation CoordinateAcquisitionViewController


#pragma mark - lazy
- (BMKLocationViewDisplayParam *)displayLocation
{
    if (!_displayLocation) {
        _displayLocation = [[BMKLocationViewDisplayParam alloc]init];
        _displayLocation.locationViewImgName = @"location";
        _displayLocation.locationViewOffsetX = 0;
        _displayLocation.locationViewOffsetY = 0;
        _displayLocation.isAccuracyCircleShow = false;
        _displayLocation.isRotateAngleValid = false;
    }
    return _displayLocation;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self uiConfigAction];
    [self startpositionAction];
}

-(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;
}

#pragma mark -UI
- (void)startpositionAction
{
    self.locService = [[BMKLocationService alloc]init];
    [self.locService startUserLocationService];
    self.mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, self.view.mj_w, self.view.mj_h-44-64)];
    [self.view insertSubview:_mapView atIndex:0];
    self.mapView.zoomLevel = 16;
    self.locService.pausesLocationUpdatesAutomatically = NO;
    self.mapView.userTrackingMode = BMKUserTrackingModeFollow;
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    [_mapView updateLocationData:userLocation];
    double latitude = userLocation.location.coordinate.latitude;
    double longitude = userLocation.location.coordinate.longitude;
    [UserInforMation manager].latitude = latitude;
    [UserInforMation manager].longitude = longitude;//记录用户经纬度
    [self displayAnnotationWithLatitude:latitude andLongitude:longitude title:USERLOCATIONID];
}

/**
 *在地图View停止定位后，会调用此函数
 *@param mapView 地图View
 */
- (void)didStopLocatingUser
{
    NSLog(@"定位停止");
}

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


#pragma mark -自定义用户大头针
- (void)displayAnnotationWithLatitude: (CGFloat)latitude andLongitude: (CGFloat)longitude title:(NSString *)title
{
    [self.mapView removeAnnotation:self.userPointAnnotation];
    [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(latitude,longitude) animated:YES];
    BMKPointAnnotation  *pointAnnotation = [[BMKPointAnnotation alloc]init];
    self.userPointAnnotation = pointAnnotation;
    pointAnnotation.coordinate = CLLocationCoordinate2DMake(latitude, longitude);
    pointAnnotation.title = title;
    [self.mapView addAnnotation:pointAnnotation];
}

/**
 *根据anntation生成对应的View
 *@param mapView 地图View
 *@param annotation 指定的标注
 *@return 生成的标注View
 */
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    CustomBMKAnnotationView *annottionView = (CustomBMKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:USERLOCATIONID];
    if (!annottionView) {
        annottionView = [[CustomBMKAnnotationView alloc]userSignInitialize:annotation reuseIdentifier:USERLOCATIONID];
    }
    [annottionView setSelected:YES animated:YES];
    UserPaopaoView *paopaoView = [[UserPaopaoView alloc] signUserInitialize:[UIView new] withCoord:annotation.coordinate];
    paopaoView.frame = CGRectMake(0, 0, 200, 70);
    annottionView.paopaoView = paopaoView;
    return annottionView;
}

#pragma mark - UI
- (void)uiConfigAction
{
    [self.collectCoordinateButton addCorners];
    [self.inputUserInformationField addCorners];
    [self.inputUserInformationField addLines];
    
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 60, 40)];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 10, 20, 20)];
    imageView.image = LOADIMAGENAME(@"search");
    [leftView addSubview:imageView];
    self.inputUserInformationField.leftViewMode = UITextFieldViewModeAlways;
    self.inputUserInformationField.leftView = leftView;
    self.collectCoordinateButton.backgroundColor = [self.inputUserInformationField.text length]?RGBA(250, 71, 76, 1):[UIColor lightGrayColor];
    self.collectCoordinateButton.enabled = [self.inputUserInformationField.text length]?YES:NO;
}

#pragma mark - <UITextFieldDelegate>
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    WS(weakSelf);
    SearchViewController *searchVC = [self.getStoryboardWithName instantiateViewControllerWithIdentifier:@"SearchViewController"];
    [searchVC setSelectCustomer:^(Customer *model) {
        weakSelf.currentUser = model;
        textField.text = [NSString stringWithFormat:@"【%@】%@",model.code,model.name];
        weakSelf.collectCoordinateButton.backgroundColor = [weakSelf.inputUserInformationField.text length]?RGBA(250, 71, 76, 1):[UIColor lightGrayColor];
        weakSelf.collectCoordinateButton.enabled = [weakSelf.inputUserInformationField.text length]?YES:NO;
    }];
    [self.navigationController pushViewController:searchVC animated:YES];
    return NO;
}

#pragma mark - 采集数据
- (IBAction)CoordinateAcquisitionButtonClick:(UIButton *)sender {
    
    WS(weakSelf);
    [self showSheetViewWithMessage:@"请确认是否上传该采集点数据？" complete:^{
        [weakSelf CreateMBProgressHUDLoding:@"上传采集点数据中"];
        
        Customer *uploadLocation = [[Customer alloc]init];
        uploadLocation.fid = self.currentUser.fid;
        uploadLocation.code = self.currentUser.code;
        uploadLocation.lat = [NSString stringWithFormat:@"%lf",[UserInforMation manager].latitude];
        uploadLocation.lng = [NSString stringWithFormat:@"%lf",[UserInforMation manager].longitude];
        uploadLocation.address = self.currentUser.address;
        [[NetworkRequestClassManager Manager] NetworkRequestWithURL:SERVERREQUESTURL(UPLOADLOCATION) WithRequestType:NetworkRequestWithPOST WithParameter:uploadLocation WithReturnValueBlock:^(id returnValue) {
            [weakSelf RemoveMBProgressHUDLoding];
            if ([returnValue[@"code"] isEqualToNumber:@0]) {
                [weakSelf SuccessMBProgressView:@"上传成功" timeDelay:1.0f finish:nil];
            }else
            {
                [weakSelf SHOWPrompttext:returnValue[@"message"]];
            }
        } WithErrorCodeBlock:^(id errorCodeValue) {
            [weakSelf RemoveMBProgressHUDLoding];
            [weakSelf SHOWPrompttext:NETWORK];
        } WithFailureBlock:^(NSError *error) {
            [weakSelf RemoveMBProgressHUDLoding];
            [weakSelf SHOWPrompttext:error.localizedDescription];
        }];
        
    }];
}

#pragma mark - 刷新按钮
- (IBAction)refreshLocationButton:(UIButton *)sender {
    
    [self.mapView setCenterCoordinate:self.userPointAnnotation.coordinate animated:YES];
    [_locService startUserLocationService];
}




#pragma mark - 释放
- (void)dealloc {
    if (_mapView) {
        _mapView = nil;
    }
}

@end
