//
//  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=true;
        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];

    // 初始播报模式（默认详细播报）
    [[AMapNaviDriveManager sharedInstance] setBroadcastMode:AMapNaviBroadcastModeDetailed];

//    [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];
        //将路线发送到js端
        [self onNaviRouteSuccess:routeIDs];
    }];
}

-(void)onNaviRouteSuccess:(NSNumber *)routeID{
    AMapNaviRoute *aRoute = [[[AMapNaviDriveManager sharedInstance] naviRoutes] objectForKey:routeID];
    int count = (int)[[aRoute routeCoordinates] count];
    NSMutableArray* coordinates=[[NSMutableArray alloc] init];
    NSMutableDictionary * route=[[NSMutableDictionary alloc] init];
    for (int i = 0; i < count; i++)
    {
        AMapNaviPoint *coordinate = [[aRoute routeCoordinates] objectAtIndex:i];
        NSDictionary *dict = @{@"latitude":[NSNumber numberWithFloat:coordinate.latitude], @"longitude":[NSNumber numberWithFloat:coordinate.longitude]};
        [coordinates addObject:dict];
    }
    [route setValue:coordinates forKey:@"coordList"];
    [route setObject:[NSNumber numberWithLong:(long)aRoute.routeLength] forKey:@"allLength"];
    [route setObject:[NSNumber numberWithLong:(long)aRoute.routeTime] forKey:@"allTime"];
    [route setObject:aRoute.routeLabels forKey:@"labels"];
    //        [route setObject:aRoute.routeLabels forKey:@"mainRoadInfo"];
    [route setObject:[NSNumber numberWithLong:aRoute.routeUID] forKey:@"pathId"];
    [route setObject:[NSNumber numberWithLong:aRoute.routeTollCost] forKey:@"tollCost"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"onNaviRouteSuccess" object:route];
}

- (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);
    // 关闭播报模式，不播放
    if (self.voiceMode == 2) {
        return;
    }
    // 详细/简洁播报均由SDK控制，此处直接播放
    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];
}

//更多按钮(设置)被点击
- (void)driveViewMoreButtonClicked:(AMapNaviDriveView *)driveView {
    [self showSettingsBottomSheet];
}

#pragma mark - 自定义设置底部弹窗

- (void)showSettingsBottomSheet {
    UIView *container = self.view;

    UIView *overlay = [[UIView alloc] initWithFrame:container.bounds];
    overlay.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
    overlay.alpha = 0;
    overlay.tag = 9001;
    [container addSubview:overlay];

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideSettingsBottomSheet)];
    [overlay addGestureRecognizer:tap];

    CGFloat cardWidth = container.bounds.size.width;
    CGFloat cardHeight = 420;
    UIView *card = [[UIView alloc] initWithFrame:CGRectMake(0, container.bounds.size.height, cardWidth, cardHeight)];
    card.tag = 9002;
    card.backgroundColor = [UIColor whiteColor];
    card.layer.cornerRadius = 20;
    card.layer.maskedCorners = kCALayerMinXMaxYCorner | kCALayerMaxXMaxYCorner;
    card.layer.shadowColor = [UIColor blackColor].CGColor;
    card.layer.shadowOffset = CGSizeMake(0, -4);
    card.layer.shadowOpacity = 0.12;
    card.layer.shadowRadius = 16;
    [container addSubview:card];

    CGFloat px = 24;
    CGFloat y = 16;

    UIView *handle = [[UIView alloc] initWithFrame:CGRectMake((cardWidth - 40) / 2, y, 40, 4)];
    handle.backgroundColor = [UIColor colorWithWhite:0.88 alpha:1];
    handle.layer.cornerRadius = 2;
    [card addSubview:handle];
    y += 24;

    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(px, y, cardWidth - px * 2, 28)];
    titleLabel.text = @"导航设置";
    titleLabel.font = [UIFont boldSystemFontOfSize:20];
    titleLabel.textColor = [UIColor colorWithWhite:0.1 alpha:1];
    [card addSubview:titleLabel];
    y += 40;

    UIView *sep1 = [[UIView alloc] initWithFrame:CGRectMake(0, y, cardWidth, 0.5)];
    sep1.backgroundColor = [UIColor colorWithWhite:0.92 alpha:1];
    [card addSubview:sep1];
    y += 16;

    UILabel *voiceHeader = [[UILabel alloc] initWithFrame:CGRectMake(px, y, cardWidth - px * 2, 16)];
    voiceHeader.text = @"语音播报";
    voiceHeader.font = [UIFont systemFontOfSize:13];
    voiceHeader.textColor = [UIColor colorWithWhite:0.55 alpha:1];
    [card addSubview:voiceHeader];
    y += 24;

    NSArray *modes = @[@"详细播报", @"简洁播报", @"关闭播报"];
    for (NSInteger i = 0; i < modes.count; i++) {
        UIView *row = [[UIView alloc] initWithFrame:CGRectMake(0, y, cardWidth, 48)];
        [card addSubview:row];

        BOOL isSelected = (i == self.voiceMode);
        CGFloat radioSize = 22;
        CGFloat radioX = px;
        CGFloat radioY = (48 - radioSize) / 2;
        UILabel *radio = [[UILabel alloc] initWithFrame:CGRectMake(radioX, radioY, radioSize, radioSize)];
        radio.layer.cornerRadius = radioSize / 2;
        radio.layer.masksToBounds = YES;
        radio.layer.borderWidth = 2;
        radio.textAlignment = NSTextAlignmentCenter;
        radio.font = [UIFont boldSystemFontOfSize:13];
        UIColor *themeColor = [UIColor colorWithRed:0x04/255.0 green:0x52/255.0 blue:0xDD/255.0 alpha:1];
        if (isSelected) {
            radio.layer.borderColor = themeColor.CGColor;
            radio.backgroundColor = themeColor;
            radio.text = @"✓";
            radio.textColor = [UIColor whiteColor];
        } else {
            radio.layer.borderColor = [UIColor colorWithWhite:0.78 alpha:1].CGColor;
            radio.backgroundColor = [UIColor clearColor];
            radio.text = @"";
        }
        [row addSubview:radio];

        UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(radioX + radioSize + 16, 0, cardWidth - radioX - radioSize - 16 - px, 48)];
        lbl.text = modes[i];
        lbl.font = [UIFont systemFontOfSize:16];
        lbl.textColor = [UIColor colorWithWhite:0.2 alpha:1];
        [row addSubview:lbl];

        NSInteger mode = i;
        UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(voiceModeTapped:)];
        row.tag = 100 + mode;
        [row addGestureRecognizer:tap2];

        y += 48;
        if (i < modes.count - 1) {
            UIView *sep = [[UIView alloc] initWithFrame:CGRectMake(px, y, cardWidth - px * 2, 0.5)];
            sep.backgroundColor = [UIColor colorWithWhite:0.94 alpha:1];
            [card addSubview:sep];
        }
    }
    y += 16;

    UILabel *navHeader = [[UILabel alloc] initWithFrame:CGRectMake(px, y, cardWidth - px * 2, 16)];
    navHeader.text = @"导航方向";
    navHeader.font = [UIFont systemFontOfSize:13];
    navHeader.textColor = [UIColor colorWithWhite:0.55 alpha:1];
    [card addSubview:navHeader];
    y += 24;

    UIView *trackingRow = [[UIView alloc] initWithFrame:CGRectMake(0, y, cardWidth, 48)];
    [card addSubview:trackingRow];

    NSString *trackingText = (self.driveView.trackingMode == AMapNaviViewTrackingModeCarNorth) ? @"车头朝上" : @"车头指北";
    UILabel *trackingLbl = [[UILabel alloc] initWithFrame:CGRectMake(px, 0, cardWidth - px * 2 - 120, 48)];
    trackingLbl.text = trackingText;
    trackingLbl.font = [UIFont systemFontOfSize:16];
    trackingLbl.textColor = [UIColor colorWithWhite:0.2 alpha:1];
    [trackingRow addSubview:trackingLbl];

    UIButton *switchBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    switchBtn.frame = CGRectMake(cardWidth - px - 100, 8, 92, 32);
    switchBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [switchBtn setTitle:@"切换" forState:UIControlStateNormal];
    switchBtn.layer.cornerRadius = 16;
    switchBtn.backgroundColor = [UIColor colorWithWhite:0.94 alpha:1];
    [switchBtn setTitleColor:[UIColor colorWithRed:0x04/255.0 green:0x52/255.0 blue:0xDD/255.0 alpha:1] forState:UIControlStateNormal];
    [switchBtn addTarget:self action:@selector(toggleTrackingMode) forControlEvents:UIControlEventTouchUpInside];
    [trackingRow addSubview:switchBtn];
    y += 56;

    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    confirmBtn.frame = CGRectMake(px, y, cardWidth - px * 2, 48);
    [confirmBtn setTitle:@"确定" forState:UIControlStateNormal];
    confirmBtn.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    confirmBtn.backgroundColor = [UIColor colorWithRed:0x04/255.0 green:0x52/255.0 blue:0xDD/255.0 alpha:1];
    confirmBtn.layer.cornerRadius = 24;
    [confirmBtn addTarget:self action:@selector(hideSettingsBottomSheet) forControlEvents:UIControlEventTouchUpInside];
    [card addSubview:confirmBtn];

    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        overlay.alpha = 1;
        card.frame = CGRectMake(0, container.bounds.size.height - cardHeight, cardWidth, cardHeight);
    } completion:nil];
}

- (void)hideSettingsBottomSheet {
    UIView *overlay = [self.view viewWithTag:9001];
    UIView *card = [self.view viewWithTag:9002];
    if (!overlay || !card) return;

    [UIView animateWithDuration:0.25 animations:^{
        overlay.alpha = 0;
        card.frame = CGRectMake(0, self.view.bounds.size.height, card.frame.size.width, card.frame.size.height);
    } completion:^(BOOL finished) {
        [overlay removeFromSuperview];
        [card removeFromSuperview];
    }];
}

- (void)voiceModeTapped:(UITapGestureRecognizer *)gesture {
    NSInteger mode = gesture.view.tag - 100;
    self.voiceMode = mode;

    UIView *card = [self.view viewWithTag:9002];
    if (!card) return;
    UIColor *themeColor = [UIColor colorWithRed:0x04/255.0 green:0x52/255.0 blue:0xDD/255.0 alpha:1];
    for (UIView *sub in card.subviews) {
        if (sub.tag >= 100 && sub.tag < 103) {
            NSInteger rowMode = sub.tag - 100;
            for (UIView *child in sub.subviews) {
                if ([child isKindOfClass:[UILabel class]] && child.layer.cornerRadius > 0 && child.frame.size.width == child.frame.size.height) {
                    UILabel *radio = (UILabel *)child;
                    if (rowMode == mode) {
                        radio.layer.borderColor = themeColor.CGColor;
                        radio.backgroundColor = themeColor;
                        radio.text = @"✓";
                        radio.textColor = [UIColor whiteColor];
                    } else {
                        radio.layer.borderColor = [UIColor colorWithWhite:0.78 alpha:1].CGColor;
                        radio.backgroundColor = [UIColor clearColor];
                        radio.text = @"";
                    }
                }
            }
        }
    }
}

- (void)applyVoiceMode:(NSInteger)mode {
    self.voiceMode = mode;
    switch (mode) {
        case 0: [[AMapNaviDriveManager sharedInstance] setBroadcastMode:AMapNaviBroadcastModeDetailed]; break;
        case 1: [[AMapNaviDriveManager sharedInstance] setBroadcastMode:AMapNaviBroadcastModeConcise]; break;
        case 2: [self.speechSynthesizer stopSpeakingAtBoundary:AVSpeechBoundaryImmediate]; break;
    }
}

- (void)toggleTrackingMode {
    if (self.driveView.trackingMode == AMapNaviViewTrackingModeCarNorth) {
        self.driveView.trackingMode = AMapNaviViewTrackingModeMapNorth;
    } else {
        self.driveView.trackingMode = AMapNaviViewTrackingModeCarNorth;
    }
    UIView *card = [self.view viewWithTag:9002];
    if (!card) return;
    for (UIView *sub in card.subviews) {
        for (UIView *child in sub.subviews) {
            if ([child isKindOfClass:[UILabel class]] && child.frame.origin.y == 0 && child.frame.origin.x == 24 && child.frame.size.height == 48) {
                UILabel *lbl = (UILabel *)child;
                if (lbl.text.length > 0 && (lbl.font.pointSize == 16) && ![lbl.text isEqualToString:@"导航设置"]) {
                    lbl.text = (self.driveView.trackingMode == AMapNaviViewTrackingModeCarNorth) ? @"车头朝上" : @"车头指北";
                }
            }
        }
    }
}

@end
