//
//  SelectLocationView.m
//  Open
//
//  Created by 雷俊博 on 2019/12/13.
//  Copyright © 2019 黄江涛 . All rights reserved.
//

#import "SelectLocationView.h"
#import "AddressItemView.h"
#import "UIView+frameAdjust.h"
#import "PayCityModel.h"
#import "AddressTableViewCell.h"

@interface SelectLocationView ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>
{
    PayCityModel*selectedModel;
}

@property (nonatomic,weak) AddressItemView * topTabbar;
@property (nonatomic,weak) UIScrollView * contentView;

@property (nonatomic,weak) UIView * underLine;
@property (nonatomic, strong)NSArray *allData;
@property (nonatomic,strong) NSMutableArray * dataSouce;
@property (nonatomic,strong) NSMutableArray * cityDataSouce;

@property (nonatomic,strong) NSMutableArray * topTabbarItems;
@property (nonatomic,strong) NSMutableArray * tableViews;
@property (nonatomic,weak) UIButton * selectedBtn;

@end

@implementation SelectLocationView
#pragma mark - lifecycle
- (instancetype)initWithProvinceArray:(NSArray *)dataArray
{
    self = [super init];
    if (self) {
        self.allData = dataArray;
        [self initUI];
        [self setUp];
    }
    return self;
}

- (void)dealloc
{
    NSLog(@"地址选择工具销毁了");
}



#pragma mark - setUp UI
- (void)setUp
{
    AddressItemView * topTabbar = [[AddressItemView alloc]initWithFrame:CGRectMake(0,0, self.alertView.bounds.size.width, kTopViewHeight)];
    [self.topView addSubview:topTabbar];
    _topTabbar = topTabbar;
    [self addTopBarItem];
    [_topTabbar layoutIfNeeded];
    
    UIView * underLine = [[UIView alloc] initWithFrame:CGRectZero];
    [topTabbar.scrollView addSubview:underLine];
    _underLine = underLine;
    underLine.height = 1.0f;
    UIButton * btn = self.topTabbarItems.lastObject;
    [self changeUnderLineFrame:btn];
    underLine.minY = self.topTabbar.maxY - 1;
      
    _underLine.backgroundColor = [UIColor redColor];
    
    
    UIScrollView * contentView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.topView.frame), self.alertView.frame.size.width, self.alertView.height - kTopViewHeight)];
    contentView.contentSize = CGSizeMake(self.alertView.bounds.size.width, 0);
    [self.alertView addSubview:contentView];
    _contentView = contentView;
    _contentView.pagingEnabled = YES;
    _contentView.backgroundColor = [UIColor whiteColor];
    [self addTableView];
    _contentView.delegate = self;
}


- (void)addTableView{

    UITableView * tabbleView = [[UITableView alloc]initWithFrame:CGRectMake(self.tableViews.count * ScreenWidth, 0, ScreenWidth, _contentView.height)];
    [_contentView addSubview:tabbleView];
    [self.tableViews addObject:tabbleView];
    tabbleView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tabbleView.delegate = self;
    tabbleView.dataSource = self;
    tabbleView.contentInset = UIEdgeInsetsMake(0, 0, 44, 0);
    [tabbleView registerNib:[UINib nibWithNibName:@"AddressTableViewCell" bundle:nil] forCellReuseIdentifier:@"AddressTableViewCell"];
}



- (void)addTopBarItem{
    
    UIButton * topBarItem = [UIButton buttonWithType:UIButtonTypeCustom];
    [topBarItem setTitle:@"请选择" forState:UIControlStateNormal];
    [topBarItem setTitleColor:[UIColor colorWithRed:43/255.0 green:43/255.0 blue:43/255.0 alpha:1] forState:UIControlStateNormal];
    [topBarItem setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
    [topBarItem sizeToFit];
     topBarItem.centerY = _topTabbar.height * 0.5;
    [self.topTabbarItems addObject:topBarItem];
    [_topTabbar.scrollView addSubview:topBarItem];
    [topBarItem addTarget:self action:@selector(topBarItemClick:) forControlEvents:UIControlEventTouchUpInside];
}

//调整指示条位置
- (void)changeUnderLineFrame:(UIButton  *)btn{
    
    _selectedBtn.selected = NO;
    btn.selected = YES;
    _selectedBtn = btn;
    _underLine.x = btn.x;
    _underLine.width = btn.width;
}
//完成地址选择,执行chooseFinish代码块
- (void)setUpAddress:(PayCityModel *)model{

    NSInteger index = self.contentView.contentOffset.x / ScreenWidth;
    UIButton * btn = self.topTabbarItems[index];
    [btn setTitle:model.name forState:UIControlStateNormal];
    [btn sizeToFit];
    [_topTabbar layoutIfNeeded];
    [self changeUnderLineFrame:btn];
    NSMutableString * addressStr = [[NSMutableString alloc] init];
    for (UIButton * btn  in self.topTabbarItems) {
        if ([btn.currentTitle isEqualToString:@"县"] || [btn.currentTitle isEqualToString:@"市辖区"] ) {
            continue;
        }
        [addressStr appendString:btn.currentTitle];
        [addressStr appendString:@" "];
    }
    //self.address = addressStr;
    if (model.isCity == YES) {
        selectedModel = model;
    }
    [self dismissWithAnimation:YES];
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//       // self.hidden = YES;
//
////        if (self.chooseFinish) {
////            self.chooseFinish();
////        }
//    });
}

//当重新选择省或者市的时候，需要将下级视图移除。
- (void)removeLastItem{

    [self.tableViews.lastObject performSelector:@selector(removeFromSuperview) withObject:nil withObject:nil];
    [self.tableViews removeLastObject];
    
    [self.topTabbarItems.lastObject performSelector:@selector(removeFromSuperview) withObject:nil withObject:nil];
    [self.topTabbarItems removeLastObject];
}

//滚动到下级界面,并重新设置顶部按钮条上对应按钮的title
- (void)scrollToNextItem:(NSString *)preTitle{
    [_topTabbar setNeedsLayout];
    NSInteger index = self.contentView.contentOffset.x / ScreenWidth;
    UIButton * btn = self.topTabbarItems[index];
    [btn setTitle:preTitle forState:UIControlStateNormal];
    [btn sizeToFit];
    [_topTabbar layoutIfNeeded];
    [UIView animateWithDuration:0.25 animations:^{
        self.contentView.contentSize = (CGSize){self.tableViews.count * ScreenWidth,0};
        CGPoint offset = self.contentView.contentOffset;
        self.contentView.contentOffset = CGPointMake(offset.x + ScreenWidth, offset.y);
        
        [self changeUnderLineFrame: [self.topTabbar.scrollView.subviews lastObject]];
    }];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if(scrollView != self.contentView) return;
    __weak typeof(self)weakSelf = self;
    [UIView animateWithDuration:0.25 animations:^{
        NSInteger index = scrollView.contentOffset.x / ScreenWidth;
        UIButton * btn = weakSelf.topTabbarItems[index];
        [weakSelf changeUnderLineFrame:btn];
    }];
}


#pragma mark - TableViewDatasouce

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if([self.tableViews indexOfObject:tableView] == 0){
        return self.dataSouce.count;
    }else if ([self.tableViews indexOfObject:tableView] == 1){
        return self.cityDataSouce.count;
    }
    return self.dataSouce.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    AddressTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"AddressTableViewCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    PayCityModel * item;
    //省级别
    if([self.tableViews indexOfObject:tableView] == 0){
        item = self.dataSouce[indexPath.row];
    //市级别
    }else if ([self.tableViews indexOfObject:tableView] == 1){
        item = self.cityDataSouce[indexPath.row];
    }
    cell.model = item;
    return cell;
}

#pragma mark - TableViewDelegate
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if([self.tableViews indexOfObject:tableView] == 0){
        

        //1.1 获取下一级别的数据源(市级别,如果是直辖市时,下级则为区级别)
        PayCityModel * provinceItem = self.dataSouce[indexPath.row];
        self.cityDataSouce = [self getCityDataSourceWithModel:provinceItem];
        if(self.cityDataSouce.count == 0){
            for (int i = 0; i < self.tableViews.count && self.tableViews.count != 1; i++) {
                [self removeLastItem];
            }
            [self setUpAddress:provinceItem];
            return indexPath;
        }
        //1.1 判断是否是第一次选择,不是,则重新选择省,切换省.
        NSIndexPath * indexPath0 = [tableView indexPathForSelectedRow];

        if ([indexPath0 compare:indexPath] != NSOrderedSame && indexPath0) {
            
            for (int i = 0; i < self.tableViews.count && self.tableViews.count != 1; i++) {
                [self removeLastItem];
            }
            [self addTopBarItem];
            [self addTableView];
            [self scrollToNextItem:provinceItem.name];
            return indexPath;
            
        }else if ([indexPath0 compare:indexPath] == NSOrderedSame && indexPath0){
            
            for (int i = 0; i < self.tableViews.count && self.tableViews.count != 1 ; i++) {
                [self removeLastItem];
            }
            [self addTopBarItem];
            [self addTableView];
            [self scrollToNextItem:provinceItem.name];
            return indexPath;
        }

        //之前未选中省，第一次选择省
        [self addTopBarItem];
        [self addTableView];
        [self scrollToNextItem:provinceItem.name ];
        
    }else if ([self.tableViews indexOfObject:tableView] == 1){
        
        PayCityModel * item = self.cityDataSouce[indexPath.row];
        [self setUpAddress:item];
    }
    return indexPath;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    PayCityModel * item;
    if([self.tableViews indexOfObject:tableView] == 0){
       item = self.dataSouce[indexPath.row];
    }else if ([self.tableViews indexOfObject:tableView] == 1){
       item = self.cityDataSouce[indexPath.row];
    }
    item.isSelected = YES;
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    PayCityModel * item;
    if([self.tableViews indexOfObject:tableView] == 0){
        item = self.dataSouce[indexPath.row];
    }else if ([self.tableViews indexOfObject:tableView] == 1){
        item = self.cityDataSouce[indexPath.row];
    }
    item.isSelected = NO;
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

}





#pragma mark - 弹出视图方法
- (void)showWithAnimation:(BOOL)animation
{
    
   
    //1.获取当前应用的主窗口
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview: self];
    self.backgroundView.alpha = 0.6;
    if (animation) {
        //动画前初始位置
        CGRect rect = self.alertView.frame;
        rect.origin.y = ScreenHeight;
        self.alertView.frame = rect;
        
        //浮现动画
        [UIView animateWithDuration:0.3 animations:^{
            CGRect rect = self.alertView.frame;
            rect.origin.y -= kSelectedAddressHeight + kTopViewHeight;
            self.alertView.frame = rect;
        }];
    }
}

#pragma mark - 关闭视图方法
- (void)dismissWithAnimation:(BOOL)animation
{
    //关闭动画
    [UIView animateWithDuration:0.2 animations:^{
        CGRect rect = self.alertView.frame;
        rect.origin.y += kSelectedAddressHeight + kTopViewHeight;
        self.alertView.frame = rect;
        
        self.backgroundView.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
         [self topBarItemClick:self.topTabbarItems[0]];
        if (self.chooseFinish && self->selectedModel) {
            self.chooseFinish(self->selectedModel);
        }
    }];
}

#pragma mark - event response
- (void)didTapBackgroundView:(UITapGestureRecognizer *)sender
{
    [self dismissWithAnimation:NO];
}
//点击按钮,滚动到对应位置
- (void)topBarItemClick:(UIButton *)btn
{
    NSInteger index = [self.topTabbarItems indexOfObject:btn];
       [UIView animateWithDuration:0.5 animations:^{
           self.contentView.contentOffset = CGPointMake(index * ScreenWidth, 0);
           [self changeUnderLineFrame:btn];
       }];
}

#pragma mark - getters and setters
//省级别数据源
- (NSMutableArray *)dataSouce{
    
    if (_dataSouce == nil) {
        _dataSouce = [[NSMutableArray alloc]init];
        [self.allData enumerateObjectsUsingBlock:^(PayCityModel* obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.pid == 0 && obj.isCity == NO) {
                [_dataSouce addObject:obj];
            }
        }];
    }
    return _dataSouce;
}

- (NSMutableArray *)tableViews{
    
    if (_tableViews == nil) {
        _tableViews = [NSMutableArray array];
    }
    return _tableViews;
}

- (NSMutableArray *)topTabbarItems{
    if (_topTabbarItems == nil) {
        _topTabbarItems = [NSMutableArray array];
    }
    return _topTabbarItems;
}

- (NSMutableArray *)getCityDataSourceWithModel:(PayCityModel *)model
{
    
    NSMutableArray *dataArray = [[NSMutableArray alloc]init];
    [self.allData enumerateObjectsUsingBlock:^(PayCityModel* obj, NSUInteger idx, BOOL * _Nonnull stop) {
               if (obj.pid == model.Id && obj.isCity == YES) {
                   obj.isSelected = NO;
                   [dataArray addObject:obj];
               }
           }];
    
    return dataArray;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
