//
//  WMShareView.m
//  Gengmei
//
//  Created by Sean Lee on 1/22/15.
//  Copyright (c) 2015 Wanmeichuangyi. All rights reserved.
//

#import "GMShareView.h"
#import <MBProgressHUD/MBProgressHUD.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import "GMShareFlowLayout.h"
#import "DouyinOpenSDKApi.h"
#import <WechatOpenSDK/WXApi.h>
#import <WeiboSDK/WeiboSDK.h>
#import "GMShareVideoAlertView.h"
#import <GMShareSDK/GMShareSDK.h>
#import <GMKit/GMButton.h>
#import <GMKit/GMLabel.h>
#import <GMPhobos/Phobos.h>
#import <GMPhobos/UIResponder+PhobosPV.h>

#import <GMKit/UIColor+GMTheme.h>
#import <GMKit/Constant.h>
#import <GMKit/GMFont.h>
#import <GMKit/Constant.h>
#import <GMKit/UIView+LineWithAutolayout.h>
#import <GMKit/GMCollectionView.h>
#import <GMFoundation/NSString+GM.h>
#import <GMKit/UIView+SafeArea.h>
#import <GMKit/GMSafeValue.h>
#import <GMKit/UIView+Layout.h>
//#import <GMShareSDK/GMShareSDK-umbrella.h>

//@import GMPhobos;

static NSString *shareCellIdentifier = @"shareCellIdentifier";

@interface GMShareView ()<UICollectionViewDelegate, UICollectionViewDataSource, UIGestureRecognizerDelegate>
@property (nonatomic, strong) MBProgressHUD *hud;
@property (nonatomic, strong) NSMutableArray *titleArray;
@property (nonatomic, strong) NSMutableArray *imageArray;
@property (nonatomic, strong) NSMutableArray *shareTypeArray;
@property (nonatomic, strong) GMButton *closeButton;
@property (nonatomic, strong) GMView *bottomView;
@end

@implementation GMShareView

- (void)setup{
    [super setup];
    
    _titleArray = [@[@"微信快照",
                     @"朋友圈快照",
                     @"抖音",
                     @"微信好友",
                     @"朋友圈",
                     @"QQ",
                     @"新浪微博",
                     @"QQ空间",
                     @"邀请回复",
                     @"收藏",
                     @"删除",
                     @"复制链接",
                     @"举报",
                     @"刷新",
                     @"取消关注"] mutableCopy];
    _imageArray = [@[@"share_wechat_session_snapshot",
                     @"share_wechat_timeline_snapshot",
                     @"share_douyin",
                     @"share_weixin_session",
                     @"share_weixin_timeline",
                     @"share_qq",
                     @"share_sina_weibo",
                     @"share_qq_space",
                     @"share_invite_answer",
                     @"share_fav_nor",
                     @"share_delete",
                     @"copy_link",
                     @"report",
                     @"refresh_web",
                     @"cancel_follow"] mutableCopy];
    _shareTypeArray = [@[@(GMSharePlatformWechatSessionSnapShot),
                         @(GMSharePlatformWechatTimelineSnapShot),
                         @(GMSharePlatformDouyin),
                         @(GMSharePlatformWechatSession),
                         @(GMSharePlatformWechatTimeline),
                         @(GMSharePlatformQQFriend),
                         @(GMSharePlatformSinaWeibo),
                         @(GMSharePlatformQQSpace),
                         @(GMSharePlatformInviteAnswer),
                         @(GMSharePlatformFav),
                         @(GMSharePlatformDelete),
                         @(GMSharePlatformCopyLink),
                         @(GMSharePlatformReport),
                         @(GMSharePlatformRefresh),
                         @(GMSharePlatformCancelFollow)] mutableCopy];
    self.showCopyLink = YES;
    self.showRefresh = YES;
    
    _bgView = [[GMView alloc]init];
    [self addSubview:_bgView];
    
    _closeButton = [GMButton buttonWithType:UIButtonTypeCustom];
    _closeButton.backgroundColor = [UIColor whiteColor];
    [_closeButton setTitleColor:UIColor.headlineText forState:UIControlStateNormal];
    [_closeButton setTitle:@"取消" forState: UIControlStateNormal];
    _closeButton.titleLabel.font = [UIFont gmFont:16];
    [_closeButton addTarget:self action:@selector(closeButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [_bgView addSubview:_closeButton];
    [_closeButton addTopLine];

    _shareCollectionView = [[GMCollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:[GMShareFlowLayout new]];
    [_shareCollectionView setBackgroundColor:UIColor.whiteColor];
    [_shareCollectionView setDataSource:self];
    [_shareCollectionView setDelegate:self];
    [_shareCollectionView setScrollEnabled:NO];
    _shareCollectionView.delegate= self;
    _shareCollectionView.dataSource = self;
    _shareCollectionView.backgroundColor = [UIColor whiteColor];
    [_shareCollectionView registerClass:[GMShareCell class] forCellWithReuseIdentifier:shareCellIdentifier];
    [_bgView addSubview:_shareCollectionView];
    
    _topLineView = [GMView new];
    _topLineView.backgroundColor = UIColor.separatorLine;
    [_bgView addSubview:_topLineView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideShareView)];
    tap.delegate = self;
    [self addGestureRecognizer:tap];
    
    _topView = [[GMShareTopView alloc] init];
    [_bgView addSubview:_topView];
    _topView.hidden = YES;
    
    _bottomView = [[GMView alloc] init];
    _bottomView.backgroundColor = [UIColor whiteColor];
    [_bgView addSubview:_bottomView];
}

- (void)updateTitleArray {
    if (!_showDelete) {
        [_titleArray removeObject:@"删除"];
        [_imageArray removeObject:@"share_delete"];
        [_shareTypeArray removeObject:@(GMSharePlatformDelete)];
    }
    
    if (!_showFavor) {
        [_titleArray removeObject:@"收藏"];
        [_imageArray removeObject:@"share_fav_nor"];
        [_shareTypeArray removeObject:@(GMSharePlatformFav)];
    }
    
    if (!_showReport) {
        [_titleArray removeObject:@"举报"];
        [_imageArray removeObject:@"report"];
        [_shareTypeArray removeObject:@(GMSharePlatformReport)];
    }
    
    if (!_showCancelFollow) {
        [_titleArray removeObject:@"取消关注"];
        [_imageArray removeObject:@"quxiaoguanzhu"];
        [_shareTypeArray removeObject:@(GMSharePlatformCancelFollow)];
    }
    
    if (!_showCopyLink) {
        [_titleArray removeObject:@"复制链接"];
        [_imageArray removeObject:@"copy_link"];
        [_shareTypeArray removeObject:@(GMSharePlatformCopyLink)];
    }
    
    if (!_showRefresh) {
        [_titleArray removeObject:@"刷新"];
        [_imageArray removeObject:@"refresh_web"];
        [_shareTypeArray removeObject:@(GMSharePlatformRefresh)];
    }
    
//    BOOL isWXAppInstalled =  [GMShareSDK isClientInstalled:GMSharePlatformWechatSessionSnapShot] || [GMShareSDK isClientInstalled:GMSharePlatformWechatTimelineSnapShot] || [GMShareSDK isClientInstalled:GMSharePlatformWechat]
    if (!_showScreenshot || (![WXApi isWXAppInstalled])) {
        [_titleArray removeObject:@"微信快照"];
        [_imageArray removeObject:@"share_wechat_session_snapshot"];
        [_shareTypeArray removeObject:@(GMSharePlatformWechatSessionSnapShot)];
        [_titleArray removeObject:@"朋友圈快照"];
        [_imageArray removeObject:@"share_wechat_timeline_snapshot"];
        [_shareTypeArray removeObject:@(GMSharePlatformWechatTimelineSnapShot)];
    }
    
    if (!_showInviteAnswer) {
        [_titleArray removeObject:@"邀请回复"];
        [_imageArray removeObject:@"share_invite_answer"];
        [_shareTypeArray removeObject:@(GMSharePlatformInviteAnswer)];
    }
    
    if ((!_shareObject.qq.title.isNonEmpty || ((!_shareObject.qq.content.isNonEmpty) && _shareObject != nil)) || (![QQApiInterface isQQInstalled])) {
        [_titleArray removeObject:@"QQ"];
        [_imageArray removeObject:@"share_qq"];
        [_shareTypeArray removeObject:@(GMSharePlatformQQFriend)];
    }
    
    
    
    if (!_shareObject.qqzone.title.isNonEmpty || ((!_shareObject.qqzone.content.isNonEmpty) && _shareObject != nil) || ![QQApiInterface isQQInstalled]) {
        [_titleArray removeObject:@"QQ空间"];
        [_imageArray removeObject:@"share_qq_space"];
        [_shareTypeArray removeObject:@(GMSharePlatformQQSpace)];
    }
    if ((_shareObject.douyin == nil && _shareObject != nil) || ![DouyinOpenSDKApi isAppInstalled]) {
        [_titleArray removeObject:@"抖音"];
        [_imageArray removeObject:@"share_douyin"];
        [_shareTypeArray removeObject:@(GMSharePlatformDouyin)];
    }
    
    if ((_shareObject.wechatline == nil && _shareObject != nil) || (![WXApi isWXAppInstalled])) {
        [_titleArray removeObject:@"朋友圈"];
        [_imageArray removeObject:@"share_weixin_timeline"];
        [_shareTypeArray removeObject:@(GMSharePlatformWechatTimeline)];
    }
    
    if ((_shareObject.wechat == nil && _shareObject.wechatmini == nil && _shareObject != nil) || (![WXApi isWXAppInstalled])) {
        [_titleArray removeObject:@"微信好友"];
        [_imageArray removeObject:@"share_weixin_session"];
        [_shareTypeArray removeObject:@(GMSharePlatformWechatSession)];
    }
    
    if ((_shareObject.weibo == nil && _shareObject != nil) || ![WeiboSDK isWeiboAppInstalled]) {
        [_titleArray removeObject:@"新浪微博"];
        [_imageArray removeObject:@"share_sina_weibo"];
        [_shareTypeArray removeObject:@(GMSharePlatformSinaWeibo)];
    }
    
    [_topLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        if (_titleArray.count / 5.0 >= 1) {
            make.height.mas_equalTo(ONE_PIXEL);
        } else {
            make.height.mas_equalTo(0);
        }
        make.top.mas_equalTo(_shareCollectionView).offset(217/2.0);
    }];
}

- (void)updateConstraints{
    [_bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    
    [_shareCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(435/2.0);
        if (_topView.hidden) {
            make.top.mas_equalTo(0);
        }
    }];
    
    [_closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_shareCollectionView.mas_bottom);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(45);
        make.bottom.mas_equalTo(-UIView.safeAreaInsetsBottom);
    }];
    
    [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(UIView.safeAreaInsetsBottom);
    }];
    
    if (!_topView.hidden) {
        [_topView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.bottom.mas_equalTo(_shareCollectionView.mas_top).offset(11);
            make.top.mas_equalTo(0);
        }];
        [_topView updateSubtitleConstraintsWithBottom:-11];
    }
    [super updateConstraints];
}

#pragma mark - Collection View

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    [self updateTitleArray];
    return _titleArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    GMShareCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:shareCellIdentifier forIndexPath:indexPath];
    cell.transferResponseChainBlock = ^{
        [self collectionView:collectionView didSelectItemAtIndexPath:indexPath];
    };
    [cell.shareButton setTitle:_titleArray[indexPath.row] forState:UIControlStateNormal];
    [cell.shareButton setImage:[UIImage imageNamed:_imageArray[indexPath.row]] forState:UIControlStateNormal];
    cell.shareType = [_shareTypeArray[indexPath.row] integerValue];
    if (cell.shareType == GMSharePlatformFav){
        [cell.shareButton setImage:[UIImage imageNamed:@"share_fav_pre"] forState:UIControlStateSelected];
        cell.shareButton.selected = _hasFav;
    }
       return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    [self hideShareView];
    
    GMShareCell * cell = (GMShareCell *) [collectionView cellForItemAtIndexPath:indexPath];
    
    if (cell.shareType == GMSharePlatformFav) {
        if ([self.delegate respondsToSelector:@selector(shareView:favriteContentWithIndexPath:)]) {
            [self.delegate shareView:self favriteContentWithIndexPath:indexPath];
        }
    }else if (cell.shareType == GMSharePlatformDelete) {
        //删除前提示用户是否需要删除
        if ([self.delegate respondsToSelector:@selector(deleteContent)]) {
            [self.delegate deleteContent];
        }
    }else if (cell.shareType == GMSharePlatformReport) {
        if ([self.delegate respondsToSelector:@selector(showReport)]) {
            [self.delegate showReport];
        }
    }else if (cell.shareType == GMSharePlatformRefresh) {
        if ([self.delegate respondsToSelector:@selector(refreshWebView)]) {
            [self.delegate refreshWebView];
        }
    }else if (cell.shareType == GMSharePlatformCopyLink) {
        if ([self.delegate respondsToSelector:@selector(copyShareUrl)]) {
            [self.delegate copyShareUrl];
        }
        [self phobosClickShareWithType:cell.shareType];
    }else if (cell.shareType == GMSharePlatformCancelFollow) {
        if ([self.delegate respondsToSelector:@selector(unFollowZone)]) {
            [self.delegate unFollowZone];
        }
    }else if (cell.shareType == GMSharePlatformInviteAnswer) {
        if ([self.delegate respondsToSelector:@selector(inviteAnswer)]) {
            [self.delegate inviteAnswer];
        }
    }else {
        if ([self.delegate respondsToSelector:@selector(shareVideo:)]) {
            [self.delegate shareVideo:cell.shareType];
        } else {
            [self shareWithType:cell.shareType];
        }
    }
}


- (void)layoutSubviews{
    [super layoutSubviews];
    [_shareCollectionView layoutIfNeeded];
    [_shareCollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(_shareCollectionView.contentSize.height);
    }];
}

#pragma mark - 公开方法
- (void)shareWithType:(GMSharePlatform)type {
    
    if (![GMShareSDK isClientInstalled:type] && (type == GMSharePlatformWechatTimeline | type == GMSharePlatformWechatSession | type == GMSharePlatformWechatSessionSnapShot | type == GMSharePlatformWechatTimelineSnapShot)) {
        //QQ和新浪支持web分享，只有微信不支持，这里优化下提示语
        [self toast:@"您未安装微信客户端"];
        return;
    }

    // 抖音
    if (type == GMSharePlatformDouyin) {
        if (![GMShareSDK isClientInstalled:type]) {
            //判断是否安装抖音
            [self toast:@"您未安装抖音"];
            return;
        }
        if (![DouyinOpenSDKApi isAppSupportShare]) {
            //判断抖音是不是支持分享
            [self toast:@"您安装的抖音版本不支持分享"];
            return;
        }
    }
    
    // 当是分享视频，并且是分享到朋友圈时，需要弹起弹窗
    if (_shareObject.videoUrl.isNonEmpty && type == GMSharePlatformWechatTimeline) {
        [self phobosClickShareWithType:type]; // 添加埋点数据
        [GMShareVideoAlertView showNoticeAtertViewWithConfirmBtnClickBlock:^{
            // 调起微信
            [WXApi openWXApp];
        }];
        return;
    }
    
    [self goToShareWithType:type];
    
}

- (void)goToShareWithType:(GMSharePlatform)type {
    //获取定制的分享内容
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    if ([self.delegate respondsToSelector:@selector(fetchSharePublishContent:)]) {
        shareParams = [self.delegate fetchSharePublishContent:type];
    }
    
    [self phobosClickShareWithType:type];
    
    [[GMShareSDK shareInstance] share: type parameters:[shareParams mutableCopy] onStateChanged:^(GMShareResponseState state, NSError *error) {
        switch (state) {
            case GMShareResponseStateBegin:{
//                debugLog(@"启动分享");
                break;
            }
            case GMShareResponseStateSuccess:{
//                debugLog(@"分享成功");
                if (self) {
                    if (self.delegate != nil && ![self.delegate isKindOfClass:[NSNull class]]) {
                        if ([self.delegate respondsToSelector:@selector(shareResponseSuccess)]) {
                            [self.delegate shareResponseSuccess];
                        }
                    }
                }
                if ([self.delegate isKindOfClass:[UIResponder class]] && self.isReportShareResult) {
                    UIResponder *phobosView = (UIResponder *)self.delegate;
                    NSDictionary *dic = @{@"page_name": SafeValue(phobosView.pageName),
                                          @"share_channel": [self channel:type]};
                    [Phobos track:@"share_success_statistics" attributes:dic];
                }
                break;
            }
            case GMShareResponseStateFail:{
//                debugLog(@"分享失败,错误描述:%@", error);
                break;
            }
            case GMShareResponseStateCancel:{
//                debugLog(@"取消分享");
                break;
            }
            default:
                break;
        }
    }];
}

- (NSString *)channel:(GMSharePlatform)type {
    NSString *channel = @"";
    switch (type) {
        case GMSharePlatformWechatSession:
            channel = @"wechat";
            break;
        case GMSharePlatformWechatTimeline:
            channel = @"wechatline";
            break;
        case GMSharePlatformQQFriend:
            channel = @"qq";
            break;
        case GMSharePlatformQQSpace:
            channel = @"qzone";
            break;
        case GMSharePlatformSinaWeibo:
            channel = @"tsina";
            break;
        case GMSharePlatformWechatSessionSnapShot:
            channel = @"wechat_snapshot";
            break;
        case GMSharePlatformWechatTimelineSnapShot:
            channel = @"wechatline_snapshot";
            break;
        case GMSharePlatformCopyLink:
            channel = @"copy_url";
            break;
        case GMSharePlatformDouyin:
            channel = @"douyin";
            break;
        default:
            channel = @"";
            break;
    }
    return channel;
}

- (void)dealloc {
    
}

/**
 *  @brief  分享界面的有关动画
     添加上滑动画
     usingSpringWithDamping的范围为0.0f到1.0f，数值越小「弹簧」的振动效果越明显。
     initialSpringVelocity则表示初始的速度，数值越大一开始移动越快。
     http://www.renfei.org/blog/ios-8-spring-animation.html
 *
 */
- (void)showWithShareUrl:(NSString *)shareUrl {
    self.shareUrl = shareUrl;
    if ([self.delegate respondsToSelector:@selector(willShowShareView:)]) {
        [self.delegate willShowShareView:self];
    }
    [self phobosClickShare];

    self.frame = MAINSCREEN_FRAME;
    _bgView.top = MAINSCREEN_HEIGHT; //storyBoard中在屏幕中央，重置在屏幕最底下
//    [[UIApplication sharedApplication].keyWindow addSubview:self];  // 用这个方法偶尔会出现bug,用下面方法替换
    [[UIApplication sharedApplication].keyWindow addSubview:self];

    self.backgroundColor = UIColor.clearColor;
    [UIView animateWithDuration:0.25 animations:^{
        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
    }];
    [UIView animateWithDuration:0.25 animations:^{
        _bgView.top = _bgView.height;
    }];
}

- (void)hideShareView{
    [UIView animateWithDuration:0.25 animations:^{
        _bgView.top = MAINSCREEN_HEIGHT;
        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

#pragma mark - 埋点
// 弹出分享框埋点
- (void)phobosClickShare {
    if ([self.delegate isKindOfClass:[UIResponder class]]) {
        NSAssert([self.shareUrl isNonEmpty], @"shareView.shareUrl 不应该为空");
        UIResponder *phobosView = (UIResponder *)self.delegate;
        NSString *businessId = SafeValue(phobosView.businessId);
        if ([self.delegate respondsToSelector:@selector(shareViewNeedBusinessId)]) {
            businessId = [self.delegate shareViewNeedBusinessId];
        }
        NSDictionary *dic = @{@"page_name": SafeValue(phobosView.pageName),
                              @"business_id": SafeValue(businessId),
                              @"url": SafeValue(self.shareUrl)};
        [Phobos track:@"page_click_share" attributes:dic];
    }
}

// page_click_share_channel 埋点
- (void)phobosClickShareWithType:(GMSharePlatform)type {
    if ([self.delegate isKindOfClass:[UIResponder class]]) {
        UIResponder *phobosView = (UIResponder *)self.delegate;
        NSString *businessId = SafeValue(phobosView.businessId);
        if ([self.delegate respondsToSelector:@selector(shareViewNeedBusinessId)]) {
            businessId = [self.delegate shareViewNeedBusinessId];
        }
        NSAssert([self.shareUrl isNonEmpty], @"shareView.shareUrl 不应该为空");
        NSDictionary *dic = @{@"page_name": SafeValue(phobosView.pageName),
                              @"business_id": SafeValue(businessId),
                              @"url": SafeValue(self.shareUrl),
                              @"share_channel": [self channel:type],
                              @"task_type":SafeValue(self.taskType),
                              @"business":@"channel"};
        [Phobos track:@"page_click_share_channel" attributes:dic];
    }
}

#pragma mark - Toast

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    if ([gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]]){
        CGPoint point = [gestureRecognizer locationInView:self];
        if (CGRectContainsPoint(_bgView.frame, point)) {
            return NO;
        }else{
            return YES;
        }
    }
    return YES;
}

/** *  @brief  分享结果提示*/
- (void)toast:(NSString *)text{
    
    [_hud hide:YES];
    MBProgressHUD *hudProgrss = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hudProgrss.mode = MBProgressHUDModeText;
    hudProgrss.userInteractionEnabled = NO;
    hudProgrss.labelText = text;
    hudProgrss.removeFromSuperViewOnHide = YES;
    [hudProgrss hide:YES afterDelay:1.0];
}
/** *  @brief  分享启动提示*/
- (void)showLoading:(NSString *)text
{
    _hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    _hud.mode = MBProgressHUDModeIndeterminate;
    _hud.userInteractionEnabled = YES;
    _hud.labelText = text;
    _hud.margin = 10.f;
    _hud.removeFromSuperViewOnHide = YES;
    [_hud show:YES];
}

- (void)hideLoading{
    [_hud hide:YES];
}

#pragma mark - Action
- (IBAction)closeButtonClicked:(id)button {
    if ([self.delegate respondsToSelector:@selector(cancleShareView)]) {
        [self.delegate cancleShareView];
    }
    [self hideShareView];
}

@end
