//
//  CarThreeTabPanel.m
//  NaviDemo
//
//  Created by linbiao on 2019/5/9.
//  Copyright © 2019年 Baidu. All rights reserved.
//

#import "CarThreeTabPanel.h"
#import "MapCommonDefine.h"
#import "UIView+layout.h"
#import "CarThreeTabView.h"
#import "LoadingAnimationBar.h"
#import "UtilUITool.h"
#import "BNaviService.h"

#define CarTabCommonOffset (CR_MAP_VIEW_ENTRANCE_RIGHT_MARGIN)
#define CarTabBottomOffset (iPhoneX ? (34) : (IPHONE_SCREEN_WIDTH<=375 ? ADAPTOR_VALUE_750(3) : ADAPTOR_VALUE_750(5)))

@interface CarThreeTabPanel() <CarThreeTabViewDelegate, LoadingAnimationBarDelegate>

@property (nonatomic, strong) BNCarRouteModel *carRoute;
@property (nonatomic, assign) NSInteger currentIndex;
@property (nonatomic, strong) UIImageView *bgView;
@property (nonatomic, strong) NSArray *tabViewArr;
@property (nonatomic, strong) UIView *bottomBar;
@property (nonatomic, strong) UIButton *naviButton; //开始导航按钮
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) UIImageView *imgvTopLine;
@property (nonatomic, strong) LoadingAnimationBar *indicatorView;

@property (strong, nonatomic) NSMutableArray *threeTabCacheTabViewArray;
@property (strong, nonatomic) NSMutableArray *threeTabCacheButtonArray;

@end

@implementation CarThreeTabPanel

- (void)dealloc {
    NSLog(@"CarThreeTabPanel Dealloc");
}

- (void)setDelegate:(id<CarThreeTabPanelDelegate>)delegate {
    _delegate = delegate;
    
    [self loadData];
}

- (void)loadData {
    CGFloat bottomTop = [self load3tabUIData];
    if (bottomTop > 0) {
        [self loadBottomBarUIData:bottomTop];
    }
}

- (CGFloat)load3tabUIData {
    self.backgroundColor = [UIColor clearColor];
    
    for (UIView *subView in self.subviews) {
        if (subView != self.bgView) {
            [subView removeFromSuperview];
        }
    }
    
    self.bgView.height = self.height - BGViewBottomOffset;
    self.carRoute = nil;
    self.tabViewArr = nil;
    self.currentIndex = -1;
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(carRouteDataForThreeTabPanel:)]) {
        self.carRoute = [self.delegate carRouteDataForThreeTabPanel:self];
    }
    
    if (self.carRoute == nil || self.carRoute.carRoutes.count == 0) {
        return -1;
    }
    
    CGFloat bottomTop = 0;
    NSInteger count = self.carRoute.carRoutes.count;
    
    if (count == 1) {
        CarThreeTabView *tabView = nil;
        if (self.threeTabCacheTabViewArray.count) {
            tabView = self.threeTabCacheTabViewArray[0];
        } else {
            tabView = [CarThreeTabView new];
        }
        
        [tabView createUICache];
        tabView.delegate = self;
        
        
        tabView.width = self.width-2*(CarTabCommonOffset + 4);
        
        [tabView updateWithOneRoute:self.carRoute.carRoutes[0] capText:[self genCapTextAtIndex:0] allRoute:self.carRoute];
        [tabView updateSigle];
        tabView.left = CarTabCommonOffset + 4;
        
        [self addSubview:tabView];
        
        UITapGestureRecognizer* tapGestrue = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickSingleTapGesture:)];
        [self addGestureRecognizer:tapGestrue];
        
        bottomTop = CGRectGetMaxY(tabView.frame);
    } else {
        CGFloat leftMargin = CarTabCommonOffset + 4;
        CGFloat topMargin = 0.0;
        CGFloat tabViewWidth = (self.width - leftMargin * 2) / count;
        CGFloat tabViewHeight = ADAPTOR_VALUE_750(168);
        NSMutableArray *tmpViews = [NSMutableArray arrayWithCapacity:3];
        CarThreeTabView *tabView = nil;
        for (NSInteger i = 0; i < count; i++) {
            if ( i < self.threeTabCacheTabViewArray.count) {
                tabView = self.threeTabCacheTabViewArray[i];
                tabView.frame = CGRectMake(tabViewWidth * i + leftMargin, topMargin, tabViewWidth, tabViewHeight);
            } else {
                tabView = [[CarThreeTabView alloc] initWithFrame:CGRectMake(tabViewWidth * i + leftMargin, topMargin, tabViewWidth, tabViewHeight)];
                [self.threeTabCacheTabViewArray addObject:tabView];
            }
            [tabView createUICache];
            tabView.delegate = self;
            [tabView updateWithOneRoute:self.carRoute.carRoutes[i] capText:[self genCapTextAtIndex:i] allRoute:self.carRoute];
            [tabView updateMulti];
            [tabView setBeenSelected:NO];
            [self addSubview:tabView];
            [tmpViews addObject:tabView];
            
            UIButton *button = nil;
            if (self.threeTabCacheButtonArray.count > i) {
                button = self.threeTabCacheButtonArray[i];
            } else {
                button = [UIButton new];
                [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
                [self.threeTabCacheButtonArray addObject:button];
            }
            button.accessibilityLabel = [NSString stringWithFormat:@"%@, 用时%@, 行驶%@.", [self genCapTextAtIndex:i], [tabView getTimeValue], [tabView getDistanceValue]];
            button.frame = tabView.frame;
            button.tag = i;
            button.backgroundColor = [UIColor clearColor];
            
            [self addSubview:button];
        }
        self.tabViewArr = tmpViews;
        
        bottomTop = tabViewHeight;
    }
    return bottomTop;
}

- (void)loadBottomBarUIData:(CGFloat)bottomTop {
    _bottomBar = [self createBottomBarWithHeight:self.height-CarTabBottomOffset - bottomTop];
    
    _bottomBar.top = bottomTop;
    _bottomBar.bottom = self.height - CarTabBottomOffset;
    _bottomBar.left = CarTabCommonOffset;
    _bottomBar.width = self.width - 2*CarTabCommonOffset;
    [self addSubview:_bottomBar];
    
    CGFloat marginY = ADAPTOR_VALUE_750(4);
    self.naviButton.centerX = _bottomBar.centerX;
    self.naviButton.top = ceilf((_bottomBar.height - self.naviButton.height)/2.0) - marginY;
  
    _lineView = self.lineView;
    _lineView.frame = CGRectMake(CarTabCommonOffset, self.height-1, self.width - 2*CarTabCommonOffset, 0.5);
    _lineView.backgroundColor = UIColorFromRGB(0xd7d8d9);
    _lineView.hidden = YES;
    [self addSubview:_lineView];
}

- (UIView *)createBottomBarWithHeight:(CGFloat)barHeight {
    [_bottomBar.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    UIView *bottomBar = [self createBottomBarUI];
    bottomBar.frame = CGRectMake(0, 0, self.width - 2*CarTabCommonOffset, barHeight);

    CGFloat buttonHeight = iPhone5 ? 33 : 38;
    
    UIButton *naviBtn = self.naviButton;
    
    CGFloat width = bottomBar.width - 2*ADAPTOR_VALUE_750(30);
    naviBtn.frame = CGRectMake(ADAPTOR_VALUE_750(30), ADAPTOR_VALUE_750(20), width, buttonHeight);
    naviBtn.centerY = bottomBar.centerY;
    
    NSString *buttonTitle = @"开始导航";
    [naviBtn setTitle:buttonTitle forState:UIControlStateNormal];
    [bottomBar addSubview:naviBtn];
    
    return bottomBar;
}

- (UIView *)createBottomBarUI {
    if (_bottomBar)
        return _bottomBar;
    _bottomBar = [[UIView alloc] init];
    
    UIFont *textFont = [UIFont systemFontOfSize:ADAPTOR_VALUE_750(32)];
    
    UIImage *backGroundImage = [[UIImage imageNamed:@"carpage_icon_button_navi"] stretchableImageWithLeftCapWidth:16 topCapHeight:0];
    UIImage* highlightBackImage = [[UIImage imageNamed:@"carpage_bottomview_navi_highlight"] stretchableImageWithLeftCapWidth:16 topCapHeight:0];
    UIButton *naviBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    naviBtn.tag = TabButtonTypeNavi;
    naviBtn.titleLabel.font = textFont;
    [naviBtn setTitleColor: [UIColor whiteColor] forState:UIControlStateNormal];
    [naviBtn setTitleColor:UIColorFromRGBA(0xffffff, 0.4) forState:UIControlStateHighlighted];
    [naviBtn setBackgroundImage:backGroundImage forState:UIControlStateNormal];
    [naviBtn setBackgroundImage:highlightBackImage forState:UIControlStateHighlighted];
    self.naviButton.height = 45;
    self.naviButton = naviBtn;
    [naviBtn addTarget:self action:@selector(bottomButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
   
    return _bottomBar;
}

- (NSString *)genCapTextAtIndex:(NSInteger)index {
    if (index >= self.carRoute.carRoutes.count) return nil;
    NSString *capText = nil;
    if ([self.delegate respondsToSelector:@selector(capTextForThreeTabPanel:atIndex:)]) {
        capText = [self.delegate capTextForThreeTabPanel:self atIndex:index];
    }
    return capText;
}

- (void)remove3TabUI {
    for (UIView *subview in self.subviews) {
        if (subview != self.bgView) {
            [subview removeFromSuperview];
        }
    }
}

- (void)selectAtIndex:(NSInteger)index {
    if (index >= self.carRoute.carRoutes.count) {
        return;
    }
    
    if (self.currentIndex != index) {
        if (self.currentIndex != -1) {
            CarThreeTabView *preTabView = self.tabViewArr[self.currentIndex];
            preTabView.beenSelected = NO;
        }
        
        CarThreeTabView *tabView = self.tabViewArr[index];
        tabView.beenSelected = YES;
        self.currentIndex = index;
        
        [self handleTabViewLine];
    }
}

- (void)reloadData {
    [self loadData];
    if ([self.delegate respondsToSelector:@selector(selectedIndexForTabPanel:)]) {
        NSInteger selectedIndex = [self.delegate selectedIndexForTabPanel:self];
        [self selectAtIndex:selectedIndex]; //刷新
    }
}

- (BOOL)isBottomBarVisiable{
    return _bottomBar && !_bottomBar.hidden;
}

- (void)hideLine:(BOOL)hidden {
    if (self.lineView.hidden != hidden) {
        self.lineView.hidden = hidden;
        self.lineView.top = self.height - 1;
    }
}

- (void)handleTabViewLine {
    NSInteger count = self.carRoute.carRoutes.count;
    if (count == 3) {
        for (CarThreeTabView *tabView in self.tabViewArr) {
            [tabView hideLine:YES];
        }
        
        if (self.currentIndex == 0) {
            [self.tabViewArr.lastObject hideLine:NO];
        } else if (self.currentIndex == 2) {
            [self.tabViewArr[1] hideLine:NO];
        }
    }
}

- (void)updateArriveTimeAndJamDist {
    if ([self.delegate respondsToSelector:@selector(carRouteDataForThreeTabPanel:)]) {
        self.carRoute = [self.delegate carRouteDataForThreeTabPanel:self];
    }
    
    if (self.carRoute == nil || self.carRoute.carRoutes.count == 0) {
        return;
    }
    
    int i = 0;
    //更新到达时间
    for (CarThreeTabView *preTabView in _tabViewArr) {
        [preTabView updateTimeWithOneRoute:self.carRoute.carRoutes[i]];
        i++;
    }
}

- (void)createUI {
    if (self.threeTabCacheTabViewArray.count)
        return;
    [self bgView];
    
    for (int i = 0; i < 3; ++i) {
        CarThreeTabView* tabView = [[CarThreeTabView alloc] initWithFrame:CGRectZero];
        [tabView createUICache];
        [self.threeTabCacheTabViewArray addObject:tabView];
        
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self.threeTabCacheButtonArray addObject:button];
    }
    [self createBottomBarUI];
    [self lineView];
}

- (void)showFullState:(BOOL)isFull {
    if (isFull) {
        [UIView animateWithDuration:0.2 animations:^{
            self.bgView.left = -12-CarTabCommonOffset;
            self.bgView.width = self.width+24+2*CarTabCommonOffset;
        }];
    } else {
        [UIView animateWithDuration:0.1 animations:^{
            CGFloat offset = (IPHONE_SCREEN_HEIGHT == 736 || IPHONE_SCREEN_HEIGHT == 896) ? 0 : (iPhoneX ? -ADAPTOR_VALUE_750(5) : -ADAPTOR_VALUE_750(4));
            self.bgView.left = offset;
            self.bgView.width = self.width - 2*offset;
        }];
    }
}

#pragma mark - PageState
- (void)pageInit {
    
}

- (void)pageLoading {
    for (UIView *subview in self.subviews) {
        if (subview != self.bgView) {
            [subview removeFromSuperview];
        }
    }
    [self showLoading];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self createUI];
    });
}

- (void)pageLoadedWillSuccess:(BNCarRouteModel*)carRoute {
    if (carRoute) {
        [self stopLoading];
        if ([self.delegate respondsToSelector:@selector(carRouteDataForThreeTabPanel:)]) {
            self.carRoute = [self.delegate carRouteDataForThreeTabPanel:self];
        }
        [self reloadData];
    }
}

- (void)pageLoadedSuccess:(id)result {
    //success之后必须做carroute赋值
    if (result) {
        [self stopLoading];
        _bottomBar.hidden = NO;
        if ([self.delegate respondsToSelector:@selector(carRouteDataForThreeTabPanel:)]) {
            self.carRoute = [self.delegate carRouteDataForThreeTabPanel:self];
        }
        [self reloadData];
    }
}

- (void)pageLoadedFailed:(NSError *)error {
    [self stopLoading];
    if (!error) {
        [self showRetryWithMessage:nil]; //显示重试
    } else {
        NSString *message = error.userInfo[NSLocalizedDescriptionKey];
        [self showRetryWithMessage:message];
    }
}

- (void)showRetryWithMessage:(NSString *)message {
    if (!self.indicatorView.superview) {
        [self addSubview:self.indicatorView];
    }
    
    if (!message) {
        [self.indicatorView updateFailedMessage:@"路线规划失败," withRetryButtonShow:YES];
    } else {
        if([message isEqualToString:kThreePanleError_LocationClose]||[message isEqualToString:kThreePanleError_LocationFail]||[message isEqualToString:kThreePanleError_NetFail]) {
            [self.indicatorView updateFailedMessage:message withRetryButtonShow:YES];
        } else {
            [self.indicatorView updateFailedMessage:message withRetryButtonShow:NO];
        }
    }
}

- (void)stopLoading {
    //stopLoading的前提是有数据
    [self.indicatorView stopAnimation];
}

- (void)showLoading {
    NSString *message = [UtilUITool nameForStrategy:[BNaviService_RoutePlan getCurrentPreference]];
    if (!self.indicatorView.superview) {
        [self addSubview:self.indicatorView];
    }
    [self.indicatorView setLoadingText:[NSString stringWithFormat:@"正在为您规划%@路线",message]];
    [self.indicatorView startAnimation];
    if (_bottomBar) {
        [_bottomBar removeFromSuperview];
    }
}

- (void)setFrame:(CGRect)frame {
    [super setFrame:frame];
    
    self.bgView.height = frame.size.height - BGViewBottomOffset + (iPhoneX ? 34 : 0);
    _imgvTopLine.left = 0;
    _imgvTopLine.width = self.width;
    _bottomBar.height = self.height - CarTabBottomOffset - _bottomBar.top + (iPhoneX ? 34 : 0);
    self.bottomBar.bottom = self.height - CarTabBottomOffset + (iPhoneX ? 34 : 0);
    
    CGFloat marginY = ADAPTOR_VALUE_750(4);
    self.naviButton.centerX = _bottomBar.centerX;
    self.naviButton.top = ceilf((_bottomBar.height - self.naviButton.height)/2.0) - marginY;

    self.indicatorView.height = CGRectGetHeight(self.frame) - CarTabBottomOffset; //tabPanel的高度会变，在这里调整
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.indicatorView.height = self.height - CarTabBottomOffset;
}
-(CGRect)getNaviBtnFrame {
    return self.naviButton.frame;
}
- (void)hiddenNaviBtn:(BOOL)hid {
    /// 防止反复设置
    if (hid && self.naviButton.hidden != hid) {
        self.bgView.height = self.frame.size.height - BGViewBottomOffset + (iPhoneX ? 34 : 0) - self.naviButton.bottom;
    }
    self.naviButton.hidden = hid;
}
#pragma mark - Event
- (BOOL)canResponseUserClick {
    BOOL ret = YES;
    if ([self.delegate respondsToSelector:@selector(pageStateIsWillSuccess)]) {
        BOOL isWillSuccess = [self.delegate pageStateIsWillSuccess];
        ret = !isWillSuccess;
    }
    return ret;
}

- (void)clickSingleTapGesture:(id)sender {
    if (![self canResponseUserClick]) {
        return;
    }
    if (self.carRoute.carRoutes.count == 1) {
        if ([self.delegate respondsToSelector:@selector(threeTabPanelDidClicked:)]) {
            [self.delegate threeTabPanelDidClicked:self];
        }
    }
}

- (void)buttonClicked:(UIButton *)button {
    if (![self canResponseUserClick]) {
        if ([self.delegate respondsToSelector:@selector(setPageStateWillSuccessRouteTabClick:)]) {
            __weak typeof(self) weakSelf = self;
            [self.delegate setPageStateWillSuccessRouteTabClick:^{
                [weakSelf buttonClicked:button];
            }];
        }
        return;
    }
    
    NSInteger index = button.tag;
    [self selectAtIndex:index];
    if ([self.delegate respondsToSelector:@selector(threeTabPanel:didSelectAtIndex:)]) {
        [self.delegate threeTabPanel:self didSelectAtIndex:index];
    }
}

- (void)bottomButtonClicked:(UIButton *)button {
    if (![self canResponseUserClick]) {
        if ([self.delegate respondsToSelector:@selector(setPageStateWillSuccessBottomButtonClick:)]) {
            __weak typeof(self) weakSelf = self;
            [self.delegate setPageStateWillSuccessBottomButtonClick:^{
                [weakSelf bottomButtonClicked:button];
            }];
        }
        return;
    }
    
    if ([self.delegate respondsToSelector:@selector(threeTabPanel:didClickButtonType:)]) {
        [self.delegate threeTabPanel:self didClickButtonType:button.tag];
    }
}

#pragma mark - CarThreeTabViewDelegate
- (BOOL)isLonjounery {
    if (self.delegate && [self.delegate respondsToSelector:@selector(isLongjounery)]) {
        return [self.delegate isLongjounery];
    }
    return NO;
}

#pragma mark - LoadingAnimationBarDelegate
- (void)retryRoutePlan {
    if ([self.delegate respondsToSelector:@selector(didRetryClicked)]) {
        [self.delegate didRetryClicked];
    }
}

#pragma mark - Lazy loading

- (UIImageView *)bgView {
    if (!_bgView) {
        _bgView = [[UIImageView alloc] init];
        UIImage *image = [UIImage imageNamed:@"tab_background_shadow.png"];
        CGFloat leftOffset = 0;
        image = [image stretchableImageWithLeftCapWidth:image.size.width * 0.5 topCapHeight:image.size.height * 0.5];
        _bgView.frame = CGRectMake(leftOffset, -4, self.frame.size.width - 2*leftOffset, self.frame.size.height - BGViewBottomOffset);
        _bgView.image = image;
        [self addSubview:_bgView];
    }
    return _bgView;
}
    
- (UIView *)lineView {
    if (!_lineView) {
        _lineView = [[UIView alloc] init];
    }
    return _lineView;
}

- (LoadingAnimationBar *)indicatorView {
    if (!_indicatorView) {
        _indicatorView = [[LoadingAnimationBar alloc] initWithFrame:CGRectMake(0, 0, self.width - 2*CarTabCommonOffset, self.height-CarTabBottomOffset)];
        _indicatorView.backgroundColor = [UIColor clearColor];
        _indicatorView.layer.masksToBounds = YES;
        _indicatorView.layer.cornerRadius = 5.f;
        _indicatorView.delegate = self;
        [self addSubview:_indicatorView];
    }
    return _indicatorView;
}
    
- (NSMutableArray *)threeTabCacheTabViewArray {
    if (!_threeTabCacheTabViewArray) {
        _threeTabCacheTabViewArray = [[NSMutableArray alloc] init];
    }
    return _threeTabCacheTabViewArray;
}
    
- (NSMutableArray *)threeTabCacheButtonArray {
    if (!_threeTabCacheButtonArray) {
        _threeTabCacheButtonArray = [[NSMutableArray alloc] init];
    }
    return _threeTabCacheButtonArray;
}


@end
