//
//  DistrictListSearchViewController.m
//  QMapKitDemo
//
//  Created by Keith Cao on 2023/10/20.
//  Copyright © 2023 tencent. All rights reserved.
//

#import "DistrictListSearchViewController.h"
#import <QMapKit/QMSSearchKit.h>
#import "QSearchTools.h"

@interface DistrictListSearchViewController () <QMSSearchDelegate>

@property (nonatomic, strong) QMSSearcher *searcher;

@end

@implementation DistrictListSearchViewController

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

- (void)executeDistrictListSearch
{
	self.searcher = [[QMSSearcher alloc] initWithDelegate:self];
	
	QMSDistrictListSearchOption *districtListSearchOption = [[QMSDistrictListSearchOption alloc] init];
	
	[self.searcher searchWithDistrictListSearchOption:districtListSearchOption];
	
}

- (void)dealWithDistrictSearchResult:(QMSDistrictSearchResult *)result
{
	NSArray <QMSDistrictData *> *districtArray = result.result.firstObject;
	
	if (districtArray.count > 0)
	{
		NSMutableArray *annos = [NSMutableArray array];
		// 遍历每个行政区划数据
		for (QMSDistrictData *data in districtArray)
		{
			QPointAnnotation *anno = [[QPointAnnotation alloc] init];
			anno.coordinate = data.location;
			anno.title = data.fullname;
			anno.subtitle = data.id_;
			
			[annos addObject:anno];
		}
		
		[self.mapView addAnnotations:annos];
		
		QMapRect rect = [self.mapView mapRectThatFits:self.mapView.visibleMapRect containsCalloutView:YES annotations:annos edgePadding:UIEdgeInsetsZero];
		
		[self.mapView setVisibleMapRect:rect animated:YES];
	}
}

#pragma mark -- Search Delegate
- (void)searchWithSearchOption:(QMSSearchOption *)searchOption didFailWithError:(NSError *)error
{
	NSLog(@"search error :%@", error);
}

- (void)searchWithDistrictSearchOption:(QMSDistrictBaseSearchOption *)districtSearchOption didRecevieResult:(QMSDistrictSearchResult *)districtSearchResult
{
	[self dealWithDistrictSearchResult:districtSearchResult];
}

#pragma mark -- Map Delegate
- (QAnnotationView *)mapView:(QMapView *)mapView viewForAnnotation:(id<QAnnotation>)annotation
{
	if ([annotation isKindOfClass:[QPointAnnotation class]])
	{
		static NSString *pointReuseIndetifier = @"pointReuseIndetifier";
		QPinAnnotationView *annotationView = (QPinAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
		
		if (annotationView == nil)
		{
			annotationView = [[QPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndetifier];
		}
		
		// 可拖拽.
		//		annotationView.draggable = YES;
		
		annotationView.canShowCallout = YES;
		
		// 开启下落动画
		annotationView.animatesDrop = YES;
		
		return annotationView;
	}
	
	return nil;
}

@end
