//
//  GMDiaryShareView.m
//  Gengmei
//
//  Created by yefengming on 2018/12/19.
//  Copyright © 2018年 更美互动信息科技有限公司. All rights reserved.
//

#import "GMDiaryShareView.h"
#import "GMDiaryShareInfoView.h"
#import "WMShareObject.h"
#import <MBProgressHUD/MBProgressHUD.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>


@interface GMDiaryShareView ()
@property (nonatomic, strong) GMView *bgView;
@property (nonatomic, strong) GMView *alphaView;
@property (nonatomic, strong) GMButton *closeButton;
@property (nonatomic, strong) GMView *infoView;
@property (nonatomic, strong) MBProgressHUD *hud;
@property (nonatomic, strong) GMView *bottomView;
@property (nonatomic, copy) NSString *shareUrl;
@end

@implementation GMDiaryShareView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _alphaView = [[GMView alloc]init];
        _alphaView.backgroundColor = [UIColor blackColor];
        _alphaView.alpha = 0.5;
        [self addSubview:_alphaView];
        _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];
        
        _topView = [[GMShareTopView alloc] init];
        [_bgView addSubview:_topView];
        
        _infoView = [[GMView alloc] init];
        [_bgView addSubview:_infoView];
        
        _bottomView = [[GMView alloc] init];
        _bottomView.backgroundColor = [UIColor whiteColor];
        [_bgView addSubview:_bottomView];
        
        [_alphaView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(0);
        }];
        
        [_bgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.bottom.mas_equalTo(0);
        }];
        
        [_closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_infoView.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);
        }];
        
        [_infoView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.bottom.mas_equalTo(_closeButton.mas_top);
            make.height.mas_equalTo(150);
        }];
        
        [_topView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.bottom.mas_equalTo(_infoView.mas_top).offset(11);
            make.top.mas_equalTo(0);
        }];
        [_topView updateSubtitleConstraintsWithBottom:-30];
        UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeButtonClicked:)];
        [_alphaView addGestureRecognizer:recognizer];
    }
    return self;
}

- (void)setDiaryArr:(NSMutableArray *)diaryArr {
    for (int i = 0; i < diaryArr.count; i++) {
        GMDiaryShareObject *object = diaryArr[i];
        GMDiaryShareInfoView *view = [[GMDiaryShareInfoView alloc] initWithFrame:CGRectMake(0, 50*i, MAINSCREEN_WIDTH, 50)];
        view.diaryNameLabel.text = object.title;
        [_infoView addSubview:view];
        __weak __typeof(self)weakSelf = self;
        [view setShareClickedBlcok:^{
            weakSelf.shareUrl = object.shareData.url;
            [weakSelf hideShareView];
            if ([weakSelf.delegate respondsToSelector:@selector(shareObject:)]) {
                [weakSelf.delegate shareObject:object.shareData];
            }
            [weakSelf shareWithType:GMSharePlatformWechatTimeline];
        }];
        if (i < diaryArr.count - 1) {
            [view addBottomLineWithLeft:20 right:-20];
        }
    }
    [_infoView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(diaryArr.count * 50);
    }];
}

- (void)shareWithType:(GMSharePlatform)type {
    if (![GMShareSDK isClientInstalled:type]) {
        [self toast:@"您未安装微信客户端"];
        return;
    }
    
    //获取定制的分享内容
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    if ([self.delegate respondsToSelector:@selector(fetchSharePublishContent:)]) {
        shareParams = [self.delegate fetchSharePublishContent:GMSharePlatformWechatTimeline];
    }
    
    [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];
                        }
                    }
                }
                break;
            }
            case GMShareResponseStateFail:{
//                debugLog(@"分享失败,错误描述:%@", error);
                break;
            }
            case GMShareResponseStateCancel:{
//                debugLog(@"取消分享");
                break;
            }
            default:
                break;
        }
    }];
}

// page_click_share_channel 埋点
- (void)phobosClickShareWithType:(GMSharePlatform)type {
    if ([self.delegate isKindOfClass:[UIResponder class]]) {
        UIResponder *phobosView = (UIResponder *)self.delegate;
        NSDictionary *dic = @{@"page_name": SafeValue(phobosView.pageName),
                              @"business_id": SafeValue(phobosView.businessId),
                              @"url": SafeValue(self.shareUrl),
                              @"share_channel": [self channel:type],
                              @"task_type":@"diary",
                              @"business":@"diary_id"
                              };
        [Phobos track:@"page_click_share_channel" attributes:dic];
    }
}

- (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;
        default:
            channel = @"";
            break;
    }
    return channel;
}

/** *  @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];
}

- (void)closeButtonClicked:(UIButton *)sender {
    [self hideShareView];
}

/**
 *  @brief  分享界面的有关动画
 添加上滑动画
 usingSpringWithDamping的范围为0.0f到1.0f，数值越小「弹簧」的振动效果越明显。
 initialSpringVelocity则表示初始的速度，数值越大一开始移动越快。
 http://www.renfei.org/blog/ios-8-spring-animation.html
 *
 */
- (void)showWithShareArr:(NSMutableArray *)shareArr {
    
    [self setDiaryArr:shareArr];
    
    self.frame = MAINSCREEN_FRAME;
    _bgView.top = MAINSCREEN_HEIGHT; //storyBoard中在屏幕中央，重置在屏幕最底下
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    
    [UIView animateWithDuration:0.25 delay:0.1 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
        
    } completion:nil];
    
    [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];
    }];
}

/** *  @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];
}

@end
