//
//  BCAMapNavigateDriveModel.m
//  ChatAgentApp
//
//  Created by caoshiqian on 2025/4/21.
//

#import "BCAMapNavigateDriveModel.h"
#import "BCALocationManager.h"
#import "BCAPoiSearchTask.h"
#import "BCAMapNaviDriveViewController.h"

#import <BaiduMapAPI_Base/BMKBaseComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>
#import "BNaviUtil.h"
#import "BCAMapNavigateCardView.h"

@interface BCAMapNavigateDriveModel ()<BMKPoiSearchDelegate, BNNaviRoutePlanDelegate>

@property (nonatomic, strong) BCAPoiSearchTask *searchTask;
@property (nonatomic, strong) NSMutableArray *searchResults;

@property (nonatomic, assign) BOOL isCurrentStart;

@property (nonatomic, strong) BCAMapNavigateCardView *cardView;

@end

@implementation BCAMapNavigateDriveModel

- (instancetype)initWithParams:(NSDictionary *)params {
    if (self = [super initWithParams:params]) {
        [self.locationManager requestLocationPermission];
        [self startLocating];
    }
    return self;
}

- (BCAMapNavigateType)type {
    return BCAMapNavigateTypeDrive;
}

- (void)startRoutePlan {
    // 终点信息缺失
    if (self.endPositions.count == 0) {
        [self callbackFinishWithCode:BCAMapNavigateErrorNoEndPosition message:@"没有终点"];
        return;
    }
    
    // 需要 city 信息来查询位置
    BCALocation *currentLocation = self.locationManager.currentLocation;
    if (!currentLocation) {
        NSLog(@"[map] 等待当前位置更新");
        return;
    }
    
    // 先查询位置坐标，所有位置信息查询完后发起路线规划
    [self searchNaviPositionsPoi];
}

- (void)enterNaviPage {
    BCAMapNaviDriveViewController *naviVC = [[BCAMapNaviDriveViewController alloc] init];
    naviVC.naviType = self.naviType;
    [self naviToVC:naviVC];
}

- (void)startNavigation {
    
}

- (UIView *)routePlanPreviewView {
    if (!self.cardView) {
        BNCarRouteModel *model = [BNaviService_DriveRoute getCurrentCarRouteData];
        NSLog(@"[map] routePlan model, count: %ld", model.carRoutes.count);
        for (BNCarOneRouteModel *route in model.carRoutes) {
            NSLog(@"[map] route %@,%ld(米),%ld秒,%ld个红绿灯", route.routeLabelName, route.distance, route.time, route.lightNum);
        }
        self.cardView = [[BCAMapNavigateCardView alloc] initWithFrame:CGRectZero];
        [self.cardView updateWithCarRoute:model];
        
        // 简易交互
        UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapCardView:)];
        [self.cardView addGestureRecognizer:tapGR];
    }
    return self.cardView;
}

#pragma mark - POI Search

- (void)searchNaviPositionsPoi {
    NSMutableArray *locations = [NSMutableArray array];
    if (self.startPosition) {
        [locations addObject:self.startPosition];
    }
    [locations addObjectsFromArray:self.endPositions];
    [self startPoiSearchTaskWithLocations:locations];
}

- (void)startPoiSearchTaskWithLocations:(NSArray *)locations {
    if (!self.locationManager.currentLocation) {
        return;
    }
    
    __weak typeof(self) weakSelf = self;
    self.searchTask = [[BCAPoiSearchTask alloc] initWithLocations:locations
                                                  currentLocation:self.locationManager.currentLocation
                                                       completion:^(NSArray<BCALocation *> *results, NSError * _Nullable error) {
        
        __strong typeof(self) strongSelf = weakSelf;
        if (error) {
            if (error.code == BCAPoiSearchErrorCallFail) {
                [strongSelf callbackFinishWithCode:BCAMapNavigateErrorPoiCallFail message:@"位置搜索调用失败"];
            } else {
                NSLog(@"[map] search err: %@", @(strongSelf.searchTask.searchErrorCode));
                [strongSelf callbackFinishWithCode:BCAMapNavigateErrorPoiSearchFail message:@"没有搜索到目的地"];
            }
            return;
        }
        strongSelf.searchResults = [results copy];
        [strongSelf startRoutePlanPrivate];
    }];
    
    [self.searchTask start];
}

#pragma mark - RoutePlan

- (void)startRoutePlanPrivate {
    NSMutableArray<BNRoutePlanNode *> *nodes = [NSMutableArray array];
    
    for (BCALocation *location in self.searchResults) {
        BNRoutePlanNode *node = [BNRoutePlanNode new];
        node.title = location.name;
        node.cityID = location.city;
        node.pos = [BNPosition positionFromCoordinate:location.coordinate];
        node.pos.eType = (BNCoordinate_Type)location.coordinateType;
        [nodes addObject:node];
        NSLog(@"[map] location: %@,%@,%@,(%@,%@)", location.name, location.city, location.detailAddress,
              @(location.coordinate.longitude), @(location.coordinate.latitude));
    }
    
    [BNaviService_RoutePlan startNaviRoutePlan:BNRoutePlanMode_Recommend naviNodes:nodes time:nil delegete:self userInfo:@{
        BNaviTripTypeKey: @(self.naviType)
    }];
}

#pragma mark - RoutePlan (BNNaviRoutePlanDelegate)

- (void)routePlanDidFinished:(NSDictionary *)userInfo {
    NSLog(@"[map] routePlan: %@", userInfo);
    [self callbackRoutePlanDidFinished:userInfo];
    // 这里可直接进入规划导航页面，或者等待外部调用
}

- (void)routePlanDidFailedWithError:(NSError *)error andUserInfo:(NSDictionary *)userInfo {
    [self callbackFinishWithCode:BCAMapNavigateErrorRoutePlanFail error:error];
}

#pragma mark - Location

- (void)locationManagerDidUpdateLocation:(BCALocation *)location {
    [super locationManagerDidUpdateLocation:location];
    location.coordinate = BMKCoordTrans(location.coordinate, BMK_COORDTYPE_GPS, BMK_COORDTYPE_BD09LL);
    
    if (self.startPosition) {
        self.startPosition.province = location.province;
        self.startPosition.city     = location.city;
        self.startPosition.district = location.district;
        self.startPosition.detailAddress = location.detailAddress;
        self.startPosition.coordinateType = location.coordinateType;
    }
    
    // 只搜索一次
    if (self.searchResults.count == 0) {
        [self searchNaviPositionsPoi];
    }
}

- (void)locationManagerDidFailWithError:(NSError *)error {
    [super locationManagerDidFailWithError:error];
    [self callbackFinishWithCode:BCAMapNavigateErrorNoLocationAuth message:@"请打开定位权限"];
}

#pragma mark - View

- (UIViewController *)chatViewController {
    UIViewController *vc = [self.delegate mapNavigateModelGetChatViewController:self];
    if (vc.navigationController) {
        return vc.navigationController;
    }
    return vc;
}

- (void)naviToVC:(UIViewController *)vc {
    UIViewController *baseVC = [self chatViewController];
    if ([baseVC isKindOfClass:[UINavigationController class]]) {
        [((UINavigationController *)baseVC) pushViewController:vc animated:YES];
    } else {
        vc.modalPresentationStyle = UIModalPresentationFullScreen;
        [baseVC presentViewController:vc animated:YES completion:^{
                    
        }];
    }
}

- (void)tapCardView:(UITapGestureRecognizer *)gr {
    [self enterNaviPage];
}

@end
