//
//  AMapNaviDriveVC.m
//  eTrip
//
//  Created by 廖毅 on 2019/4/8.
//  Copyright © 2019 Facebook. All rights reserved.
//

#import "AMapNaviDriveVC.h"
#import <AMapNaviKit/AMapNaviKit.h>
#import <AVFoundation/AVFoundation.h>

@interface AMapNaviDriveVC ()<AMapNaviDriveViewDelegate,AMapNaviDriveManagerDelegate>

@property (nonatomic,strong)AMapNaviDriveView *driveView;
@property (nonatomic,strong)AVSpeechSynthesizer *speechSynthesizer;


@end

@implementation AMapNaviDriveVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initDriveView];
    [self initDriveManager];
    self.speechSynthesizer=[[AVSpeechSynthesizer alloc]init];
}

//第 1 步，创建 AMapNaviDriveView
- (void)initDriveView
{
    if (self.driveView == nil)
    {
        self.driveView = [[AMapNaviDriveView alloc] initWithFrame:self.view.bounds];
        self.driveView.showMoreButton=false;
        self.driveView.trackingMode = AMapNaviViewTrackingModeCarNorth;//车头指北
        self.driveView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        [self.driveView setDelegate:self];

        [self.view addSubview:self.driveView];
    }
}
//第 2 步，创建 AMapNaviDriveManager
- (void)initDriveManager
{
    [[AMapNaviDriveManager sharedInstance] setDelegate:self];
    //将driveView添加为导航数据的Representative，使其可以接收到导航诱导数据
    [[AMapNaviDriveManager sharedInstance] addDataRepresentative:self.driveView];

//    [self calculateDriveRouteWithStartPoint];
    [self independentCalculateDriveRouteWithStartPOIInfo];
}

- (NSArray*)array2AMapNaviPointArray:(NSArray*)array
{
    NSMutableArray *wayPoints = [[NSMutableArray alloc] init];
    NSUInteger count = array.count;
    for( int i=0; i<count; i++){
        NSDictionary * dic=[array objectAtIndex:i];
        AMapNaviPoint *point=  [AMapNaviPoint locationWithLatitude:[[dic objectForKey:@"latitude"] doubleValue] longitude:[[dic objectForKey:@"longitude"] doubleValue]];
        [wayPoints addObject:point];
    }
    return wayPoints;
}

//第 3 步，进行路线规划
- (void)calculateDriveRouteWithStartPoint{
    NSArray *wayPoints=[self array2AMapNaviPointArray:self.wayPOIInfos];

    [[AMapNaviDriveManager sharedInstance] calculateDriveRouteWithStartPoints:@[[AMapNaviPoint locationWithLatitude:[[self.startPoi objectForKey:@"latitude"] doubleValue] longitude:[[self.startPoi objectForKey:@"longitude"] doubleValue]]] endPoints:@[[AMapNaviPoint locationWithLatitude:[[self.endPoi objectForKey:@"latitude"] doubleValue] longitude:[[self.endPoi objectForKey:@"longitude"] doubleValue]]] wayPoints:wayPoints drivingStrategy:self.drivingStrategy];
}
//第 4 步，开始实时导航
- (void)driveManager:(AMapNaviDriveManager *)driveManager onCalculateRouteSuccessWithType:(AMapNaviRoutePlanType)type;
{
    NSLog(@"onCalculateRouteSuccess");
    //算路成功后开始GPS导航
    [[AMapNaviDriveManager sharedInstance] startGPSNavi];
}

// 算路失败后的回调函数,路径规划页面的算路、导航页面的重算等失败后均会调用此方法
- (void)compositeManager:(AMapNaviCompositeManager *)compositeManager onCalculateRouteFailure:(NSError *)error {
    NSLog(@"onCalculateRouteFailure error:{%ld - %@}", (long)error.code, error.localizedDescription);
}

//独立规划算路 自定义导航线路
-(void)independentCalculateDriveRouteWithStartPOIInfo{
    NSArray *wayPoints=[self array2AMapNaviPointArray:self.wayPOIInfos];

    AMapNaviPoint *startPoint = [AMapNaviPoint locationWithLatitude:[[self.startPoi objectForKey:@"latitude"] doubleValue] longitude:[[self.startPoi objectForKey:@"longitude"] doubleValue]];
    AMapNaviPoint *endPoint   = [AMapNaviPoint locationWithLatitude:[[self.endPoi objectForKey:@"latitude"] doubleValue] longitude:[[self.endPoi objectForKey:@"longitude"] doubleValue]];
    AMapNaviPOIInfo *startPOI =  [[AMapNaviPOIInfo alloc] init];
    startPOI.locPoint =startPoint;
    AMapNaviPOIInfo *endPOI =  [[AMapNaviPOIInfo alloc] init];
    endPOI.locPoint = endPoint;

    [[AMapNaviDriveManager sharedInstance] independentCalculateDriveRouteWithStartPOIInfo:startPOI endPOIInfo:endPOI wayPOIInfos:wayPoints drivingStrategy:self.drivingStrategy callback:^(AMapNaviRouteGroup * _Nonnull routeGroup, NSError * _Nonnull error) {
        NSLog(@"group = %@, error = %@",routeGroup,error);
        // 1.获取独立算路的结果
        AMapNaviRouteGroup *independentRouteGroup = routeGroup;
        NSNumber *routeIDs = [independentRouteGroup.naviRouteIDs firstObject];
        //如果有距离限制 就在算出的路中找一条最接近的
        if(self.drivingDistance!=0){
            long diff=1000000000000;
            for (NSNumber *aRouteID in independentRouteGroup.naviRouteIDs)
            {
                if(ABS(self.drivingDistance-independentRouteGroup.naviRoutes[aRouteID].routeLength)<diff){
                    routeIDs=aRouteID;
                    diff=ABS(self.drivingDistance-independentRouteGroup.naviRoutes[aRouteID].routeLength);
                }
            }
        }
        // 2.行前选路
        [independentRouteGroup selectNaviRouteWithRouteID:[routeIDs integerValue]];
        // 3.使用独立路径规划的路线，开始导航
        [[AMapNaviDriveManager sharedInstance] startGPSNavi:independentRouteGroup];
    }];
}

- (void)dealloc
{
    [self destroyNavigation];
}

-(void)destroyNavigation{
    [[AMapNaviDriveManager sharedInstance] stopNavi];
    [[AMapNaviDriveManager sharedInstance] removeDataRepresentative:self.driveView];
    [[AMapNaviDriveManager sharedInstance] setDelegate:nil];

    BOOL success = [AMapNaviDriveManager destroyInstance];
    NSLog(@"单例是否销毁成功 : %d",success);
}

- (BOOL)driveManagerIsNaviSoundPlaying:(AMapNaviDriveManager *)driveManager
{
    return [self.speechSynthesizer isSpeaking];
}

- (void)driveManager:(AMapNaviDriveManager *)driveManager playNaviSoundString:(NSString *)soundString soundStringType:(AMapNaviSoundType)soundStringType
{
    NSLog(@"playNaviSoundString:{%ld:%@}", (long)soundStringType, soundString);
    AVSpeechUtterance*utterance = [[AVSpeechUtterance alloc]initWithString:soundString];//需要转换的文字
    utterance.rate=0.5;// 设置语速，范围0-1，注意0最慢，1最快；AVSpeechUtteranceMinimumSpeechRate最慢，AVSpeechUtteranceMaximumSpeechRate最快
    AVSpeechSynthesisVoice*voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];//设置发音，这是中文普通话
    utterance.voice= voice;
    [self.speechSynthesizer speakUtterance:utterance];//开始
}
//退出导航按钮被点击
- (void)driveViewCloseButtonClicked:(AMapNaviDriveView *)driveView{
    [self.speechSynthesizer stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
    [self destroyNavigation];
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
