//
//  ALShareSheet.m
//  GMAlpha
//
//  Created by zhb on 2018/11/27.
//  Copyright © 2018 Gengmei. All rights reserved.
//

#import "ALShareSheet.h"

@interface ALShareItemCell : UICollectionViewCell
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UILabel *textLabel;
@end

@implementation ALShareItemCell
#pragma mark - life cycle
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self setup];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setup];
    }
    return self;
}

- (void)setup {
    self.backgroundColor = UIColor.whiteColor;
    [self addSubview:self.imageView];
    [self addSubview:self.textLabel];
    [self addLayouts];
}

- (void)addLayouts {
    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(35, 35));
        make.centerX.mas_equalTo(0);
    }];
    [self.textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.imageView.mas_bottom).offset(8);
        make.left.right.mas_equalTo(0);
    }];
}

#pragma mark - getters and setters
- (UIImageView *)imageView {
    if (_imageView == nil) {
        _imageView = [UIImageView new];
        _imageView.backgroundColor = UIColor.whiteColor;
    }
    return _imageView;
}

- (UILabel *)textLabel {
    if (_textLabel == nil) {
        _textLabel = [[UILabel alloc] init];
        _textLabel.textAlignment = NSTextAlignmentCenter;
        _textLabel.textColor = UIColor.auxiliaryTextLight;
        _textLabel.font = [UIFont gmFont:13];
    }
    return _textLabel;
}
@end

///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
////////////////////////// ALShareSheet ///////////////////////////////////
////////////////////////// ALShareSheet ///////////////////////////////////
///////////////////////////////////////////////////////////////////////////

@interface ALShareSheet ()<UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, strong) UIView *coverView;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) NSMutableArray *UIDataArray;
@property (nonatomic, strong) UIView *shareView;

@end

@implementation ALShareSheet
#pragma mark - life cycle
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self setup];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setup];
    }
    return self;
}

- (void)setup {
    
    self.frame = CGRectMake(0, 0, MAINSCREEN_WIDTH, MAINSCREEN_HEIGHT);
    
    [self addSubview:self.coverView];
    [self addSubview:self.shareView];
    
    [self.shareView addSubview:self.cancelButton];
    [self.shareView addSubview:self.lineView];
    [self.shareView addSubview:self.collectionView];
    [self addLayouts];
}

- (void)addLayouts {
    
    [self.shareView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-(UIView.safeAreaInsetsBottom));
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(0);
    }];
    
    [self.coverView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
        make.size.mas_equalTo(CGSizeMake(MAINSCREEN_WIDTH, MAINSCREEN_HEIGHT));
    }];
    [self.cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(0);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(50);
    }];
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.bottom.equalTo(self.cancelButton.mas_top);
        make.height.mas_equalTo(0.5);
    }];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.bottom.equalTo(self.lineView.mas_top);
        make.height.mas_equalTo(120);
    }];
}

#pragma makr - 对外使用
- (void)willMoveToSuperview:(UIView *)newSuperview {
    [super willMoveToSuperview:newSuperview];
    if (newSuperview == nil) return;
    [self.collectionView reloadData];
//    CGFloat height = self.collectionView.collectionViewLayout.collectionViewContentSize.height;
//    [self.collectionView mas_updateConstraints:^(MASConstraintMaker *make) {
//        make.height.mas_equalTo(height);
//    }];
    [self.collectionView.collectionViewLayout invalidateLayout];
    
}

- (void)show {
    
    [AppDelegate.shareInstance.window addSubview:self];
    self.coverView.hidden = NO;
    
    [self.shareView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(170);
    }];
    
    [UIView animateWithDuration:3.0f animations:^{
        [self setNeedsDisplay];
    }];
    
}

- (void)hide {
    self.coverView.hidden = YES;
    [self.shareView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(0);
    }];
    [UIView animateWithDuration:3.0f animations:^{
        [self setNeedsDisplay];
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

#pragma mark - system dataSource and delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.UIDataArray.count;
}
- (UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ALShareItemCell *itemCell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([ALShareItemCell class]) forIndexPath:indexPath];
    NSDictionary *uiDict = self.UIDataArray[indexPath.row];
    itemCell.imageView.image = [UIImage imageNamed:uiDict[@"img"]];
    itemCell.textLabel.text = uiDict[@"title"];
    return itemCell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    GMSharePlatform platform = GMSharePlatformUnknown;
    switch (indexPath.row) {
        case 0:
            platform = GMSharePlatformWechatSession;
            break;
        case 1:
            platform = GMSharePlatformSinaWeibo;
            break;
        case 2:
            platform = GMSharePlatformWechatTimeline;
            break;
        case 3:
            platform = GMSharePlatformQQFriend;
            break;
        default:
            platform = GMSharePlatformUnknown;
            break;
    }
    
    if (![GMShareSDK isClientInstalled:platform] &&
        (platform == GMSharePlatformWechatTimeline | platform == GMSharePlatformWechatSession)) {
        //QQ和新浪支持web分享，只有微信不支持，这里优化下提示语
        [GMHudModule toast:@"您未安装微信客户端"];
        return;
    }
    
    if (self.shareTypeBlock) {
        self.shareTypeBlock(platform);
    }
    [self hide];
}

#pragma mark -  事件
/** action : 背景 */
- (void)clickedCoverView:(UITapGestureRecognizer *)tap {
    [self hide];
}
/** action : 取消 */
- (void)clickedCancelButton:(UIButton *)sender {
    [self hide];
}


#pragma mark - getters and setters
- (UIView *)coverView {
    if (!_coverView) {
        _coverView = [[UIView alloc] init];
        _coverView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        _coverView.hidden = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickedCoverView:)];
        [_coverView addGestureRecognizer:tap];
    }
    return _coverView;
}

- (UIButton *)cancelButton {
    if (!_cancelButton) {
        _cancelButton = [[UIButton alloc] init];
        _cancelButton.backgroundColor = UIColor.whiteColor;
        [_cancelButton setTitleColor:RGBCOLOR_HEX(0x666666) forState:UIControlStateNormal];
        _cancelButton.titleLabel.font = [UIFont gmFont:16];
        [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelButton addTarget:self action:@selector(clickedCancelButton:) forControlEvents:UIControlEventTouchUpInside];
        [_cancelButton sizeToFit];
    }
    return _cancelButton;
}

- (UIView *)lineView {
    if (!_lineView) {
        _lineView = [[UIView alloc] init];
        _lineView.backgroundColor = RGBCOLOR_HEX(0xE5E5E5);
    }
    return _lineView;
}

- (UIView *)shareView {
    if (!_shareView) {
        _shareView = [[UIView alloc] init];
    }
    return _shareView;
}

- (UICollectionViewFlowLayout *)flowLayout {
    if (_flowLayout == nil) {
        _flowLayout = [[UICollectionViewFlowLayout alloc] init];
        _flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _flowLayout.itemSize = CGSizeMake(self.itemW, self.itemH);
        _flowLayout.sectionInset = UIEdgeInsetsMake(self.topM, self.leftM, self.bottomM, self.rightM);
        _flowLayout.minimumLineSpacing = 0;
        _flowLayout.minimumInteritemSpacing = self.colSpacing;
    }
    return _flowLayout;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.flowLayout];
        _collectionView.backgroundColor = UIColor.whiteColor;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        [_collectionView registerClass:[ALShareItemCell class] forCellWithReuseIdentifier:NSStringFromClass([ALShareItemCell class])];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    }
    return _collectionView;
}

- (NSMutableArray *)UIDataArray {
    if (!_UIDataArray) {
        _UIDataArray = [NSMutableArray array];
        NSString *imgName1 = @"share_chat";
        NSString *imgName2 = @"share_sina";
        NSString *imgName3 = @"share_friend";
        NSString *imgName4 = @"share_qq";
        NSString *title1 = @"微信";
        NSString *title2 = @"微博";
        NSString *title3 = @"朋友圈";
        NSString *title4 = @"QQ";
        [_UIDataArray addObject:@{@"img": imgName1, @"title": title1}];
        [_UIDataArray addObject:@{@"img": imgName2, @"title": title2}];
        [_UIDataArray addObject:@{@"img": imgName3, @"title": title3}];
        [_UIDataArray addObject:@{@"img": imgName4, @"title": title4}];
    }
    return _UIDataArray;
}



- (CGFloat)topM {
    return 30;
}
- (CGFloat)leftM {
    return 40;
}
- (CGFloat)bottomM {
    return 30;
}
- (CGFloat)rightM {
    return 40;
}
- (CGFloat)itemW {
    return 43;
}
- (CGFloat)itemH {
    return 60;
}

/** 列间距*/
- (CGFloat)colSpacing {
    return  ((MAINSCREEN_WIDTH - self.leftM - self.rightM) - self.itemW * 4.0) / 3;
}

@end



//- (UIView *)contentView {
//    if (!_contentView) {
//        _contentView = [[UIView alloc] init];
//        _contentView.backgroundColor = UIColor.whiteColor;
//    }
//    return _contentView;
//}
