#import "ClxMapPoiSearchPlugin.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>

@interface ClxMapPoiSearchPlugin ()<AMapSearchDelegate>

@property (nonatomic, strong) FlutterMethodChannel *channel;
@property (nonatomic, strong) AMapSearchAPI *search;
@property (nonatomic, strong) FlutterResult resultM;

@end

@implementation ClxMapPoiSearchPlugin

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"clx_map_poi_search"
                                                                binaryMessenger:[registrar messenger]];
    ClxMapPoiSearchPlugin *instance = [[ClxMapPoiSearchPlugin alloc] init];
    instance.channel = channel;
    [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    NSDictionary *arguments = call.arguments;
    __weak ClxMapPoiSearchPlugin *weakSelf = self;
    self.resultM = result;
    
    if ([@"searchPOI#keywords" isEqualToString:call.method]) {
        @try {
            if ([arguments.allKeys containsObject:@"keywords"]) {
                NSString *keywords = arguments[@"keywords"];
                NSLog(@"---handleMethodCall--- keywords:%@", keywords);
                [weakSelf keywordsSearch:keywords];
            }
        } @catch(FlutterError *e) {
            result(e);
        }
    } else if ([@"searchPOI#around" isEqualToString:call.method]) {
        @try {
            if ([arguments.allKeys containsObject:@"latitude"] && [arguments.allKeys containsObject:@"longitude"]) {
                NSString *latitude = arguments[@"latitude"];
                NSString *longitude = arguments[@"longitude"];
                NSLog(@"---handleMethodCall--- latitude:%@, longitude:%@", latitude, longitude);
                [weakSelf aroundSearch:[latitude floatValue] Lng:[longitude floatValue]];
            }
        } @catch(FlutterError *e) {
            result(e);
        }
    } else if ([@"searchPOI#initPoiSearch" isEqualToString:call.method]) {
        @try {
            NSDictionary *apiKey = arguments[@"apiKey"];
            if (apiKey && [apiKey isKindOfClass:[NSDictionary class]]) {
                NSString *iosKey = apiKey[@"iosKey"];
                if (iosKey && iosKey.length > 0) {//通过flutter传入key,则再重新设置一次key
                    [AMapServices sharedServices].apiKey = iosKey;
                    NSLog(@"---handleMethodCall--- apiKey:%@", apiKey);
                }
            }
            //这里统一检查key的设置是否生效
            NSAssert(([AMapServices sharedServices].apiKey != nil), @"没有设置APIKey,请先设置key");
            
            // 隐私合规
            [AMapSearchAPI updatePrivacyShow:AMapPrivacyShowStatusDidShow
                                 privacyInfo:AMapPrivacyInfoStatusDidContain];
            [AMapSearchAPI updatePrivacyAgree:AMapPrivacyAgreeStatusDidAgree];
            
            result(nil);
        } @catch(FlutterError *e) {
            result(e);
        }
    } else if ([@"searchPOI#around#all" isEqualToString:call.method]) {
        @try {
            NSLog(@"---handleMethodCall--- arguments:%@", arguments);
            [weakSelf aroundSearchAll:arguments];
        } @catch(FlutterError *e) {
            result(e);
        }
    } else if ([@"getPlatformVersion" isEqualToString:call.method]) {
        result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
    } else {
        result(FlutterMethodNotImplemented);
    }
}

- (void)keywordsSearch:(NSString *)keywords {
    AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
    request.keywords = keywords;
    request.page = 1;
    request.offset = 20;
    //是否返回扩展信息
    //request.requireExtension = YES;
    [self.search AMapPOIKeywordsSearch:request];
}

- (void)aroundSearch:(CGFloat)lat Lng:(CGFloat)lon {
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude:lat longitude:lon];
    request.page = 1;
    request.offset = 20;
    request.radius = 1000;
    [self.search AMapPOIAroundSearch:request];
}

- (void)aroundSearchAll:(NSDictionary *)arguments {
    NSString *latitude = arguments[@"latitude"];
    NSString *longitude = arguments[@"longitude"];
    NSString *keywords = arguments[@"keywords"];
    NSString *city = arguments[@"city"];
    
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude:[latitude floatValue] longitude:[longitude floatValue]];
    request.page = 1;
    request.offset = 20;
    request.radius = 1000;
    if (keywords.length != 0) {
        request.keywords = keywords;
    }
    if (city.length != 0) {
        request.city = city;
    }
    [self.search AMapPOIAroundSearch:request];
}

#pragma mark -
#pragma mark - AMapSearchDelegate

- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response {
    NSLog(@"onPOISearchDone 结束:%lu", (unsigned long)response.pois.count);
    
    NSArray<AMapPOI *> *pois = response.pois;
    if (pois.count > 0) {
        NSMutableDictionary *arguments = [NSMutableDictionary dictionary];
        NSMutableDictionary *data = [NSMutableDictionary dictionary];
        NSMutableArray *listArray = [NSMutableArray array];
        for (AMapPOI *poiItem in pois) {
            NSMutableDictionary *dicMut = [NSMutableDictionary dictionary];
            [dicMut setValue:@(poiItem.location.latitude) forKey:@"latitude"];
            [dicMut setValue:@(poiItem.location.longitude) forKey:@"longitude"];
            [dicMut setValue:poiItem.province forKey:@"provinceName"];
            [dicMut setValue:poiItem.pcode forKey:@"provinceCode"];
            [dicMut setValue:poiItem.city forKey:@"cityName"];
            [dicMut setValue:poiItem.citycode forKey:@"cityCode"];
            [dicMut setValue:poiItem.address forKey:@"adName"];
            [dicMut setValue:poiItem.businessArea forKey:@"businessArea"];
            [dicMut setValue:@(poiItem.distance) forKey:@"distance"];
            
            [dicMut setValue:@"" forKey:@"snippet"];
            [dicMut setValue:poiItem.name forKey:@"title"];
            [listArray addObject:dicMut];
        }
        [data setValue:listArray forKey:@"poiList"];
        [arguments setValue:data forKey:@"searchPOIResult"];
        NSLog(@"onPOISearchDone 1 : arguments=%@", arguments);
        
        // 回调
        if (arguments) {
            self.resultM(arguments);
            //[_channel invokeMethod:@"camera#searchPOIEvent" arguments:arguments];
        }
    } else {
        NSMutableDictionary *arguments = [NSMutableDictionary dictionary];
        NSMutableDictionary *data = [NSMutableDictionary dictionary];
        NSMutableArray *listArray = [NSMutableArray array];
        [data setValue:listArray forKey:@"poiList"];
        [arguments setValue:data forKey:@"searchPOIResult"];
        self.resultM(arguments);
        //[_channel invokeMethod:@"camera#searchPOIEvent" arguments:arguments];
        NSLog(@"onPOISearchDone 2 : arguments=%@", arguments);
        return;
    }
}

- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error {
    NSLog(@"Error: %@", error);
}

#pragma mark -
#pragma mark - 懒加载

- (AMapSearchAPI *)search {
    if (!_search) {
        _search = [[AMapSearchAPI alloc] init];
        _search.delegate = self;
    }
    return  _search;
}

@end