//
//  ASearchAddressController.m
//  ANavDemo
//
//  Created by admin on 2026/2/6.
//

#import "ASearchAddressController.h"
#import "AMapNavSDKManager.h"

#import <AMapFoundationKit/AMapFoundationKit.h>

#import "AMapNavCommonUtil.h"

@interface ASearchAddressController ()<UITextFieldDelegate , AMapSearchDelegate,UITableViewDelegate , UITableViewDataSource>

@property (nonatomic , strong) UITableView *tableView;
@property (nonatomic , strong) UIBarButtonItem *rightItem;
@property (nonatomic ,strong)UIButton * backBtn;

@property (nonatomic , strong) NSMutableArray *dataArr;

@property (nonatomic, strong) UITextField *inputAddressTf;
@property (nonatomic, strong) AMapSearchAPI *search;
@property (nonatomic,assign)NSInteger currPage;

@end

@implementation ASearchAddressController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"选择地点";
    self.currPage = 1;
    _dataArr = [NSMutableArray array];
    
    
    [self initSubview];
    
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    
#ifdef kAMapSDKDebugFlag
    self.inputAddressTf.text = @"人民广场";
#endif
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.inputAddressTf becomeFirstResponder];
    });
   
}

-(void)initSubview {
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.backBtn];
    
    UITextField * inputAddressTf = [[UITextField alloc] init];
    inputAddressTf.borderStyle = UITextBorderStyleRoundedRect;
    inputAddressTf.placeholder = @"输入地址";
    inputAddressTf.returnKeyType = UIReturnKeySearch;
    inputAddressTf.tag = 100;
    inputAddressTf.delegate = self;
    
    [self.view addSubview:inputAddressTf];
    
    [inputAddressTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view).offset(10);
        make.right.mas_equalTo(self.view).offset(-10);
        make.top.mas_equalTo(self.view).offset(kRoutePlanBarHeight + 10);
        make.height.mas_equalTo(@35);
    }];
    
    self.inputAddressTf = inputAddressTf;
    
    
    
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:@"当前位置" forState:UIControlStateNormal];
    btn.backgroundColor = [UIColor whiteColor];
    btn.layer.borderColor = [UIColor blueColor].CGColor;
    btn.layer.borderWidth = 1;
    btn.layer.cornerRadius = 5;
    btn.titleLabel.font = [UIFont systemFontOfSize:12];
    btn.hidden = YES;
    
    [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(searchBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
       make.left.equalTo(inputAddressTf.mas_right).offset(12);
        make.top.mas_equalTo(inputAddressTf);
        make.right.mas_equalTo(self.view).offset(-10);
        make.height.mas_equalTo(@30);
        make.width.mas_equalTo(70);
    }];
   
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(inputAddressTf.mas_bottom).offset(5);
        make.left.equalTo(self.view);
        make.bottom.equalTo(self.view);
        make.centerX.equalTo(self.view);
        
    }];
    
    [self.tableView reloadData];
}

#pragma mark -
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    AMapPOI * m = self.dataArr[indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@" , m.name ];
    
    return cell;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    AMapPOI * m = self.dataArr[indexPath.row];
    
    if (self.selectAddressBlk) {
        self.selectAddressBlk(m);
    }
    
    [self backBtnAction];
//    [self.navigationController popViewControllerAnimated:YES];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == self.dataArr.count - 1 && (self.dataArr.count % 20 == 0)) {
        self.currPage = self.currPage + 1;
        [self requestAddressWithAddress:self.inputAddressTf.text atPage:self.currPage];
    }
    
}

#pragma mark -
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    
    return _tableView;
}

-(UIButton *)backBtn{
    if (!_backBtn) {
        _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _backBtn.frame = CGRectMake(0, 0, 40, 30);
        _backBtn.imageEdgeInsets = UIEdgeInsetsMake(2, -5, 2, 5);
        
//        _backBtn.backgroundColor = UIColor.redColor;
        [_backBtn setImage:[AMapNavCommonUtil imageWithName:@"icon_fanhui"] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(backBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backBtn;
}

-(void)backBtnAction {
    [self dismissViewControllerAnimated:YES completion:^{
            
    }];
    
}

#pragma mark - Action
-(void)searchBtnAction {
    AMapNavSDKManager * sdk  = [AMapNavSDKManager sharedManager];
    self.inputAddressTf.text = sdk.locationAddressDetail;
    
    [self startSearchWithAddress:self.inputAddressTf.text];
}

-(void)startSearchWithAddress:(NSString *)addr {
    if (!addr) {
        return;
    }
    
    [self requestAddressWithAddress:addr atPage:1];

}

-(void)requestAddressWithAddress:(NSString *)addr atPage:(NSInteger)page {
    AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
        
    request.keywords            = addr;
    
    AMapNavSDKManager * sdk  = [AMapNavSDKManager sharedManager];
//    request.city                = sdk.localCity;
    
    
//    request.types               = @"高等院校";
//    request.requireExtension    = YES;
    request.offset  =20;
    request.page = page;
    
    /*  搜索SDK 3.2.0 中新增加的功能，只搜索本城市的POI。*/
//    request.cityLimit           = YES;
//    request.requireSubPOIs      = YES;

    
    [self.search AMapPOIKeywordsSearch:request];
}

#pragma mark -
/* POI 搜索回调. */
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    NSArray * pois = response.pois;
    if (pois.count == 0)
    {
        return;
    }
    
    //解析response获取POI信息，具体解析见 Demo
    
    [self.dataArr addObjectsFromArray:pois];
    
    [self.tableView reloadData];
    
}



- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    [self.dataArr removeAllObjects];
    self.currPage = 1;
    
    [self startSearchWithAddress:textField.text];
    
    return YES;
}



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.inputAddressTf resignFirstResponder];
}
@end
