//
//  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
{
    _locService = [[BMKLocationService alloc]init];
    [_locService startUserLocationService];
    _mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, self.view.mj_w, self.view.mj_h-44-64)];
    [self.view insertSubview:_mapView atIndex:0];
    _mapView.zoomLevel = 16;
    _locService.distanceFilter = 50.0;
    _mapView.userTrackingMode = BMKUserTrackingModeFollow;
//    _mapView.showsUserLocation = YES;//显示定位图层
//    [_mapView updateLocationViewWithParam:self.displayLocation];
}

/**
 *用户位置更新后，会调用此函数
 *@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 setCenterCoordinate:CLLocationCoordinate2DMake(latitude,longitude) animated:YES];
    //判断用户的大头针存在否
    BMKPointAnnotation *pointAnnotation;
    if (self.userPointAnnotation) {
        pointAnnotation = self.userPointAnnotation;
        
    } else {
        pointAnnotation = [[BMKPointAnnotation alloc]init];
        self.userPointAnnotation = pointAnnotation;
    }
    CLLocationCoordinate2D coor;
    coor.latitude = latitude;
    coor.longitude = longitude;
    pointAnnotation.coordinate = coor;
    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];
    }
    UserPaopaoView *paopaoView = [[UserPaopaoView alloc] signUserInitialize:[UIView new] withCoord:annotation.coordinate];
    paopaoView.frame = CGRectMake(0, 0, ScreenSize.width-150, 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:@"上传采集点数据中"];
        NSString *string = [NSString stringWithFormat:@"customer/saveCoordinate/%@?lat=%lf&lng=%lf",self.currentUser.fid,[UserInforMation manager].latitude,[UserInforMation manager].longitude];
        [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:SERVERREQUESTURL(string) WithRequestType:1 WithParameter:nil 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 - 释放
- (void)dealloc {
    if (_mapView) {
        _mapView = nil;
    }
}

@end
