//
//  GMShareSDK.m
//  Gengmei
//
//  Created by licong on 2017/8/16.
//  Copyright © 2017年 更美互动信息科技有限公司. All rights reserved.
//

#import "GMShareSDK.h"
//#import <Weibo_SDK/WeiboSDK.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterfaceObject.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import "WXApiObject.h"
#import "GMThirdPartyOauthManager.h"
#import "GMThirdPartyDefine.h"
#import "WeiboSDK.h"
#import <GMKit/UIImage+GM.h>
@interface GMShareSDK ()<WBMediaTransferProtocol>

@property (nonatomic, strong) WBMessageObject *messageObject;

@end

@implementation GMShareSDK

+ (instancetype)shareInstance
{
    static dispatch_once_t onceToken;
    static id instance = nil;
    dispatch_once(&onceToken, ^{
        instance = [[[self class] alloc] init];
    });
    return instance;
}


+ (BOOL)isClientInstalled:(GMSharePlatform)platformType{
    
    if (platformType == GMSharePlatformQQ) {
        return [QQApiInterface isQQInstalled] ? YES : NO;
    } else if (platformType == GMSharePlatformWechatTimeline | platformType == GMSharePlatformWechatSession | GMSharePlatformWechat) {
        return [WXApi isWXAppInstalled] ? YES : NO;
    } else if (platformType == GMSharePlatformSinaWeibo){
        return [WeiboSDK isWeiboAppInstalled] ? YES : NO;
    } else{
        return YES;
    }
}

// 获取分享平台渠道（H5 埋点使用）
+ (NSString *)shareChannel:(GMSharePlatform)platformType {
    switch (platformType) {
        case GMSharePlatformQQFriend:{
            return @"QQ";
        }
            break;
        case GMSharePlatformQQSpace:{
            return @"QZone";
            break;
        }
        case GMSharePlatformWechatSession:{
            return @"Wechat";
            break;
        }
        case GMSharePlatformWechatTimeline:{
            return @"WechatMoments";
            break;
        }
        case GMSharePlatformWechatSessionSnapShot:{
            return @"Wechat";
            break;
        }
        case GMSharePlatformWechatTimelineSnapShot:{
            return @"WechatMoments";
            break;
        }
        case GMSharePlatformWechatMiniProgram:{
            return @"WechatMiniProgram";
            break;
        }
        case GMSharePlatformSinaWeibo:{
            return @"SinaWeibo";
            break;
        }
        default:
            return @"Default";
            break;
    }
}

+ (UIImage *)compressWithUrl:(NSString *)url{
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:1.5];
    NSURLResponse *response = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    UIImage* image = [UIImage imageWithData: data];
    //如果远程的图片下载不下来，则使用默认图
    if (image == nil) {
        image = [UIImage imageNamed:@"AppIcon"];
    }
    image = [GMShareSDK compressImage:image];
    return image;
}

+ (UIImage *)compressImage:(UIImage *)image{
    // 图片下载成功后，分享到微信的图片不能太大
    if (image.size.width * image.size.height>  300 * 300) {
        CGFloat scale =  sqrt(300 * 300 / (image.size.width * image.size.height));
        image = [image resizedImageWithSize:CGSizeMake(image.size.width * scale, image.size.height * scale)];
    }
    return image;
}

- (void)share:(GMSharePlatform)platformType parameters:(NSMutableDictionary *)parameters onStateChanged:(GMSDKShareStateChangedHandler)stateChangedHandler {
    GMShareContentType contentType = (GMShareContentType)[parameters[@"type"] integerValue];
    if (contentType == GMShareContentTypeMiniProgram) {
        platformType = GMSharePlatformWechatMiniProgram;
    }
    switch (platformType) {
        case GMSharePlatformQQFriend:{
            [self QQFriendShareWithParameters:parameters];
            [self shareWithName:kQQShare onStateChanged:stateChangedHandler];
        }
            break;
        case GMSharePlatformQQSpace:{
            [self QQSpaceShareWithParameters:parameters];
            [self shareWithName:kQQShare onStateChanged:stateChangedHandler];
            break;
        }
        case GMSharePlatformWechatSession:{
            [self wechatSessionShareWithParameters:parameters scene:WXSceneSession];
            [self shareWithName:kWechatShare onStateChanged:stateChangedHandler];
            break;
        }
        case GMSharePlatformWechatTimeline:{
            [self wechatSessionShareWithParameters:parameters scene:WXSceneTimeline];
            [self shareWithName:kWechatShare onStateChanged:stateChangedHandler];
            break;
        }
        case GMSharePlatformWechatSessionSnapShot:{
            [self wechatSessionShareWithParameters:parameters scene:WXSceneSession];
            [self shareWithName:kWechatShare onStateChanged:stateChangedHandler];
            break;
        }
        case GMSharePlatformWechatTimelineSnapShot:{
            [self wechatSessionShareWithParameters:parameters scene:WXSceneTimeline];
            [self shareWithName:kWechatShare onStateChanged:stateChangedHandler];
            break;
        }
        case GMSharePlatformWechatMiniProgram:{
            [self wechatSessionShareWithParameters:parameters scene:WXSceneSession];
            [self shareWithName:kWechatShare onStateChanged:stateChangedHandler];
            break;
        }
        case GMSharePlatformSinaWeibo:{
            [self weiboShareWithParameters:parameters];
            [self shareWithName:kSinaShare onStateChanged:stateChangedHandler];
            break;
        }
        default:
            break;
    }
}

- (void)shareWithName:(NSString *)name onStateChanged:(GMSDKShareStateChangedHandler)stateChangedHandler {
    __block id observer = [[NSNotificationCenter defaultCenter] addObserverForName:name object:nil queue: [NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        GMShareResponseState state = (GMShareResponseState )[note.userInfo[@"state"] integerValue];
        stateChangedHandler(state, nil);
        [[NSNotificationCenter defaultCenter] removeObserver:observer];
    }];
}

/**
    只分享一张图片
 */
- (void)shareImage:(UIImage *)image platform:(GMSharePlatform)platformType {
    switch (platformType) {
        case GMSharePlatformQQFriend: {
            [self QQFriendShareWithImage:image];
        }
            break;

        case GMSharePlatformWechatSession: {
            [self wechatImageShareWithParameters:@{@"images": image} scene:WXSceneSession];
        }
            break;
            
        case GMSharePlatformWechatTimeline:{
            [self wechatImageShareWithParameters:@{@"images": image} scene:WXSceneTimeline];
        }
            break;
         
        case GMSharePlatformSinaWeibo:{
            [self weiboShareWithParameters:@{@"images": image}];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark -- QQShare

- (void)QQFriendShareWithImage:(UIImage *)image {
    QQApiImageObject *imgObj = [QQApiImageObject objectWithData:UIImagePNGRepresentation(image) previewImageData:nil title:@"更美app" description:@"我是图片"];
    SendMessageToQQReq* req = [SendMessageToQQReq reqWithContent:imgObj];
    imgObj.shareDestType = ShareDestTypeQQ;
    QQApiSendResultCode sent = [QQApiInterface sendReq:req];
    [self handleSendResult:sent];
}

- (void)QQFriendShareWithParameters: (NSDictionary *)parameters {
    id string = parameters[@"images"];
    UIImage * originlaImage = [self originalImageWithString:string];
    NSURL* url = [self shareUrl:parameters[@"url"]];
    NSString *title = parameters[@"title"];
    NSString *description = parameters[@"content"];
    
    QQApiNewsObject* img = [QQApiNewsObject objectWithURL:url title:title description:description previewImageData:UIImagePNGRepresentation([GMShareSDK compressImage:originlaImage])];
    SendMessageToQQReq* req = [SendMessageToQQReq reqWithContent:img];
    img.shareDestType = ShareDestTypeQQ;
    QQApiSendResultCode sent = [QQApiInterface sendReq:req];
    [self handleSendResult:sent];
}


- (void)QQSpaceShareWithParameters: (NSDictionary *)parameters {

    id string = parameters[@"images"];
    UIImage * originlaImage = [self originalImageWithString:string];
    
    NSURL* url = [self shareUrl:parameters[@"url"]];
    NSString *title = parameters[@"title"];
    NSString *description = parameters[@"content"];
    NSData *data = UIImagePNGRepresentation([GMShareSDK compressImage:originlaImage]);
    QQApiNewsObject * imgObj = [QQApiNewsObject objectWithURL:url title:title description:description previewImageData:data];
    [imgObj setTitle:title ? : @""];
    [imgObj setCflag:kQQAPICtrlFlagQZoneShareOnStart]; //不要忘记设置这个flag
    SendMessageToQQReq* req = [SendMessageToQQReq reqWithContent:imgObj];
    QQApiSendResultCode sent = [QQApiInterface sendReq:req];
    [self handleSendResult:sent];
}


- (void)handleSendResult:(QQApiSendResultCode)sendResult{
    switch (sendResult)
    {
        case EQQAPIAPPNOTREGISTED:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"App未注册" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            break;
        }
        case EQQAPIMESSAGECONTENTINVALID:
        case EQQAPIMESSAGECONTENTNULL:
        case EQQAPIMESSAGETYPEINVALID:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"发送参数错误" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            break;
        }
        case EQQAPIQQNOTINSTALLED:
        {
//            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"未安装手Q" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
//            [msgbox show];
            NSLog(@"未安装手Q");
            [[NSNotificationCenter defaultCenter] postNotificationName:kQQShare object:nil userInfo:@{@"state": @(GMShareResponseStateFail)}];
            break;
        }
        case EQQAPITIMNOTINSTALLED:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"未安装TIM" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            break;
        }
        case EQQAPIQQNOTSUPPORTAPI:
        case EQQAPITIMNOTSUPPORTAPI:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"API接口不支持" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            break;
        }
        case EQQAPISENDFAILD:
        {
//            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"发送失败" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
//            [msgbox show];
            NSLog(@"发送失败");
            [[NSNotificationCenter defaultCenter] postNotificationName:kQQShare object:nil userInfo:@{@"state": @(GMShareResponseStateFail)}];
            break;
        }
        case EQQAPIVERSIONNEEDUPDATE:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"当前QQ版本太低，需要更新" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            break;
        }
        case ETIMAPIVERSIONNEEDUPDATE:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"当前QQ版本太低，需要更新" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            break;
        }
        default:
        {
            break;
        }
    }
}

#pragma mark -- WeiBoShare

- (void)weiboShareWithParameters: (NSDictionary *)parameters{
    _messageObject = [self manageWeiboMessageWithParameters:parameters];
    [self messageShare];
}

- (void)messageShare {
    WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
    authRequest.redirectURI = SINAWEIBO_REDIRECTURI;
    authRequest.scope = @"all";
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:_messageObject authInfo:authRequest access_token:[GMThirdPartyOauthManager shareInstance].wbtoken];
    request.userInfo = @{@"flag": @"share"};
    [WeiboSDK sendRequest:request];
}

- (WBMessageObject *)manageWeiboMessageWithParameters: (NSDictionary *)parameters{
    id string = parameters[@"images"];
    UIImage * originlaImage = [self originalImageWithString:string];
    NSString *description = [NSString stringWithFormat:@"%@%@%@",parameters[@"title"],parameters[@"content"],parameters[@"url"]];
    WBMessageObject *message = [WBMessageObject message];
    message.text = description;
    WBImageObject *imageObject = [WBImageObject object];
    imageObject.delegate = self;
    imageObject.imageData = UIImagePNGRepresentation([GMShareSDK compressImage:originlaImage]);
    //这句话会crash
//    [imageObject addImages:@[,thumbImage]];
    message.imageObject = imageObject;
    return message;
}

-(void)wbsdk_TransferDidReceiveObject:(id)object{
    [self messageShare];
}

-(void)wbsdk_TransferDidFailWithErrorCode:(WBSDKMediaTransferErrorCode)errorCode andError:(NSError*)error{
    
}


#pragma mark -- weChatShare

- (void)wechatSessionShareWithParameters: (NSDictionary *)parameters scene:(int)scene {
    GMShareContentType contentType = (GMShareContentType)[parameters[@"type"] integerValue];
    switch (contentType) {
        case GMShareContentTypeAuto:{
            NSURL* url = [self shareUrl:parameters[@"url"]];;
            if (url) {
                [self wechatLinkShareWith:parameters scene:scene];
            } else {
                [self wechatImageShareWithParameters:parameters scene:scene];
            }
        }
            break;
        case GMShareContentTypeText:
            break;
        case GMShareContentTypeImage:
            [self wechatImageShareWithParameters:parameters scene:scene];
            break;
        case GMShareContentTypeWebPage:
            [self wechatLinkShareWith:parameters scene:scene];
            break;
        case GMShareContentTypeAudio:
            break;
        case GMShareContentTypeVideo:
            break;
        case GMShareContentTypeFile:
            break;
        case GMShareContentTypeFBMessageImages:
            break;
        case GMShareContentTypeFBMessageVideo:
            break;
        case GMShareContentTypeMiniProgram:
            [self wechatMiniProgramWithParameters:parameters scene:scene];
            break;
        default:
            break;
    }
}

- (void)wechatMiniProgramWithParameters: (NSDictionary *)parameters scene:(int)scene{
    WXMiniProgramObject *wxMiniObject = [WXMiniProgramObject object];
    wxMiniObject.webpageUrl = parameters[@"url"] ;
    wxMiniObject.userName = parameters[@"userName"];
    wxMiniObject.path = parameters[@"path"];
    
    NSData * hdImageData = [self requesDataWithString:parameters[@"hdImageData"]];
    wxMiniObject.hdImageData = hdImageData;
    
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = parameters[@"title"];
    message.description = parameters[@"description"];
    message.mediaObject = wxMiniObject;
    
    UIImage * thumbImage = [self originalImageWithString:parameters[@"thumbImage"]];
    [message setThumbImage:thumbImage];
    
    SendMessageToWXReq * req = [[SendMessageToWXReq alloc]init];
    req.message = message;
    req.scene = scene;
    [WXApi sendReq:req];
}

- (void)wechatImageShareWithParameters: (NSDictionary *)parameters scene:(int)scene{
    id string = parameters[@"images"];
    UIImage * originlaImage = [self originalImageWithString:string];
    WXImageObject *ext = [WXImageObject object];
    ext.imageData = UIImagePNGRepresentation(originlaImage);
    WXMediaMessage *message = [WXMediaMessage message];
    message.mediaObject = ext;
    [message setThumbImage:[GMShareSDK compressImage:originlaImage]];
    SendMessageToWXReq * req = [self requestWithText:nil OrMediaMessage:message bText:NO InScene:scene];
    [WXApi sendReq:req];
}

- (void)wechatLinkShareWith:(NSDictionary *)parameters scene:(int)scene{
    id image = parameters[@"images"];
    UIImage * originlaImage  = [self originalImageWithString:image];
    NSURL* url = [self shareUrl:parameters[@"url"]];
    NSString *title = parameters[@"title"];
    NSString *description = parameters[@"content"];
    
    WXWebpageObject *ext = [WXWebpageObject object];
    ext.webpageUrl = url.absoluteString;
    
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = title;
    message.description = description;
    message.mediaObject = ext;
    
    [message setThumbImage:[GMShareSDK compressImage:originlaImage]];
    SendMessageToWXReq* req =  [self requestWithText:nil OrMediaMessage:message bText:NO InScene:scene];
    [WXApi sendReq:req];
}

- (NSURL *)shareUrl:(id )string {
    
    if ([string isKindOfClass:[NSURL class]]) {
        return (NSURL *)string;
    } else if([string isKindOfClass:[NSString class]]){
        return [NSURL URLWithString:string];
    }
    return nil;
}

- (UIImage *)originalImageWithString:(id )string{
    UIImage* image = nil;
    if ([string isKindOfClass:[UIImage class]]){
        image = (UIImage *)string;
    } else if ([string isKindOfClass:[NSString class]]) {
        NSString *url = (NSString *)string;
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:1.5];
        NSURLResponse *response = nil;
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
        image = [UIImage imageWithData: data];
        //如果远程的图片下载不下来，则使用默认图
        if (image == nil) {
            image = [UIImage imageNamed:@"AppIcon"];
        }
    }
    return image;
}

- (NSData *)requesDataWithString:(id)string{
    NSData *data = nil;
    UIImage * image = nil;
    if ([string isKindOfClass:[UIImage class]]){
        UIImage * image = (UIImage *)string;
        data = UIImagePNGRepresentation(image);
    } else if ([string isKindOfClass:[NSString class]]) {
        NSString *url = (NSString *)string;
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:1.5];
        NSURLResponse *response = nil;
        data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
        //如果远程的图片下载不下来，则使用默认图
        if (data == nil) {
            image = [UIImage imageNamed:@"AppIcon"];
            data = UIImagePNGRepresentation(image);
        }
    }
    return data;
}

- (SendMessageToWXReq *)requestWithText:(NSString *)text
                         OrMediaMessage:(WXMediaMessage *)message
                                  bText:(BOOL)bText
                                InScene:(enum WXScene)scene {
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = bText;
    req.scene = scene;
    if (bText)
        req.text = text;
    else
        req.message = message;
    return req;
}

@end

