//
//  ChooseAddressController.m
//  Open
//
//  Created by weface on 2023/8/8.
//  Copyright © 2023 QXY. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "ChooseAddressController.h"
#import "CityNameCell.h"

@interface ChooseAddressController()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>
@property (nonatomic, strong)UITableView *tableView;
/*用来存放分组之后的城市数据*/
@property (nonatomic, strong)NSMutableDictionary *cityDic;
/*用来存放分组的城市数据A --- Z*/
@property (nonatomic, strong)NSMutableArray *GroupTempArray;
/*用来存放分组之后的省份数据*/
@property (nonatomic, strong)NSMutableDictionary *provinceDic;
/*用来存放分组的省份数据A --- Z*/
@property (nonatomic, strong)NSMutableArray *GroupProvinceArray;

@property(nonatomic,strong)UILabel *location;
@property(nonatomic,strong)UILabel *address;


@end


@implementation ChooseAddressController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    
}

-(void) viewDidLoad{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHex:0xFFFFFF];
    [self navConfig];
    [self loadCityData];
    [self topLocation];
    [self.view addSubview:self.tableView];
}

//加载本地数据
-(void)loadCityData{
    NSString *path=[[NSBundle mainBundle] pathForResource:@"city" ofType:@"txt"];
    NSString *jsonString=[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *array=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    _cityDic = [NSMutableDictionary dictionary];
    _provinceDic = [NSMutableDictionary dictionary];
    /*初始化一个数组，用来存放每个首字母的（key）的value*/
    NSMutableArray *arr=nil;
    NSMutableArray *pro=nil;
    for (int i=0; i<array.count; i++) {
        NSDictionary *model =array[i];
        NSString *cityfirst  = model[@"cityFirst"];
        NSString *cityName=model[@"cityName"];
        NSString *city_of_province=model[@"city_of_province"];
        if([[_cityDic allKeys] containsObject:cityfirst]){
            arr=[_cityDic objectForKey:cityfirst];
            [arr addObject:cityName];
            [_cityDic setObject:arr forKey:cityfirst];
        }else{
            arr= [[NSMutableArray alloc]initWithObjects:cityName, nil];
            [_cityDic setObject:arr forKey:cityfirst];
            }
        
        if([[_provinceDic allKeys] containsObject:cityfirst]){
            pro=[_provinceDic objectForKey:cityfirst];
            [pro addObject:city_of_province];
            [_provinceDic setObject:pro forKey:cityfirst];
        }else{
            pro= [[NSMutableArray alloc]initWithObjects:city_of_province, nil];
            [_provinceDic setObject:pro forKey:cityfirst];
            }
        
    }
    _GroupTempArray= [NSMutableArray arrayWithArray:[[_cityDic allKeys] sortedArrayUsingSelector:@selector(compare:)]];
    _GroupProvinceArray= [NSMutableArray arrayWithArray:[[_provinceDic allKeys] sortedArrayUsingSelector:@selector(compare:)]];
    NSLog(@"首字母:%@",@"done");
}

#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.GroupTempArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *Array = [self.cityDic objectForKey:self.GroupTempArray[section]];
    return Array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    CityNameCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CityNameCell"];
    NSArray *Array = [self.cityDic objectForKey:self.GroupTempArray[indexPath.section]];
    [cell.cityName setText:Array[indexPath.row]];
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *Array = [self.provinceDic objectForKey:self.GroupProvinceArray[indexPath.section]];
    NSString *province=Array[indexPath.row];
    NSArray *provinceArray = [self.cityDic objectForKey:self.GroupTempArray[indexPath.section]];
    NSString *city=provinceArray[indexPath.row];
    NSLog(@"省份:%@/城市:%@",province,city);
    [[NSUserDefaults standardUserDefaults]setObject:[NSString stringWithFormat:@"%@",province] forKey:@"chooseProvince"];
    [[NSUserDefaults standardUserDefaults]setObject:[NSString stringWithFormat:@"%@",city] forKey:@"chooseCity"];
    [self.delegate ChooseAddressBack:province :city];
    [self.navigationController popViewControllerAnimated:YES];
}

//快速索引
- (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView{
    return self.GroupTempArray;
}

- (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    return index;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight+50, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight ) style:UITableViewStyleGrouped];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
         //_tableView.separatorStyle =  UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
        _tableView.estimatedRowHeight = 50;
        [_tableView registerNib:[UINib nibWithNibName:@"CityNameCell" bundle:nil] forCellReuseIdentifier:@"CityNameCell"];
        
    }
    return _tableView;
}
- (void)backClick{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void) topLocation{
   
    
}
- (void)navConfig{
    UIView*nav = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
     nav.backgroundColor = [UIColor colorWithHex:0x086ed7];
     [self.view addSubview:nav];
     
     UIButton*backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
     [backBtn setTitle:@"返回" forState:UIControlStateNormal];
     [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
     [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
     [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
     [backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
     [nav addSubview:backBtn];
     
     [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
         make.left.offset(0);
         make.top.offset(cl_kStatusBarHeight);
         make.width.offset(80);
         make.height.offset(44);
     }];
     
    UILabel*titleLabel = [[UILabel alloc]init];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = @"地区选择";
    titleLabel.font = [UIFont boldSystemFontOfSize:17];
    [nav addSubview:titleLabel];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.offset(cl_kStatusBarHeight);
        make.width.offset(80);
        make.height.offset(44);
    }];
    
    UIView*topAddress = [[UIView alloc]initWithFrame:CGRectMake(0, nav.height, ScreenWidth, 50)];
    //topAddress.backgroundColor = [UIColor colorWithHex:0x086ed7];
     [self.view addSubview:topAddress];
    
    _address = [[UILabel alloc]init];
    _address.textColor = [UIColor darkGrayColor];
    _address.textAlignment = NSTextAlignmentLeft;
    _address.text = @"位置:北京市";
    _address.font = [UIFont systemFontOfSize:16];
    _address.userInteractionEnabled=YES;
    UITapGestureRecognizer *addresslocation = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addresslocation:)];
    [_address addGestureRecognizer:addresslocation];
    [topAddress addSubview:_address];
    [_address mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(10);
        make.top.offset(5);
        make.width.offset(120);
        make.height.offset(44);
    }];
    
    _location = [[UILabel alloc]init];
    _location.textColor = [UIColor darkGrayColor];
    _location.textAlignment = NSTextAlignmentRight;
    _location.text = @"重新定位";
    _location.userInteractionEnabled=YES;
    _location.font = [UIFont systemFontOfSize:16];
    UITapGestureRecognizer *textLocation = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textlocation:)];
    [_location addGestureRecognizer:textLocation];
    [topAddress addSubview:_location];
    [_location mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-10);
        make.top.offset(5);
        make.width.offset(80);
        make.height.offset(44);
    }];
    
    UIImageView *image=[[UIImageView alloc] init];
    image.image=[UIImage imageNamed:@"home_location"];
    [topAddress addSubview:image];
    [image mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_location.mas_left).offset(10);
        make.top.offset(17);
    }];
    
    NSString *chooseCity=[[NSUserDefaults standardUserDefaults]objectForKey:@"chooseCity"];
    if(chooseCity!=nil){
        _address.text=[NSString stringWithFormat:@"位置:%@",chooseCity];
    }else{
        NSString *locationCity=[[NSUserDefaults standardUserDefaults]objectForKey:@"locationCity"];
        _address.text=[NSString stringWithFormat:@"位置:%@",locationCity];
    }
    
}

-(void)textlocation:(UITapGestureRecognizer *)tap{
    NSString *locationCity=[[NSUserDefaults standardUserDefaults]objectForKey:@"locationCity"];
    NSString *locationProvince=[[NSUserDefaults standardUserDefaults]objectForKey:@"locationProvince"];
    if(locationCity!=nil){
        self.address.text=[NSString stringWithFormat:@"位置:%@",locationCity];;
    }
    [self.delegate ChooseAddressBack:locationProvince :locationCity];
    
    //重新定位后,选择的为ip定位
    [[NSUserDefaults standardUserDefaults]setObject:locationProvince forKey:@"chooseProvince"];
    [[NSUserDefaults standardUserDefaults]setObject:locationCity forKey:@"chooseCity"];
    [self.navigationController popViewControllerAnimated:YES];
    
}
-(void)addresslocation:(UITapGestureRecognizer *)tap{
    NSString *locationCity=[[NSUserDefaults standardUserDefaults]objectForKey:@"locationCity"];
    NSString *locationProvince=[[NSUserDefaults standardUserDefaults]objectForKey:@"locationProvince"];
    
    [[NSUserDefaults standardUserDefaults]setObject:locationProvince forKey:@"chooseProvince"];
    [[NSUserDefaults standardUserDefaults]setObject:locationCity forKey:@"chooseCity"];
    
    [self.navigationController popViewControllerAnimated:YES];
}

@end

