//
//  YYAreaSearchViewController.m
//  YYObjCDemo
//
//  Created by zhaoxiangru on 2020/12/25.
//  Copyright © 2020 百度鹰眼. All rights reserved.
//

#import "YYAreaSearchViewController.h"
#import <BaiduMapAPI_Search/BMKSearchComponent.h>

#define kHeight_SegMentBackgroud  60

@interface YYAreaSearchViewController ()<BMKMapViewDelegate, BTKEntityDelegate, BMKDistrictSearchDelegate>
@property (nonatomic, strong) BMKMapView *mapView; //当前界面的mapView
@property (nonatomic, strong) UISegmentedControl *mapSegmentControl;

@end

@implementation YYAreaSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"空间搜索";
    [self configUI];
    [self createMapView];
    [self aroundSearch];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:NO];
    //当mapView即将被显示的时候调用，恢复之前存储的mapView状态
    [_mapView viewWillAppear];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:NO];
    //当mapView即将被隐藏的时候调用，存储当前mapView的状态
    [_mapView viewWillDisappear];
}

#pragma mark - Config UI
- (void)configUI {
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.mapSegmentControl];
}

- (void)createMapView {
    //将mapView添加到当前视图中
    [self.view addSubview:self.mapView];
    //设置mapView的代理
    _mapView.delegate = self;
}

#pragma mark - Responding events
- (void)segmentControlDidChangeValue:(id)sender {
    NSUInteger selectedIndex = [_mapSegmentControl selectedSegmentIndex];
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView removeOverlays:self.mapView.overlays];
    switch (selectedIndex) {
        case 0:
            //周边搜索
            [self aroundSearch];
            break;
        case 1:
            //矩形搜索
            [self boundsSearch];
            break;
        case 2:
            //行政区域搜索
            [self districtSearch];
            break;
        default:
            //周边搜索
            [self aroundSearch];
            break;
    }
}

- (void)aroundSearch {
    // 设置检索的过滤条件
   BTKQueryEntityFilterOption *filterOption = [[BTKQueryEntityFilterOption alloc] init];
//   filterOption.entityNames = @[@"Test"];
   filterOption.activeTime = [[NSDate date] timeIntervalSince1970] - 49 * 24 * 3600;
   // 设置检索结果的排序方式
   BTKSearchEntitySortByOption *sortbyOption = [[BTKSearchEntitySortByOption alloc] init];
   sortbyOption.fieldName = @"loc_time";
   sortbyOption.sortType = BTK_ENTITY_SORT_TYPE_DESC;
   // 构造检索请求对象
   BTKAroundSearchEntityRequest *request = [[BTKAroundSearchEntityRequest alloc] initWithCenter:CLLocationCoordinate2DMake(40.054354, 116.300586) inputCoordType:BTK_COORDTYPE_BD09LL radius:1000 filter:filterOption sortby:sortbyOption outputCoordType:BTK_COORDTYPE_BD09LL pageIndex:1 pageSize:10 ServiceID:serviceID tag:0];
   // 发起检索请求
   [[BTKEntityAction sharedInstance] aroundSearchEntityWith:request delegate:self];
}

- (void)boundsSearch {
    // 设置矩形的区域
    NSMutableArray *bounds = [NSMutableArray arrayWithCapacity:2];
    // 矩形左下角的顶点坐标116.287507,40.044302
    CLLocationCoordinate2D point1 = CLLocationCoordinate2DMake(40.044302, 116.287507);
    [bounds addObject:[NSValue valueWithBytes:&point1 objCType:@encode(CLLocationCoordinate2D)]];
    // 矩形右上角的顶点坐标116.311079,40.070258
    CLLocationCoordinate2D point2 = CLLocationCoordinate2DMake(40.070258, 116.311079);
    [bounds addObject:[NSValue valueWithBytes:&point2 objCType:@encode(CLLocationCoordinate2D)]];
    // 设置检索的过滤选项
    BTKQueryEntityFilterOption *filterOption = [[BTKQueryEntityFilterOption alloc] init];
//    filterOption.entityNames = @[@"entityA", @"entityB", @"entityC"];
    filterOption.activeTime = [[NSDate date] timeIntervalSince1970] - 49 * 24 * 3600;
    // 设置检索结果的排序选项
    BTKSearchEntitySortByOption *sortbyOption = [[BTKSearchEntitySortByOption alloc] init];
    sortbyOption.fieldName = @"loc_time";
    sortbyOption.sortType = BTK_ENTITY_SORT_TYPE_DESC;
    // 构造检索请求
    BTKBoundSearchEntityRequest *request = [[BTKBoundSearchEntityRequest alloc] initWithBounds:bounds inputCoordType:BTK_COORDTYPE_BD09LL filter:filterOption sortby:sortbyOption outputCoordType:BTK_COORDTYPE_BD09LL pageIndex:1 pageSize:10 ServiceID:serviceID tag:1];
    // 发起检索请求
    [[BTKEntityAction sharedInstance] boundSearchEntityWith:request delegate:self];
}

- (void)districtSearch {
// 设置检索的过滤选项
BTKQueryEntityFilterOption *filterOption = [[BTKQueryEntityFilterOption alloc] init];
//    filterOption.entityNames = @[@"entityA", @"entityB", @"entityC"];
filterOption.activeTime = [[NSDate date] timeIntervalSince1970] - 49 * 24 * 3600;
// 设置检索结果的排序选项
BTKSearchEntitySortByOption *sortbyOption = [[BTKSearchEntitySortByOption alloc] init];
sortbyOption.fieldName = @"loc_time";
sortbyOption.sortType = BTK_ENTITY_SORT_TYPE_DESC;
BTKDistrictSearchEntityRequest *request = [[BTKDistrictSearchEntityRequest alloc] initWithQueryKeyword:@"海淀区" filter:filterOption sortby:sortbyOption outputCoordType:BTK_COORDTYPE_BD09LL returnType:BTK_ENTITY_SEARCH_RESULT_TYPE_ALL pageIndex:1 pageSize:10 ServiceID:serviceID tag:2];
    // 发起检索请求
[[BTKEntityAction sharedInstance] districtSearchEntityWith:request delegate:self];
    BMKDistrictSearch *search = [[BMKDistrictSearch alloc] init];
    BMKDistrictSearchOption *option = [[BMKDistrictSearchOption alloc] init];
    option.city = @"北京市";
    option.district = @"海淀区";
    search.delegate = self;
    BOOL flag = [search districtSearch:option];
    if (flag) {
        NSLog(@"行政区域检索成功！");
    }
}

#pragma mark - BMKDistrictSearchDelegate
/**
 行政区域检索结果回调
 
 @param searcher 检索对象
 @param result 行政区域检索结果
 @param error 错误码，@see BMKCloudErrorCode
 */
- (void)onGetDistrictResult:(BMKDistrictSearch *)searcher result:(BMKDistrictResult *)result errorCode:(BMKSearchErrorCode)error {
    [_mapView removeOverlays:_mapView.overlays];
    //BMKSearchErrorCode错误码，BMK_SEARCH_NO_ERROR：检索结果正常返回
    if (error == BMK_SEARCH_NO_ERROR) {
        for (NSString *path in result.paths) {
            BMKPolygon *polygon = [self transferPathStringToPolygon:path];
            /**
             向地图View添加Overlay，需要实现BMKMapViewDelegate的-mapView:viewForOverlay:方法
             来生成标注对应的View
             
             @param overlay 要添加的overlay
             */
            [_mapView addOverlay:polygon];
        }
        _mapView.centerCoordinate = result.center;
        _mapView.zoomLevel = 12;
    }
}

- (BMKPolygon *)transferPathStringToPolygon:(NSString *)path {
    NSUInteger pathCount = [path componentsSeparatedByString:@";"].count;
    if (pathCount > 0) {
        BMKMapPoint points[pathCount];
        NSArray *pointsArray = [path componentsSeparatedByString:@";"];
        for (NSUInteger i = 0; i < pathCount; i ++) {
            if ([pointsArray[i] rangeOfString:@","].location != NSNotFound) {
                NSArray *coordinates = [pointsArray[i] componentsSeparatedByString:@","];
                points[i] = BMKMapPointMake([coordinates.firstObject doubleValue], [coordinates .lastObject doubleValue]);
            }
        }
        /**
         根据多个点生成多边形
         
         points 直角坐标点数组，这些点将被拷贝到生成的多边形对象中
         count 点的个数
         新生成的多边形对象
         */
        BMKPolygon *polygon = [BMKPolygon polygonWithPoints:points count:pathCount];
        return polygon;
    }
    return nil;
}

#pragma mark - entity终端检索
/**
 圆形区域检索Entity终端实体的回调方法

 @param response 检索结果
 */
- (void)onEntityAroundSearch:(NSData *)response {
    NSDictionary *content = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:nil]; //转换数据格式
    if (content && [content[@"status"] intValue] == 0 && [content[@"size"] intValue] > 0) {
        [self showCarsWithEntities:(NSArray *)content[@"entities"]];
        dispatch_async(MAIN_QUEUE, ^{
            BMKCircle *circle = [[BMKCircle alloc] init];
            circle.radius = 1000;
            circle.coordinate = CLLocationCoordinate2DMake(40.054354, 116.300586);
            [self.mapView addOverlay:circle];
            self.mapView.centerCoordinate = circle.coordinate;
            self.mapView.zoomLevel = 16;
        });
    } else {
        dispatch_async(MAIN_QUEUE, ^{
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:content[@"message"] preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
            [alertController addAction:defaultAction];
            [self presentViewController:alertController animated:YES completion:nil];
        });
    }
    NSLog(@"检索结果：%@", content);
}

/**
 矩形区域检索Entity终端实体的回调方法

 @param response 检索结果
 */
- (void)onEntityBoundSearch:(NSData *)response {
    NSDictionary *content = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:nil]; //转换数据格式
    if (content && [content[@"status"] intValue] == 0 && [content[@"size"] intValue] > 0) {
        [self showCarsWithEntities:(NSArray *)content[@"entities"]];
        dispatch_async(MAIN_QUEUE, ^{
            CLLocationCoordinate2D *coors = new CLLocationCoordinate2D[4];
            coors[0] = CLLocationCoordinate2DMake(40.044302, 116.287507);
            coors[1] = CLLocationCoordinate2DMake(40.044302, 116.311079);
            coors[2] = CLLocationCoordinate2DMake(40.070258, 116.311079);
            coors[3] = CLLocationCoordinate2DMake(40.070258, 116.287507);
            BMKPolygon *polygon = [BMKPolygon polygonWithCoordinates:coors count:4];
            [self.mapView addOverlay:polygon];
            
            self.mapView.centerCoordinate = CLLocationCoordinate2DMake((40.044302 + 40.070258) / 2.0, (116.287507 + 116.311079) / 2.0);
            self.mapView.zoomLevel = 16;
        });
    } else {
        dispatch_async(MAIN_QUEUE, ^{
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:content[@"message"] preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
            [alertController addAction:defaultAction];
            [self presentViewController:alertController animated:YES completion:nil];
        });
    }
    NSLog(@"检索结果：%@", content);
}

/**
 多边形区域检索Entity终端实体的回调方法

 @param response 检索结果
 */
- (void)onEntityPolygonSearch:(NSData *)response {
    NSDictionary *content = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:nil]; //转换数据格式
    if (content && [content[@"status"] intValue] == 0 && [content[@"size"] intValue] > 0) {
        [self showCarsWithEntities:(NSArray *)content[@"entities"]];
        dispatch_async(MAIN_QUEUE, ^{
            CLLocationCoordinate2D *coors = new CLLocationCoordinate2D[4];
            coors[0] = CLLocationCoordinate2DMake(40.044302, 116.287507);
            coors[1] = CLLocationCoordinate2DMake(40.044302, 116.311079);
            coors[2] = CLLocationCoordinate2DMake(40.070258, 116.311079);
            coors[3] = CLLocationCoordinate2DMake(40.070258, 116.287507);
            BMKPolygon *polygon = [BMKPolygon polygonWithCoordinates:coors count:4];
            [self.mapView addOverlay:polygon];
            
            self.mapView.centerCoordinate = CLLocationCoordinate2DMake((40.044302 + 40.070258) / 2.0, (116.287507 + 116.311079) / 2.0);
            self.mapView.zoomLevel = 16;
        });
    } else {
        dispatch_async(MAIN_QUEUE, ^{
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:content[@"message"] preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
            [alertController addAction:defaultAction];
            [self presentViewController:alertController animated:YES completion:nil];
        });
    }
    NSLog(@"检索结果：%@", content);
}

/**
 行政区域内检索Entity终端实体的回调方法

 @param response 检索结果
 */
- (void)onEntityDistrictSearch:(NSData *)response {
    NSDictionary *content = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:nil]; //转换数据格式
    if (content && [content[@"status"] intValue] == 0 && [content[@"size"] intValue] > 0) {
        [self showCarsWithEntities:(NSArray *)content[@"entities"]];
    } else {
        dispatch_async(MAIN_QUEUE, ^{
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:content[@"message"] preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
            [alertController addAction:defaultAction];
            [self presentViewController:alertController animated:YES completion:nil];
        });
    }
    NSLog(@"检索结果：%@", content);
}

- (void)showCarsWithEntities:(NSArray *)entities {
    NSMutableArray *array = [NSMutableArray array];
    if (entities &&  entities.count > 0) {
        for (int i = 0; i < entities.count; i ++) {
            BMKPointAnnotation *annotation = [[BMKPointAnnotation alloc] init];
            NSDictionary *entity = entities[i];
            annotation.coordinate = CLLocationCoordinate2DMake([entity[@"latest_location"][@"latitude"] doubleValue], [entity[@"latest_location"][@"longitude"] doubleValue]);
            annotation.title = entity[@"entity_name"];
            [array addObject:annotation];
        }
        dispatch_async(MAIN_QUEUE, ^{
            [self.mapView addAnnotations:array];
        });
    }
}

#pragma mark - BMKMapViewDelegate
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation {
    static NSString *pointAnnotationViewID = @"pointAnnotationViewID";
    BMKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:pointAnnotationViewID];
    if (nil == annotationView) {
        annotationView = [[BMKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointAnnotationViewID];
    }
    annotationView.image = [UIImage imageNamed:@"car"];
    return annotationView;
}

- (BMKOverlayView *)mapView:(BMKMapView *)mapView viewForOverlay:(id<BMKOverlay>)overlay {
    if ([overlay isMemberOfClass:[BMKCircle class]]) {
        BMKCircleView *circleView = [[BMKCircleView alloc] initWithOverlay:overlay];
        circleView.fillColor = [[UIColor alloc] initWithRed:0 green:0 blue:1 alpha:0.2];
        circleView.strokeColor = [[UIColor alloc] initWithRed:0 green:0 blue:1 alpha:0.5];
        circleView.lineWidth = 1;
        return circleView;
    }
    if ([overlay isMemberOfClass:[BMKPolygon class]]) {
        BMKPolygonView *polygonView = [[BMKPolygonView alloc] initWithOverlay:overlay];
        polygonView.fillColor = [[UIColor alloc] initWithRed:0 green:0 blue:1 alpha:0.2];
        polygonView.strokeColor = [[UIColor alloc] initWithRed:0 green:0 blue:1 alpha:0.5];
        polygonView.lineWidth = 1;
        return polygonView;
    }
    return nil;
}

#pragma mark - Lazy loading
- (BMKMapView *)mapView {
    if (!_mapView) {
        CGRect mapRect = CGRectMake(0, kViewTopHeight + kHeight_SegMentBackgroud, self.view.bounds.size.width, self.view.bounds.size.height - kViewTopHeight - kHeight_SegMentBackgroud);
        _mapView = [[BMKMapView alloc] initWithFrame:mapRect];
    }
    return _mapView;
}

- (UISegmentedControl *)mapSegmentControl {
    if (!_mapSegmentControl) {
        NSArray *array = [[NSArray alloc] initWithObjects:@"周边搜索", @"矩形搜索", @"行政区域搜索", nil];
        _mapSegmentControl = [[UISegmentedControl alloc] initWithItems:array];
        _mapSegmentControl.frame = CGRectMake(30, kViewTopHeight + 12.5, self.view.frame.size.width - 60, 35);
        [_mapSegmentControl setTitle:@"周边搜索" forSegmentAtIndex:0];
        [_mapSegmentControl setTitle:@"矩形搜索" forSegmentAtIndex:1];
        [_mapSegmentControl setTitle:@"行政区域搜索" forSegmentAtIndex:2];
        _mapSegmentControl.selectedSegmentIndex = 0;
        [_mapSegmentControl addTarget:self action:@selector(segmentControlDidChangeValue:) forControlEvents:UIControlEventValueChanged];
    }
    return _mapSegmentControl;
}

@end
