//
//  RNLocation.m
//  RNPhotosPicker
//
//  Created by SmartFun on 2018/7/25.
//  Copyright © 2018年 SmartFun. All rights reserved.
//

#import "RNLocation.h"
#import "AMapFoundationKit.h"
#import "AMapLocationKit.h"
#define kSCREEN_WIDTH          ([UIScreen mainScreen].bounds.size.width)
#define kSCREEN_HEIGHT         ([UIScreen mainScreen].bounds.size.height)
#define iPhoneX     (kSCREEN_WIDTH == 375.f && kSCREEN_HEIGHT == 812.f)

@interface RNLocation ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *head;
@property (nonatomic, strong) UIView *locationView;
@property (nonatomic, strong) NSMutableArray *titleArray;
@property (nonatomic, strong) NSMutableArray *data;
@property (nonatomic, strong) NSMutableArray *cityArray;
@property (nonatomic, strong) AMapLocationManager         *locationManager;
@property (nonatomic, strong) UILabel *positionLab;
@end

@implementation RNLocation

-(void)getLocations{
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyThreeKilometers];
    self.locationManager.locationTimeout = 5;
    self.locationManager.reGeocodeTimeout = 5;
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            if (error.code == AMapLocationErrorLocateFailed)
            {
                return;
            }
        }
        if (regeocode)
        {
            NSMutableDictionary *resultDic = [NSMutableDictionary dictionary];
            NSLog(@"-----------reGeocode:%@", regeocode);
            resultDic[@"latitude"] = @(location.coordinate.latitude);
            resultDic[@"longitude"] = @(location.coordinate.longitude);
            resultDic[@"cityCode"] = regeocode.citycode;
            resultDic[@"city"] = regeocode.city;
            self.positionLab.text = resultDic[@"city"];
        }
    }];
}

- (AMapLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [[AMapLocationManager alloc] init];
        _locationManager.delegate = self;
    }
    return _locationManager;
}

- (NSMutableArray *)cityArray{
    if (!_cityArray) {
        _cityArray = [NSMutableArray array];
    }
    return _cityArray;
}

- (NSMutableArray *)titleArray{
    if (!_titleArray) {
        _titleArray = [NSMutableArray array];
    }
    return _titleArray;
}

- (NSMutableArray *)data{
    if (!_data) {
        _data = [NSMutableArray array];
    }
    return _data;
}

- (void)getJsonData{
    NSData *jsonData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"prov-city" ofType:@"json"]];
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:nil];
    self.data = jsonObject;
    for (int i = 0; i < self.data.count; i++) {
        NSDictionary *obj = self.data[i];
        NSString *title = [obj[@"pinyin"] substringToIndex:1];
        [self.titleArray addObject:title];
    }
    NSSet *set = [NSSet setWithArray:self.titleArray];
    self.titleArray = [[set allObjects] mutableCopy];
    for (int i = 0; i < self.titleArray.count; i++) {
        NSMutableArray *temp = [NSMutableArray array];
        for (int j = 0; j < self.data.count; j++) {
            NSString *t = [self.data[j][@"pinyin"] substringToIndex:1];
            if ([self.titleArray[i] isEqualToString:t]) {
                [temp addObject:self.data[j]];
            }
        }
        [self.cityArray addObject:temp];
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.head];
    [self.view addSubview:self.tableView];
    [self getJsonData];
    
    
    
    CGFloat height = iPhoneX ? 88 : 64;
    self.head.frame = CGRectMake(0, 0, kSCREEN_WIDTH, height);
    self.tableView.frame = CGRectMake(0, height, kSCREEN_WIDTH, kSCREEN_HEIGHT - height);
    
    UIButton *cancel = [[UIButton alloc] initWithFrame:CGRectMake(0, height - 44, 44, 44)];
    [cancel setImage: [UIImage imageNamed:@"cancel"] forState:UIControlStateNormal];
    [cancel addTarget:self action:@selector(clickCancel:) forControlEvents:UIControlEventTouchUpInside];
    [self.head addSubview:cancel];
    
    UIView *txBack = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
    txBack.center = CGPointMake((kSCREEN_WIDTH - 44) * 0.5 + 44, height - 44 + 22);
    txBack.layer.cornerRadius = 15;
    CGFloat color = 243/256.0;
    txBack.backgroundColor = [UIColor colorWithRed:color green:color blue:color alpha:1];
    
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(15, 2, 200-25, 26)];
    textField.placeholder = @"输入城市名称查询";
    textField.font = [UIFont systemFontOfSize:14];
    [txBack addSubview:textField];
    [self.head addSubview:txBack];
 
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
    [btn addTarget:self action:@selector(clickLocation) forControlEvents:UIControlEventTouchUpInside];
    
    self.tableView.tableHeaderView = self.locationView;
    self.locationView.frame = CGRectMake(0, 0, kSCREEN_WIDTH, 50);
    UIImageView *loImg = [[UIImageView alloc] initWithFrame:CGRectMake(10, 25 * 0.5, 25, 25)];
    loImg.image = [UIImage imageNamed:@"ic_location"];
    [self.locationView addSubview:loImg];
    
    self.positionLab = [[UILabel alloc] initWithFrame:CGRectMake(38, 15, 80, 20)];
    self.positionLab.text  = @"";
    [self.locationView addSubview:self.positionLab];
    
    [self getLocations];
    
    UILabel *detail = [[UILabel alloc] initWithFrame:CGRectMake(118, 15, 100, 20)];
    detail.text = @"GPS定位";
    detail.textColor = [UIColor colorWithRed:169/256.0 green:169/256.0 blue:169/256.0 alpha:1];
    detail.font = [UIFont systemFontOfSize:12];
    [self.locationView addSubview:detail];
    [self.locationView addSubview:btn];
}

- (void)clickLocation{
    self.callback(@[[NSNull null], self.positionLab.text]);
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.cityArray[section] count];
}

-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return  self.titleArray;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return  self.titleArray[section];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identify = @"cell";
    RNLocationCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    if (!cell) {
        cell = [[RNLocationCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify];
    }
    NSMutableArray *t = self.cityArray[indexPath.section];
    NSString *str = t[indexPath.row][@"name"];
    cell.labal.text = str;
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, 30)];
    view.backgroundColor = [UIColor colorWithRed:244/256.0 green:244/256.0 blue:244/256.0 alpha:1];
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 200, 20)];
    lab.text = self.titleArray[section];
    lab.font = [UIFont systemFontOfSize:14];
    [view addSubview:lab];
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSMutableArray *t = self.cityArray[indexPath.section];
    NSString *str = t[indexPath.row][@"name"];
    NSString *zip = t[indexPath.row][@"zip"];
    self.callback(@[[NSNull null], str, zip]);
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.titleArray.count;
}

- (void)clickCancel:(UIButton *)sender{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (UIView *)locationView{
    if (!_locationView){
        _locationView = [[UIView alloc] init];
    }
    return _locationView;
}

- (UIView *)head{
    if (!_head) {
        _head = [UIView new];
        _head.backgroundColor = [UIColor whiteColor];
    }
    return _head;
}

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

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
