//
//  GMToFaceDoctorListNewHeaderView.m
//  Gengmei
//
//  Created by Jessica on 2020/3/28.
//  Copyright © 2020 更美互动信息科技有限公司. All rights reserved.
//

#import "GMToFaceDoctorListNewHeaderView.h"
#import "GMToFaceDoctorListHeaderFlowLayout.h"
#import "GMToFaceDoctorListHorNewCell.h"
#import "GMTelephoneProxy.h"
#import "GMFaceListPageControl.h"

#define MaxCount 500
@interface GMToFaceDoctorListNewHeaderView ()<UICollectionViewDelegate, UICollectionViewDataSource> {
    BOOL _beganDragging;
}
@property (nonatomic, strong) GMToFaceDoctorListHeaderFlowLayout *layout;
@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic, strong) GMFaceListPageControl *pageControl;

@end
@implementation GMToFaceDoctorListNewHeaderView
- (instancetype)init {
    if (self = [super init]) {
        [self setUI];
    }
    return self;
}

- (void)setUI {
    self.backgroundColor = RGBCOLOR_HEX(0xF7F6FA);
    [self addSubview:self.collectView];
    [self addSubview:self.pageControl];

    [self.collectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(((MAINSCREEN_WIDTH - 12 - 12) / 1.7) + 30);
        make.top.mas_equalTo(0);
    }];
    self.pageControl.frame = CGRectMake(0, ((MAINSCREEN_WIDTH - 12 - 12) / 1.7) + 30, MAINSCREEN_WIDTH, 10);
}

- (void)setDataArray:(NSMutableArray<GMToFaceRecommendsDoctors *> *)dataArray {
    _dataArray = dataArray;
    [self.collectView reloadData];
    __weak typeof(self)weakSelf = self;
    // 用这个方法是防止 collectionview reloadData 执行完成后 再做接下来的事情
    [self.collectView performBatchUpdates:^{
        [weakSelf.collectView layoutIfNeeded];
    } completion:^(BOOL finished) {
        if (finished) {
            NSIndexPath *firstIndexPath = [NSIndexPath indexPathForItem: 0 inSection:0];
            [self.collectView scrollToItemAtIndexPath:firstIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
            _layout.currentIndex = 0;
            self.pageControl.numberOfPages = dataArray.count;
            [self setUpTimer];
        }
    }];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count * MaxCount;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    GMToFaceDoctorListHorNewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([GMToFaceDoctorListHorNewCell class]) forIndexPath:indexPath];
    NSIndexPath *currentIndex = [NSIndexPath indexPathForItem:(indexPath.row % self.dataArray.count) inSection:0];
    self.pageCtrl.tabName = @"医生推荐";
    cell.pageCtrl = self.pageCtrl;
    cell.doctorsModel = self.dataArray[currentIndex.row];
    cell.indexPath = currentIndex;
    __weak __typeof(self)weakSelf = self;
    cell.blockInfoCallback = ^(NSString *blockInfo) {
        weakSelf.blockInfoCallback(blockInfo);
    };
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
//    GMToFaceRecommendsDoctors *model = self.dataArray[indexPath.row];
//    [GMBaseTool getCurrentViewController].tabName = @"医生推荐";
//    //跳到医生主页
//    [[GMRouter sharedInstance] pushScheme:model.gm_url];
}

#pragma mark <UIScrollViewDelegate>
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    _beganDragging = YES;
    [self invalidateTimer];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    _beganDragging = NO;
    if (decelerate == NO) { // 没有降速的过程,直接在此方法中去添加定时器
        [self setUpTimer];
    }

}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [self setUpTimer];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    // 确定当前页数及组数
    self.pageControl.currentPage = _layout.currentIndex % self.dataArray.count;
}

- (void)setUpTimer {
    if (self.timer.valid) {
        [self invalidateTimer];
    }

    self.timer = [NSTimer timerWithTimeInterval:10 target:[GMTelephoneProxy proxyWithTarget:self] selector:@selector(nextPage) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
}

- (void)invalidateTimer {
    [self.timer invalidate];
    self.timer = nil;
}

- (void)nextPage{
    if (_beganDragging) return;
    if (!self.superview) return;
    _layout.currentIndex += 1;
    if (_layout.currentIndex == (self.dataArray.count * MaxCount)) {
       _layout.currentIndex = 0;
    }
    NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem: _layout.currentIndex inSection:0];
    [self scrolToPath:nextIndexPath animated:YES];
}

//滚动处理
- (void)scrolToPath:(NSIndexPath*)path animated:(BOOL)animated{
    
    if (path.row > self.dataArray.count * MaxCount - 1){
        [self invalidateTimer];
        return;
    }
    if (self.dataArray.count==0) return;
    [self.collectView scrollToItemAtIndexPath:path atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:animated];
    
        self.collectView.contentOffset = CGPointMake(self.collectView.contentOffset.x+self.collectView.frame.size.width *(0.5 - _layout.contentOffsetX), self.collectView.contentOffset.y);
}

+ (CGFloat)viewHeight {
    return (((MAINSCREEN_WIDTH - 12 - 12) / 1.7) + 40);
}
- (UICollectionViewFlowLayout *)layout {
    if (!_layout) {
        _layout = [[GMToFaceDoctorListHeaderFlowLayout alloc] init];
    }
    return _layout;
}

- (UICollectionView *)collectView {
    if (!_collectView) {
        _collectView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.layout];
        _collectView.showsHorizontalScrollIndicator = NO;
        _collectView.backgroundColor = RGBCOLOR_HEX(0xF7F6FA);
        _collectView.decelerationRate = UIScrollViewDecelerationRateFast;
        _collectView.delegate = self;
        _collectView.dataSource = self;
        [_collectView registerClass:[GMToFaceDoctorListHorNewCell class] forCellWithReuseIdentifier:NSStringFromClass([GMToFaceDoctorListHorNewCell class])];
    }     return _collectView;
}

- (GMFaceListPageControl *)pageControl {
    if (!_pageControl) {
        _pageControl = [[GMFaceListPageControl alloc] init];
        _pageControl.numberOfPages = 0;
        _pageControl.tintColor = RGBCOLOR_HEX(0xD8D8D8);
        _pageControl.currentTintColor = RGBCOLOR_HEX(0x7DC6CC);
    }
    return _pageControl;
}

- (void)dealloc {
    [self invalidateTimer];
}
@end
