//
//  BCAMapNaviDriveViewController.m
//  ChatAgentApp
//
//  Created by caoshiqian on 2025/4/22.
//

#import "BCAMapNaviDriveViewController.h"
#import "RouteContentView.h"
#import "RadarSwitchView.h"
#import "RadarLocationView.h"
#import "MapCommonDefine.h"
#import "BNRoutePlanModel.h"
#import "BNaviService.h"
#import "BNCommonDef.h"

#define kPanelHeight        (ADAPTOR_VALUE_750(302) + SAFE_AREA_INSETS_BOTTOM) //底部面板显示区域高度
#define kPanelLessHeight    (ADAPTOR_VALUE_750(266) + SAFE_AREA_INSETS_BOTTOM)
#define kLeftOffset         (CR_MAP_VIEW_ENTRANCE_RIGHT_MARGIN+4+1)

@interface BCAMapNaviDriveViewController ()<BNNaviRoutePlanDelegate, BNDriveRouteManagerDelegate, RadarLocationViewDelegate, BNNaviUIManagerDelegate, BMKMapViewDelegate>

@property (nonatomic, strong) RouteContentView *contentView;
@property (nonatomic, strong) RadarSwitchView *radarSwitchView;
@property (nonatomic, strong) RadarLocationView *radarLocationView;
@property (nonatomic, assign) BOOL isExitNavi;
@property (nonatomic, strong) UIButton *backButton;

@end

@implementation BCAMapNaviDriveViewController

- (void)dealloc {
    [BNaviService_DriveRoute stopUpdateLocation];
    NSLog(@"[map] BCAMapNaviDriveViewController Dealloc");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.contentView.tabPanel pageLoading];
    
    BNaviService_DriveRoute.delegate = self;
    [BNaviService_Instance naviMapView].delegate = self;

    [self setupBackButton];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (!self.isExitNavi) {
        [self startRoutePlan];
    }
    self.isExitNavi = NO;
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    [BNaviService_DriveRoute viewWillAppear:self.view];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    [BNaviService_DriveRoute viewWillDisAppear:self.view];
}

- (void)startRoutePlan {
//    [self addVdrIndoorLocation];
    
    [self.contentView.tabPanel pageLoading];
    [BNaviService_YellowTips removeYellowTipFromContainer];
    [self showRouteViewAll];
    /// 获取路线数据
    BNCarRouteModel *routeModel =  [BNaviService_DriveRoute getCurrentCarRouteData];
    if (self.isTripType) {
//        BNaviService_YellowTips.dataSource = self;
//        CGFloat top = [[UIApplication sharedApplication] statusBarFrame].size.height+ 44.f;
//        self.customYellowTipsBgVew.frame = CGRectMake(0, top, self.view.width, 50);
        [self showRouteViewAll];
        
//        [BNaviService_YellowTips addYellowTipsContainer:self.customYellowTipsBgVew];
    } else {
//        [BNaviService_YellowTips addYellowTipsContainer:self.customYellowTipsBgVew];
    }
    
    if (routeModel) {
        self.carRoute = routeModel;
        [self routeSelectIndex:[BNaviService_RoutePlan GetCurrentSelectRouteIdx] needSelectRoute:NO];
        
        [self resetUIFrame]; // [self resetUIFrame];需要在pageLoadedSuccess前，因为tabPanel中会用到tabPanel的高度
        [self.contentView.tabPanel pageLoadedSuccess:self.carRoute];
        [self.contentView.carDetailContentView refreshData:self.carRoute index:self.selectIndex];
    }
    
    // 算路成功后需要打开定位才能显示车标
   
    [BNaviService_DriveRoute startUpdateLocation];
}

- (void)closeViewController {
    if (self.presentingViewController || self.presentationController) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - Public
- (void)carRouteDidSelectAtIndex:(NSInteger)index {
    [self showRouteViewAll];
    if (index >= 0 && index < self.carRoute.carRoutes.count) {
        [self routeSelectIndex:index needSelectRoute:YES];
        [self.contentView.carDetailContentView refreshData:self.carRoute index:self.selectIndex];
    }
}
 
//- (void)yellowTips_ClickedWithItemRoutID:(NSNumber *)roudId{
//    [self.myYellowTipsView removeFromSuperview];
//    [self showRouteViewTop:0];
//}


- (void)enterNaviPage {
    [BNaviService_DriveRoute stopUpdateLocation];
    [BNaviService_UI showPage:BNaviUI_NormalNavi delegate:self extParams:@{BNaviUI_NormalNavi_TypeKey: @(self.naviType)}];
}

- (void)retryRoutePlan {
    [self startRoutePlan];
}

#pragma mark - Private
- (void)routeSelectIndex:(NSInteger)selectIndex needSelectRoute:(BOOL)needSelectRoute {
    self.selectIndex = selectIndex;
    
    if (needSelectRoute) {
        [BNaviService_DriveRoute selectRouteAtIndex:selectIndex];
        [self showRouteViewAll];
    }
}

- (CGFloat)bottomPaneHeight {
    if (self.carRoute.carRoutes.count == 1) {
        return kPanelLessHeight;
    } else {
        return kPanelHeight;
    }
}

- (void)resetUIFrame {
    CGFloat naviBtnHeight = 0;
    if (self.isTripType) {
        naviBtnHeight = 45;
    }
    self.contentView.frame = CGRectMake(0, IPHONE_SCREEN_HEIGHT-[self bottomPaneHeight]+naviBtnHeight, IPHONE_SCREEN_WIDTH, [self bottomPaneHeight]-naviBtnHeight);
    if (self.isTripType) {
        CGRect rect = self.contentView.frame;
        rect.origin.y = IPHONE_SCREEN_HEIGHT-[self bottomPaneHeight] + naviBtnHeight - 10;
        rect.size.height = [self bottomPaneHeight] - naviBtnHeight;
        self.contentView.frame = rect;
    }
    self.radarLocationView.frame = CGRectMake(kLeftOffset, self.contentView.top - kRAButtonHeight-5, kRAButtonWidth, kRAButtonHeight);
    
    self.radarSwitchView.frame = CGRectMake(IPHONE_SCREEN_WIDTH-kRAButtonWidth-kLeftOffset, self.contentView.top - (kRAButtonHeight*2+1)-5, kRAButtonWidth, kRAButtonHeight*2+1);
    self.radarSwitchView.bottom = self.radarLocationView.bottom;
//    self.logoView.frame = CGRectMake(CGRectGetMaxX(self.radarLocationView.frame)+5, IPHONE_SCREEN_HEIGHT-[self bottomPaneHeight]-self.logoView.height-5, self.logoView.width, self.logoView.height);
    [self.contentView reset];
    if (self.isTripType) {
        [self.contentView.tabPanel hiddenNaviBtn:self.isTripType];
    }
}

- (void)showRouteViewAll {
//    if (self.customYellowTipsBgVew) {
//        [self showRouteViewTop:self.customYellowTipsBgVew.height];
//    }
    [self showRouteViewTop:0];
}

- (void)showRouteViewTop:(CGFloat)offset {
    CGFloat top = [[UIApplication sharedApplication] statusBarFrame].size.height+ 44.f;
    BNMargin margin = {top+offset, 20, self.view.frame.size.height-self.radarSwitchView.frame.origin.y, 20};
    
    [BNaviService_DriveRoute showRouteViewAll:margin animated:YES];
    
}

- (void)refreshRouteData {
    BNCarRouteModel *route = [BNaviService_DriveRoute getCurrentCarRouteData];
    if (route) {
        self.carRoute = route;
        [self routeSelectIndex:[BNaviService_RoutePlan GetCurrentSelectRouteIdx] needSelectRoute:NO];
        
        [self resetUIFrame]; // [self resetUIFrame];需要在pageLoadedSuccess前，因为tabPanel中会用到tabPanel的高度
        [self.contentView.tabPanel pageLoadedSuccess:self.carRoute];
        [self.contentView.carDetailContentView refreshData:self.carRoute index:self.selectIndex];
    } else { // 没获取到当前路线信息，有可能是已经到达终点，退出驾车页
        [self.navigationController popViewControllerAnimated:YES];
    }
}


#pragma mark - BNDriveRouteManagerDelegate

/**
 用户在地图上点击了某条路线（如果需要高亮该路线，要调用selectRouteAtIndex:接口）
 
 @param routeIndex 路线序号（从0开始）
 */
- (void)onHandleTouchRouteAtIndex:(NSUInteger)routeIndex {
    if (routeIndex < self.carRoute.carRoutes.count) {
        [self routeSelectIndex:routeIndex needSelectRoute:NO];
        [self.contentView.tabPanel selectAtIndex:self.selectIndex];
        [self.contentView.carDetailContentView refreshData:self.carRoute index:self.selectIndex];
    }
}

- (void)onHandleUpdateCurrentCarPositionInfo:(NSDictionary *)positionInfo {
    
}

#pragma mark - RadarLocationViewDelegate
- (void)radarLocation:(RadarLocationView *)locationView {
    [self showRouteViewAll];
}

#pragma mark - BNMapViewManagerDelegate
- (void)mapStatusDidChanged:(BMKMapView *)mapView {
    [self.radarSwitchView handleMapLevelChange:[mapView getMapStatus].fLevel];
}
- (void)onHandleMapLevelChange:(NSInteger)level {
    [self.radarSwitchView handleMapLevelChange:level];
}

#pragma mark - BNNaviUIManagerDelegate

- (void)willExitPage:(BNaviUIType)pageType extraInfo:(NSDictionary*)extraInfo {
    self.isExitNavi = YES;
    [self showRouteViewAll];
    [BNaviService_DriveRoute startUpdateLocation];
    
    [self refreshRouteData];
}

#pragma mark - Lazy loading

- (RouteContentView *)contentView {
    if (!_contentView) {
        _contentView = [[RouteContentView alloc] initWithFrame:CGRectMake(0, IPHONE_SCREEN_HEIGHT-[self bottomPaneHeight], IPHONE_SCREEN_WIDTH, [self bottomPaneHeight])];
        _contentView.drivePageVc = self;
        [self.view addSubview:_contentView];
    }
    return _contentView;
}

- (RadarSwitchView *)radarSwitchView {
    if (!_radarSwitchView) {
        _radarSwitchView = [[RadarSwitchView alloc] initWithFrame:CGRectMake(IPHONE_SCREEN_WIDTH-kRAButtonWidth-kLeftOffset, IPHONE_SCREEN_HEIGHT-[self bottomPaneHeight]-(kRAButtonHeight*2+1)-5, kRAButtonWidth, kRAButtonHeight*2+1)];
        [self.view insertSubview:_radarSwitchView belowSubview:self.contentView];
    }
    return _radarSwitchView;
}

- (RadarLocationView *)radarLocationView {
    if (!_radarLocationView) {
        _radarLocationView = [[RadarLocationView alloc] initWithFrame:CGRectMake(kLeftOffset, IPHONE_SCREEN_HEIGHT-[self bottomPaneHeight]-kRAButtonHeight-5, kRAButtonWidth, kRAButtonHeight)];
        _radarLocationView.delegate = self;
        [self.view insertSubview:_radarLocationView belowSubview:self.contentView];
    }
    return _radarLocationView;
}

#pragma mark - 禁止横屏
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationPortrait;
}

#pragma mark - UI Setup
- (void)setupBackButton {
    if (!self.presentingViewController && (self.navigationController && !self.navigationController.navigationBarHidden)) {
        return;
    }
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    NSString *title = (self.presentingViewController || self.presentationController) ? @"关闭" : @"返回";
    [self.backButton setTitle:title forState:UIControlStateNormal];
    
    // 设置按钮样式
    [self.backButton setTitleColor:[UIColor systemBlueColor] forState:UIControlStateNormal];
    self.backButton.layer.cornerRadius = 20;
    self.backButton.titleLabel.font = [UIFont boldSystemFontOfSize:ADAPTOR_VALUE_750(32)];
    
    CGFloat statusBarHeight = [[UIApplication sharedApplication] statusBarFrame].size.height;
    self.backButton.frame = CGRectMake(15, statusBarHeight, 60, 40);
    
    [self.backButton addTarget:self action:@selector(backButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.backButton];
}

- (void)backButtonClicked {
    [self closeViewController];
}

@end
