//
//  GMFaceSegmentView.m
//  Gengmei
//
//  Created by 朱璇 on 2019/12/17.
//  Copyright © 2019 更美互动信息科技有限公司. All rights reserved.
//

#import "GMFaceSegmentView.h"
#import "GMFaceSegmentViewLayout.h"
#import <AudioToolbox/AudioToolbox.h>
@import GMFoundation;
#define itemWidth 65
#define itemHeight 40

@interface GMAIDotNotificationView : GMView

@property (nonatomic, strong) GMView *dotView;

@end

@implementation GMAIDotNotificationView

static CGFloat kRedDotViewWidth = 3;

- (void)setup {
    [super setup];
    [self addSubview:self.dotView];
}

- (void)showWithSuperView:(UIView *)superView top:(CGFloat)top left:(CGFloat)left {
    [superView addSubview:self];
    self.frame = CGRectMake(left, top, kRedDotViewWidth, kRedDotViewWidth);
}

- (void)hide {
    [self removeFromSuperview];
}

- (GMView *)dotView {
    if (!_dotView) {
        _dotView = [[GMView alloc] init];
        _dotView.backgroundColor = UIColor.auxiliaryTextGreen;
        _dotView.layer.cornerRadius = kRedDotViewWidth / 2.0;
        _dotView.layer.masksToBounds = YES;
        [self addSubview:_dotView];
        [_dotView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
    }
    return _dotView;
}
@end

@interface GMfaceTypeCell()
@property (nonatomic, strong) GMLabel *titleLabel;
@end
@implementation GMfaceTypeCell
- (void)setup {
    [super setup];
    self.layer.cornerRadius = 7;
    _titleLabel = [[GMLabel alloc] init];
    _titleLabel.textColor = UIColor.headlineText;
    _titleLabel.font = [UIFont gmFont:12];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    [self addSubview:_titleLabel];
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self);
    }];
}

- (void)setIsSelected:(BOOL)isSelected {
    if (isSelected) {
           _titleLabel.textColor = UIColor.auxiliaryTextGreen;
           _titleLabel.font = [UIFont gmBoldFont:12];
       } else {
           _titleLabel.textColor = UIColor.headlineText;
           _titleLabel.font = [UIFont gmFont:12];
       }
}

- (void)setCellSelected:(BOOL)selected {
   
}

@end

@interface GMFaceSegmentView()<UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, strong) GMCollectionView *segmentCollectionView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) GMAIDotNotificationView *dotView;


@end

static NSString *kShowedSkinDotView = @"kShowedSkinDotView";

@implementation GMFaceSegmentView
- (void)setup {
    [super setup];
    _dataSource = [NSMutableArray arrayWithObjects:@"面孔起源", @"颜值分析", @"肤质分析", nil];
    GMFaceSegmentViewLayout *layout = [[GMFaceSegmentViewLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    // 设置最小行间距
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    
    _segmentCollectionView = [[GMCollectionView alloc] initWithFrame:CGRectMake(0, 0, itemWidth * 5, itemHeight) collectionViewLayout:layout];
    _segmentCollectionView.backgroundColor = UIColor.whiteColor;
    _segmentCollectionView.delegate = self;
    _segmentCollectionView.dataSource = self;
    _segmentCollectionView.showsVerticalScrollIndicator = NO;
    _segmentCollectionView.showsHorizontalScrollIndicator = NO;
    [_segmentCollectionView registerClass:[GMfaceTypeCell class] forCellWithReuseIdentifier:NSStringFromClass([GMfaceTypeCell class])];
    [self addSubview:_segmentCollectionView];
    
    [_segmentCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.right.left.mas_equalTo(0);
    }];
    
    [self setSelectedCellWithType:GMScanAnimationTypeScanSkin];
    [self.segmentCollectionView setContentOffset:CGPointMake(itemWidth * 2, 0)];
}

- (void)setSelectedCellWithType:(GMScanAnimationType)type {
    NSArray *cells = [_segmentCollectionView visibleCells];
    for (GMfaceTypeCell *cell in cells) {
        NSIndexPath *indexPath = [_segmentCollectionView indexPathForCell:cell];
        if (indexPath.section == 1) {
            cell.isSelected = indexPath.row == [self getIndexWithType:type];
        }
    }
}

- (void)setSelectedType:(GMScanAnimationType)selectedType {
    _selectedType = selectedType;
    [self setSelectedCellWithType:selectedType];
    [self.segmentCollectionView setContentOffset:CGPointMake([self getIndexWithType:selectedType] * itemWidth, 0) animated:YES];
    if (selectedType == GMScanAnimationTypeScanSkin) {
        [_dotView hide];
    }
}

- (int)getIndexWithType:(GMScanAnimationType)type {
    if (type == GMScanAnimationTypeScanFace) {
        return 1;
    } else if (type == GMScanAnimationTypeScanSkin) {
        return 2;
    } else if (type == GMScanAnimationTypeGeneMemory){
        return 0;
    }
    return 2;
}

- (GMScanAnimationType)getTypeWithIndex:(NSInteger)index {
    if (index == 1) {
        return GMScanAnimationTypeScanFace;
    } else if (index == 2) {
        return GMScanAnimationTypeScanSkin;
    } else if (index == 0){
        return GMScanAnimationTypeGeneMemory;
    }
    return GMScanAnimationTypeScanSkin;
}

// 改变按钮选中状态
-(void)btnChange:(NSInteger)tag {
    AudioServicesPlaySystemSound(1519);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (self.delegate && [self.delegate respondsToSelector:@selector(segmentViewItemDidSelected:)]) {
            [self.delegate segmentViewItemDidSelected:[self getTypeWithIndex:tag]];
            NSString *tabName = @"";
            NSInteger position = tag;
            if (tag == 0) {
                tabName = @"AI面孔";
                position = 3;
            } else if (tag == 1) {
                tabName = @"AI测脸";
            } else if (tag == 2) {
                tabName = @"AI测肤";
            }
            [Phobos track:@"on_click_tab" attributes:@{@"page_name": @"face_scan", @"position": @(position - 1),@"tab_name": tabName}];
        }
    });
}

#pragma mark - UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 3;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        return 2;
    } else if (section == 1) {
        return _dataSource.count;
    }
    return 2;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    GMfaceTypeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([GMfaceTypeCell class]) forIndexPath:indexPath];
    NSString *lastShowDate = [[NSUserDefaults standardUserDefaults] objectForKey:kShowedSkinDotView];
    NSString *currentDate = [[NSDate date] dateFormatToString];
    if (indexPath.section == 1) {
        if (indexPath.row == 2 && (!lastShowDate || ![currentDate isEqualToString:lastShowDate])) {
            _dotView = [[GMAIDotNotificationView alloc] init];
            [_dotView showWithSuperView:cell top:6 left:itemWidth - 7];
            [[NSUserDefaults standardUserDefaults] setObject:currentDate forKey:kShowedSkinDotView];
        }
        cell.isSelected = indexPath.row == 2;
        cell.titleLabel.text = _dataSource[indexPath.row];
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    GMfaceTypeCell *cell = (GMfaceTypeCell *)[collectionView cellForItemAtIndexPath:indexPath];
    if (cell.isSelected) {
        return;
    }
    [self btnChange:indexPath.row];
}

//动态设置每个Item的尺寸大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(itemWidth, itemHeight);
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (!decelerate) {
        [self btnChange: scrollView.contentOffset.x / itemWidth];
    }

}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    BOOL scrollToScrollStop = !scrollView.tracking && !scrollView.dragging && !scrollView.decelerating;
    if (scrollToScrollStop) {
        [self btnChange: scrollView.contentOffset.x / itemWidth];
    }
}

@end
