//
//  POISuggestionSearchViewController.m
//  QMapKitDebugging
//
//  Created by Keith Cao on 2019/8/5.
//  Copyright © 2019 tencent. All rights reserved.
//

#import "POISuggestionSearchViewController.h"
#import "QPoiAnnotation.h"
#import <QMapKit/QMSSearchKit.h>

@interface POISuggestionSearchViewController () <UISearchBarDelegate, UISearchResultsUpdating, UITableViewDelegate,UITableViewDataSource,QMSSearchDelegate>

@property (nonatomic, strong) QMSSearcher *mySearcher;

@property (nonatomic, strong) QMSSuggestionResult *sugResult;

@property (nonatomic, strong) QMSGeoCodeSearchResult *geoResult;

@property (nonatomic, strong) QMSSuggestionSearchOption *sugOption;

@property (nonatomic, strong) UISearchController *searchController;

@property (nonatomic, strong) NSMutableArray *searchSuggestions;

@property (nonatomic, strong) UITableView *tableView;

@end

@implementation POISuggestionSearchViewController

#pragma mark - SearchController
- (void)setUpSearchController
{
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    
    self.searchController.searchResultsUpdater = self;
    self.searchController.dimsBackgroundDuringPresentation = NO;
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    
    self.searchController.searchBar.delegate = self;
    self.searchController.searchBar.placeholder = @"请输入关键字";
    [self.searchController.searchBar sizeToFit];
    
    UIView *viewForSearchbar = [[UIView alloc] initWithFrame:CGRectMake(self.mapView.frame.origin.x, self.mapView.frame.origin.y, self.mapView.frame.size.width, self.searchController.searchBar.frame.size.height)];

    [viewForSearchbar addSubview:self.searchController.searchBar];
    [self.mapView addSubview:viewForSearchbar];
    
}

#pragma mark - SearchControllerDelegate

- (void)updateSearchResultsForSearchController:(nonnull UISearchController *)searchController
{

    self.tableView.hidden = !searchController.isActive;
    
    [self suggestionSearch:searchController.searchBar.text];
    
    if (searchController.isActive && searchController.searchBar.text.length > 0)
    {
        searchController.searchBar.placeholder = searchController.searchBar.text;
    }
}


- (void)suggestionSearch:(NSString*) text
{
    [self.sugOption setKeyword:text];
    [self.sugOption setRegion:@"北京"];
    [self.mySearcher searchWithSuggestionSearchOption:self.sugOption];
    
}

- (void)fetchGeoData:(QMSSuggestionPoiData *)suggestionPoiData
{
    //配置搜索参数
    QMSGeoCodeSearchOption *geoOption = [[QMSGeoCodeSearchOption alloc] init];
    [geoOption setAddress:[suggestionPoiData address]];
    [geoOption setRegion:@"北京"];
    
    [self.mySearcher searchWithGeoCodeSearchOption:geoOption];
}

#pragma mark - SuggestionSearchDelegate

- (void)searchWithSearchOption:(QMSSearchOption *)searchOption didFailWithError:(NSError *)error
{
    NSLog(@"error: %@",error);
}

- (void)searchWithSuggestionSearchOption:(QMSSuggestionSearchOption *)suggestionSearchOption didReceiveResult:(QMSSuggestionResult *)suggestionSearchResult
{
    self.sugResult = suggestionSearchResult;
    
    NSLog(@"suggest result:%@", suggestionSearchResult);
    
    [self.tableView reloadData];
}

- (void)searchWithGeoCodeSearchOption:(QMSGeoCodeSearchOption *)geoCodeSearchOption didReceiveResult:(QMSGeoCodeSearchResult *)geoCodeSearchResult
{
    self.geoResult = geoCodeSearchResult;
    
    [self setupAnnotation];
}

#pragma mark - Annotations

- (void)setupAnnotation
{
    [self.mapView removeAnnotations:self.mapView.annotations];
    
    [self.mapView setCenterCoordinate:self.geoResult.location];
    
    QPoiAnnotation *annotation = [[QPoiAnnotation alloc] initWithPoiData:self.geoResult];
    [annotation setCoordinate:self.geoResult.location];
    [annotation setTitle:[NSString stringWithFormat:@"%@%@", self.geoResult.address_components.city, self.geoResult.address_components.district]];
    [annotation setSubtitle:[NSString stringWithFormat:@"lat:%f, lng:%f", self.geoResult.location.latitude, self.geoResult.location.longitude]];
    [self.mapView addAnnotation:annotation];
}

- (QAnnotationView *)mapView:(QMapView *)mapView viewForAnnotation:(id<QAnnotation>)annotation
{
    static NSString *reuseId = @"REUSE_ID";
    QPinAnnotationView *annotationView = (QPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseId];
    
    if (nil == annotationView) {
        annotationView = [[QPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseId];
    }
    
    annotationView.canShowCallout   = YES;
    
    return annotationView;
}

#pragma mark - TableView
- (void)initTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.searchController.searchBar.frame.size.height, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    
    self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.hidden = YES;
    
    [self.view addSubview:self.tableView];
}

#pragma mark - TableViewDelegate

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    static NSString *reuseId = @"REUSE_ID";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseId];
    if (nil == cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseId];
    }
    
    QMSSuggestionPoiData *poi = [self.sugResult.dataArray objectAtIndex:[indexPath row
                                                                               ]];
    
    [cell.textLabel setText:poi.title];
    [cell.detailTextLabel setText:[NSString stringWithFormat:@"%@ %@", poi.address, poi.adcode]];
    
    return cell;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.sugResult.dataArray.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    QMSSuggestionPoiData *poiData = [self.sugResult.dataArray objectAtIndex:[indexPath row]];
    
    [self fetchGeoData:poiData];
    
    [self.searchController setActive:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.mySearcher = [[QMSSearcher alloc] initWithDelegate:self];
    
    self.sugOption = [[QMSSuggestionSearchOption alloc] init];

    [self setUpSearchController];
    [self initTableView];
    
}

@end
