//
//  BCAMapPoiSearchViewController.m
//  ChatAgentApp
//
//  Created by caoshiqian on 2025/5/12.
//

#import "BCAMapPoiSearchViewController.h"
#import <BaiduMapAPI_Base/BMKBaseComponent.h>
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>
#import "MapCommonDefine.h"

@implementation BCAPoiAnnotation
@end

@interface BCAMapPoiSearchViewController ()<BMKMapViewDelegate>

@property (nonatomic, strong) BMKMapView *mapView;
@property (nonatomic, strong) UILabel *addressLabel;
@property (nonatomic, strong) UIButton *backButton;

@end

@implementation BCAMapPoiSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"地点检索";
    [self.view addSubview:self.mapView];
    [self.view addSubview:self.addressLabel];
    
    [self setupBackButton];
    
    [self showPoiSearchResult:self.poiResult];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:NO];
    // 当mapView即将被显示的时候调用，恢复之前存储的mapView状态
    [_mapView viewWillAppear];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:NO];
    // 当mapView即将被隐藏的时候调用，存储当前mapView的状态
    [_mapView viewWillDisappear];
}

- (void)showPoiSearchResult:(BMKPOISearchResult *)poiResult {
    
    NSMutableArray<BCAPoiAnnotation *> *annotions = [NSMutableArray array];
    for (int i = 0; i < poiResult.poiInfoList.count; i++) {
        BMKPoiInfo *info = poiResult.poiInfoList[i];
        BCAPoiAnnotation *annotaion = [[BCAPoiAnnotation alloc] init];
        annotaion.coordinate = info.pt;
        annotaion.title = info.name;
        annotaion.index = i;
        [annotions addObject:annotaion];
    }
    
    // 添加标注
    [_mapView addAnnotations:annotions];
    // 标注适配屏幕
    [self showAnnotations:annotions animated:YES];
}

/// 标注适配屏幕
- (void)showAnnotations:(NSArray *)annotations animated:(BOOL)animated {
    if (!annotations || annotations.count == 0) {
        return;
    }
    //只有一个则直接设置地图中心为annotation的位置
    if (annotations.count == 1) {
        id<BMKAnnotation> annotation = [annotations firstObject];
        [_mapView setCenterCoordinate:annotation.coordinate animated:animated];
        return;
    }
    
    double left = DBL_MAX;
    double right = DBL_MIN;
    double top = DBL_MAX;
    double bottom = DBL_MIN;
    for (id <BMKAnnotation> annotation in annotations) {
        // 如果是固定在屏幕上的，则不进行计算，会影响展示效果。
        if ([annotation isKindOfClass:[BMKPointAnnotation class]] && ((BMKPointAnnotation *)annotation).isLockedToScreen) {
            continue;
        }
        BMKMapPoint point = BMKMapPointForCoordinate(annotation.coordinate);
        left = fmin(left, point.x);
        right = fmax(right, point.x);
        top = fmin(top, point.y);
        bottom = fmax(bottom, point.y);
    }

    double x = left;
    double y = top;
    double width = right - left;
    double height = bottom - top;
    if (width > 0 && height > 0) {
        BMKMapRect newRect = BMKMapRectMake(x, y, width, height);
        if (newRect.size.width == 0) {
            newRect.size.width = 1;
        }
        if (newRect.size.height == 0) {
            newRect.size.height = 1;
        }
        CGFloat scale = ADAPTOR_VALUE_750(90);
        UIEdgeInsets padding = UIEdgeInsetsMake(self.mapView.mapPadding.top + scale, self.mapView.mapPadding.left + scale,
                                                self.mapView.mapPadding.bottom + scale, self.mapView.mapPadding.right + scale);
        [self.mapView fitVisibleMapRect:newRect edgePadding:padding withAnimated:YES];
    }
}

- (void)configAddressLabel:(NSString *)name address:(NSString *)address {
    NSMutableAttributedString *poi = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@", name, address]];
    NSRange nRange = NSMakeRange(0, [name length]);
    NSRange aRange = NSMakeRange([name length], [address length] + 1);
    [poi addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"PingFangSC-Semibold" size:24] range:nRange];
    [poi addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"PingFangSC-Regular" size:16] range:aRange];
    // 底部label展示poi信息
    _addressLabel.attributedText = poi;
    _addressLabel.hidden = NO;
}

#pragma mark - BMKMapViewDelegate

/// 根据anntation生成对应的annotationView
/// @param mapView 地图View
/// @param annotation 指定的标注
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation {
    if ([annotation isMemberOfClass:[BMKPointAnnotation class]]) {
        BMKPinAnnotationView *annotationView = (BMKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"com.Baidu.BMKPointAnnotation"];
        if (!annotationView) {
            annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"com.Baidu.BMKPointAnnotation"];
            annotationView.image = [UIImage imageNamed:@"icon_marker"];
        }
        return annotationView;
    } else if ([annotation isMemberOfClass:[BCAPoiAnnotation class]]) {
        BMKPinAnnotationView *annotationView = (BMKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"com.Baidu.BMKPoiAnnotation"];
        if (!annotationView) {
            annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"com.Baidu.BMKPoiAnnotation"];
        }
        annotationView.pinColor = BMKPinAnnotationColorRed;
        return annotationView;
    }
    return nil;
}

- (void)mapView:(BMKMapView *)mapView didAddAnnotationViews:(NSArray *)views {
    for (id view in views) {
        if ([view isKindOfClass:[BMKPinAnnotationView class]]) {
            BMKPinAnnotationView *annotionView = (BMKPinAnnotationView *)view;
            BCAPoiAnnotation *annotion = (BCAPoiAnnotation *)annotionView.annotation;
            if ([annotion respondsToSelector:@selector(index)] && annotion.index == 0) {
                annotionView.selected = YES;
            }
        }
    }
}

- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view {
    BMKPinAnnotationView *selView = (BMKPinAnnotationView *)view;
    selView.pinColor = BMKPinAnnotationColorGreen;
    BCAPoiAnnotation *annotion = (BCAPoiAnnotation *)selView.annotation;
    BMKPoiInfo *info = self.poiResult.poiInfoList[annotion.index];
    NSString *name = info.name ? info.name : @"";
    NSString *address = info.address ? info.address : @"";
    [self configAddressLabel:name address:address];
    [mapView mapForceRefresh];
}

- (void)mapView:(BMKMapView *)mapView didDeselectAnnotationView:(BMKAnnotationView *)view {
    BMKPinAnnotationView *selView = (BMKPinAnnotationView *)view;
    selView.pinColor = BMKPinAnnotationColorRed;
    [mapView mapForceRefresh];
}

#pragma mark - UI

- (BMKMapView *)mapView {
    if (!_mapView) {
        _mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds))];
        _mapView.delegate = self;
        _mapView.zoomLevel = 16;
        _mapView.trafficEnabled = YES;
    }
    return _mapView;
}

- (UILabel *)addressLabel {
    if (!_addressLabel) {
        _addressLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, CGRectGetMaxY(_mapView.frame) - 80 - 15 - 25, PHONE_SIZE.width - 10 * 2, 80)];
        _addressLabel.textAlignment = NSTextAlignmentCenter;
        _addressLabel.numberOfLines = 0;
        _addressLabel.backgroundColor = [UIColor whiteColor];
        _addressLabel.textColor = [UIColor colorWithRed:51.f / 255.f green:51.f / 255.f blue:51.f / 255.f alpha:1.f];
        _addressLabel.layer.cornerRadius = 5;
        _addressLabel.layer.masksToBounds = YES;
        _addressLabel.hidden = YES;
    }
    return _addressLabel;
}

- (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];
}

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

@end
