//
//  WMWeixinShareView.m
//  Gengmei
//
//  Created by Sean Lee on 7/6/15.
//  Copyright (c) 2015 Wanmeichuangyi. All rights reserved.
//

#import "GMWeixinShareView.h"
#import "NSMutableDictionary+GMShareSDK.h"
#import "GMShareSDK.h"

@interface GMWeixinShareView ()
@property (weak, nonatomic) IBOutlet UITapGestureRecognizer *tapGestureRecognizer;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *shareViewBottomConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *shareViewHeight;
@end


@implementation GMWeixinShareView
+ (GMWeixinShareView *)shareView{
    GMWeixinShareView *shareView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([GMWeixinShareView class]) owner:nil options:nil].firstObject;
    shareView.shareViewHeight.constant = [UIDevice resolutionType] == iPhone58Inches ? 184 : 150;
    return shareView;
}

- (NSMutableDictionary *)shareContentWithShareType:(GMSharePlatform)shareType{
    WMShareBasicObject * object = [WMShareBasicObject new];
    //对于微信分享数据，只从js注册的方法通过参数里获取
    if (shareType == GMSharePlatformWechatSession) {
        object = self.weixinShareObject.wechat;
    }else if (shareType == GMSharePlatformWechatTimeline){
        object = self.weixinShareObject.wechatline;
    }
    NSString *title = object.title;
    NSString *content = object.content;
    NSString *url = self.weixinShareObject.url;
    NSString *image = self.weixinShareObject.image;

    UIImage *shareImage = nil;
    if (image.length != 0) {
        shareImage = [GMShareSDK compressWithUrl:image];
    }else{
        // 使用app logo做图标
        shareImage = [UIImage imageNamed:@"icon"];
    }

    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    [shareParams shareSetupShareParamsByText:content
                                      images:shareImage
                                         url:[NSURL URLWithString:url]
                                       title:title
                                        type:GMShareContentTypeAuto];
    return shareParams;
}

- (IBAction)shareButtonClicked:(UIButton *)button{
    [self hideShareView:nil];
    GMSharePlatform type = (GMSharePlatform)button.tag;
    //分享埋点
    [self weixin_click_share_channel:type];
    
    if (![GMShareSDK isClientInstalled:type] && (type == GMSharePlatformWechatTimeline | type == GMSharePlatformWechatSession)) {
        //QQ和新浪支持web分享，只有微信不支持，这里优化下提示语
        [self.sourceController toast:@"您未安装微信客户端"];
        return;
    }
    __block NSString *toast = @"";
    NSDictionary *shareParams = [self shareContentWithShareType:type];
    NSString * typeString = nil;
    if(type == GMSharePlatformWechatSession) {
        typeString = @"wechatSession";
    }else if(type == GMSharePlatformWechatTimeline){
        typeString = @"wechatTimeline";
    }
    [[GMShareSDK shareInstance] share: type parameters:[shareParams mutableCopy] onStateChanged:^(GMShareResponseState state, NSError *error) {
        switch (state) {
            case GMShareResponseStateBegin:{
                debugLog(@"启动分享");
                break;
            }
            case GMShareResponseStateSuccess:{
                toast = @"分享成功";
                debugLog(@"分享成功");
                break;
            }
            case GMShareResponseStateFail:{
                toast = @"分享失败";
                debugLog(@"分享失败,错误描述:%@", error);
                break;
            }
            case GMShareResponseStateCancel:{
                toast = @"取消分享";
                debugLog(@"取消分享");
                break;
            }
            default:
                break;
        }
        // 只有分享成功时把状态码1传给h5
        NSNumber *jsState = state == GMShareResponseStateSuccess ? @1 : @0;
        NSData *jsParamData  = [NSJSONSerialization dataWithJSONObject:@{@"type" : typeString ,@"state" : jsState} options:0 error:NULL];
        NSString *jsParam = [[NSString alloc] initWithData:jsParamData encoding:NSUTF8StringEncoding];
        NSString *jsString = [NSString stringWithFormat:@"gm.util.wechatShare('%@')",jsParam];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [self.sourceController.webView stringByEvaluatingJavaScriptFromString:jsString];
            [self.sourceController toast:toast];
        });
    }];
}

- (void)showShareView:(id)sender {
    self.hidden = NO;
    self.tapGestureRecognizer.enabled = YES;
    [UIView animateWithDuration:0.25 animations:^{
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];
        self.shareViewBottomConstraint.constant = [UIDevice resolutionType] == iPhone58Inches ? 184 : 150;
        [self layoutIfNeeded];
    }];
}

- (IBAction)hideShareView:(id)sender {
    self.tapGestureRecognizer.enabled = NO;
    [UIView animateWithDuration:0.25 animations:^{
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
        self.shareViewBottomConstraint.constant = 0;
        [self layoutIfNeeded];
    } completion:^(BOOL finished) {
        self.hidden = YES;
    }];
}
//埋点
- (void)weixin_click_share_channel:(NSInteger)type {
    //type 3-微信好友, 4-朋友圈
    [Phobos track:@"weixin_click_share_channel" attributes:@{
            @"share_channel" : type == 3 ? @"微信好友" : @"朋友圈",
            @"from" : self.weixinShareObject.from.isNonEmpty ? self.weixinShareObject.from : @""}];
}

@end
