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

#import "CarDetailContentView.h"
#import "MapCommonDefine.h"
#import "RouteCollectionViewLayout.h"
#import "RouteReusableView.h"
#import "UtilUITool.h"
#import "BNCarRouteStepModel+Ext.h"

@interface CarDetailContentView() <RouteCollectionViewLayoutDelegate, UICollectionViewDelegate, UICollectionViewDataSource>
{
    NSMutableDictionary *_titleHeightCache;
    RouteCollectionViewLayout *_layout;
    UILabel *_detailLabel;
    BNCarRouteModel *_carRouteData;
    NSInteger _routeIndex;
    UIImageView *_bgView;
}

@end

@implementation CarDetailContentView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = UIColorFromRGB(0xf7f7f7);
        [self contentInit];
    }
    return self;
}

- (void)setFrame:(CGRect)frame {
    [super setFrame:frame];
    
    CGFloat topOffset = -4;
    _bgView.frame = CGRectMake(0, topOffset, self.frame.size.width, self.frame.size.height - topOffset*2 + 11);
    _detailLabel.frame = CGRectMake(15 , 10 + ADAPTOR_VALUE_750(20), self.bounds.size.width, 20);
    _detailView.frame = CGRectMake(CR_MAP_VIEW_ENTRANCE_RIGHT_MARGIN + 4, 0, self.bounds.size.width  - CR_MAP_VIEW_ENTRANCE_RIGHT_MARGIN*2 - 8, self.bounds.size.height);
}

static float linePadding = 3;
+ (void)setLinePadding:(float)padding{
    linePadding = padding;
}

- (void)contentInit {
    _bgView = [[UIImageView alloc] init];
    UIImage *image = [UIImage imageNamed:@"tab_background_shadow.png"];
    CGFloat topOffset = -4;
    image = [image stretchableImageWithLeftCapWidth:image.size.width * 0.5 topCapHeight:image.size.height * 0.5];
    _bgView.frame = CGRectMake(0, topOffset, self.frame.size.width, self.frame.size.height - topOffset*2 + 11);
    _bgView.image = image;
    [self addSubview:_bgView];
    
    _detailLabel = [[UILabel alloc] initWithFrame:CGRectMake(15 , 10 + ADAPTOR_VALUE_750(20), self.bounds.size.width, 20)];
    _detailLabel.text = @"路线详情";
    _detailLabel.textAlignment = NSTextAlignmentLeft;
    _detailLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:ADAPTOR_VALUE_750(32)];
    [_detailLabel setTextColor:[UIColor colorWithRed:0x33/255.0f green:0x33/255.0f blue:0x33/255.0f alpha:1.0f]];
    
    _layout = [[RouteCollectionViewLayout alloc] init];
    _layout.delegate = self;
    _layout.contentInsets = UIEdgeInsetsMake(ADAPTOR_VALUE_750(480) + 30 + CR_MAP_VIEW_ENTRANCE_RIGHT_MARGIN + 4, CR_MAP_VIEW_ENTRANCE_RIGHT_MARGIN + 4, 0, CR_MAP_VIEW_ENTRANCE_RIGHT_MARGIN + 4);
    _layout.leftPanelWidth = 60;
    _layout.linePadding = linePadding;
    _layout.lineWidth = 2;
    
    _detailView = [[UICollectionView alloc] initWithFrame:CGRectMake(CR_MAP_VIEW_ENTRANCE_RIGHT_MARGIN + 4, 0, self.bounds.size.width  - CR_MAP_VIEW_ENTRANCE_RIGHT_MARGIN*2 - 8, self.bounds.size.height) collectionViewLayout:_layout];
    
    if (@available(iOS 11.0, *)) {
        _detailView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
    
    _detailView.layer.cornerRadius = 5.f;
    _detailView.clipsToBounds = YES;
    _detailView.delegate = self;
    _detailView.dataSource = self;
    _detailView.backgroundColor = [UIColor clearColor];
    _detailView.scrollEnabled = NO;
    [self addSubview:_detailView];
    
    [_detailView registerClass:[RouteCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [_detailView registerClass:[RouteSupplementaryIconView class] forSupplementaryViewOfKind:kRouteSupplementaryIconKind withReuseIdentifier:@"icon"];
    [_detailView registerClass:[RouteSupplementaryDashedLineView class] forSupplementaryViewOfKind:kRouteSupplementaryLineKind withReuseIdentifier:@"line"];
    
    [_detailView addSubview:_detailLabel];
}

- (void)refreshData:(BNCarRouteModel *)carRoute index:(NSInteger)index {
    _carRouteData = carRoute;
    _routeIndex = index;
    [_detailView reloadData];
    [self scrollToTop];
}

- (void)scrollToTop {
    [_detailView setContentOffset:CGPointMake(0.0f, 0.0f) animated:NO];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    _layout.contentInsets = UIEdgeInsetsMake(30 + CR_MAP_VIEW_ENTRANCE_RIGHT_MARGIN + 4, CR_MAP_VIEW_ENTRANCE_RIGHT_MARGIN + 4, 0, CR_MAP_VIEW_ENTRANCE_RIGHT_MARGIN + 4);
    _detailLabel.frame = CGRectMake(15, 10 + ADAPTOR_VALUE_750(20), self.bounds.size.width, 20);
    _detailView.top = 0;
    _detailView.height = self.bounds.size.height;
}

#pragma mark - Private
- (CGFloat)titleHeightAtIndex:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    NSInteger totalCount = [self totalStepCount];
    NSAttributedString *title = [self titleAtIndex:indexPath];
    NSInteger key = section;
    // 起终点缓存key跟在数组最后，即totalCount和totalCount+1
    if (section == 0 && row == 0) {
        key = totalCount;
    } else if (section == totalCount - 1 && row == 1) {
        key = totalCount + 1;
    }
    NSNumber *theHeight = _titleHeightCache[@(key)];
    if (theHeight == nil) {
        CGSize boundSize = CGSizeMake(320 - 130, 1000);
        CGRect textBound = [title boundingRectWithSize: boundSize
                                               options: NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin
                                               context: nil];
        theHeight = @(ceilf(textBound.size.height));
        _titleHeightCache[@(key)] = theHeight;
    }
    return [theHeight floatValue];
}

- (NSInteger)totalStepCount {
    if ([_carRouteData.carRoutes count] > 0) {
        if (_carRouteData.carRoutes.count > _routeIndex) {
            BNCarOneRouteModel *oneRoute = [_carRouteData.carRoutes objectAtIndex:_routeIndex];
            return [oneRoute.stepList count];
        } else {
            return 0;
        }
    }
    return 0;
}

- (NSAttributedString *)titleAtIndex:(NSIndexPath *)indexPath {
    BNCarOneRouteModel *oneRoute = nil;
    if ([_carRouteData.carRoutes count] > 0) {
        oneRoute = [_carRouteData.carRoutes objectAtIndex:_routeIndex];
    }
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    NSAttributedString *title = nil;
    if (section == 0 && row == 0) {
        NSString *tmpString = nil;
        if (!oneRoute.startPoint.name || [oneRoute.startPoint.name isEqualToString:@""]) {
            tmpString = @"起点";
        } else {
            tmpString = [NSString stringWithFormat:@"从%@出发",oneRoute.startPoint.name];
        }
        title = [BNCarRouteStepModel combinedTitleWithRoadName:tmpString distance:@"起点"];
    } else if (section == [self totalStepCount] - 1 && row == 0) {
        NSString *tmpString = nil;
        if (!oneRoute.endPoint.name || [oneRoute.endPoint.name isEqualToString:@""]) {
            tmpString = @"终点";
        } else {
            tmpString = [NSString stringWithFormat:@"%@",oneRoute.endPoint.name];
        }
        title = [BNCarRouteStepModel combinedTitleWithRoadName:tmpString distance:@"到达终点"];
    } else {
        BNCarRouteStepModel *carRouteStep = nil;
        if (oneRoute && indexPath.section <= [oneRoute.stepList count]) {
            carRouteStep = [oneRoute.stepList objectAtIndex:indexPath.section];
        }
        title = carRouteStep.linkFormatTipDoubleLineAttrString;
    }
    return title;
}

- (UIImage *)iconAtIndex:(NSIndexPath *)indexPath {
    BNCarOneRouteModel *oneRoute = nil;
    if ([_carRouteData.carRoutes count] > 0) {
        oneRoute = [_carRouteData.carRoutes objectAtIndex:_routeIndex];
    }
    
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    NSString *iconName;
    BNCarRouteStepModel *step = oneRoute.stepList[section];
    if (section == 0 && row == 0) {
        if ([oneRoute.startPoint.name isEqualToString: @"我的位置"]) {
            iconName = @"icon_cardetail_location";
        } else {
            iconName = @"map_route_turn_start";
        }
    } else if (section == [self totalStepCount]-1 && row == 0) {
        if ([oneRoute.endPoint.name isEqualToString: @"我的位置"]) {
            iconName = @"icon_cardetail_location";
        } else {
            iconName = @"map_carroute_turn_dest";
        }
    } else if ([step.linkFormatTip containsString:@"步行前往"]) {
        return [UtilUITool loadResourceImage:@"map_route_turn_walk"];
    } else {
        if (oneRoute && indexPath.section <= [oneRoute.stepList count]) {
            BNCarRouteStepModel *carRouteStep = [oneRoute.stepList objectAtIndex:indexPath.section];
            NSInteger iconIndex = carRouteStep.turn;
            iconName = [BNCarRouteDataUtil typeIconNameOfEnum:(int)iconIndex];
        }
    }
    
    if ([iconName isKindOfClass:[NSString class]] && iconName.length) {
        return [UtilUITool loadResourceImage:iconName];
    }
    return nil;
}

+ (void)setHeightForCellAdditionalHeight:(float)height{
    heightForCellAdditionalHeight = height;
}
static float heightForCellAdditionalHeight = 25.0f;

#pragma mark - RouteCollectionViewLayoutDelegate
- (CGFloat)routeCollectionViewLayout:(RouteCollectionViewLayout *)layout heightForItemAtIndexPath:(NSIndexPath *)indexPath {
    return [self titleHeightAtIndex:indexPath] + heightForCellAdditionalHeight;
}

- (CGSize)routeCollectionViewLayout:(RouteCollectionViewLayout *)layout sizeForIconAtIndexPath:(NSIndexPath *)indexPath {
    return [[self iconAtIndex:indexPath] size];
}

#pragma mark - UICollectionViewDelegate, UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return [self totalStepCount];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0 ){
        return 2;
    }
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    _detailView = collectionView;
    RouteCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.left = 0;
    cell.width = collectionView.width;
    cell.titleLabel.attributedText = [self titleAtIndex:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (kind == kRouteSupplementaryIconKind) {
        RouteSupplementaryIconView *icon = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"icon" forIndexPath:indexPath];
        icon.imageView.image = [self iconAtIndex:indexPath];
        
        return icon;
    }
    else if(kind == kRouteSupplementaryLineKind){
        RouteSupplementaryDashedLineView *line = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"line" forIndexPath:indexPath];
        return line;
    }
    else {
        return nil;
    }
}

@end
