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

#import "GMShareSDK.h"
#import "WeiboSDK/WeiboSDK.h"
#import "TencentOpenAPI/TencentOAuth.h"
#import "TencentOpenAPI/QQApiInterface.h"
#import "TencentOpenAPI/QQApiInterfaceObject.h"
#import "WXApiObject.h"
#import "GMThirdPartyOauthManager.h"
#import "GMThirdPartyDefine.h"
#import "WeiboSDK.h"
#import <Photos/Photos.h>
#import "TencentOpenAPI/QQApiInterfaceObject.h"
#import <GMKit/UIImage+GM.h>
#import "UIImage+Compress.h"
#import "DouyinOpenSDKApi.h"
#import "UIAlertController+gm.h"
#import "WechatOpenSDK/WXApi.h"

@interface GMShareSDK ()
#warning TODO 待验证
//<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 if (platformType == GMSharePlatformDouyin) {
        return [DouyinOpenSDKApi isAppInstalled];
    } 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 @"wechatline";
            break;
        }
        case GMSharePlatformWechatSessionSnapShot:{
            return @"wechat_snapshot";
            break;
        }
        case GMSharePlatformWechatTimelineSnapShot:{
            return @"wechatline_snapshot";
            break;
        }
        case GMSharePlatformWechatMiniProgram:{
            return @"xcx";
            break;
        }
        case GMSharePlatformSinaWeibo:{
            return @"tsina";
            break;
        }
        case GMSharePlatformDouyin:{
            return @"Douyin";
            break;
        }
        default:
            return @"Default";
            break;
    }
}

//TODO 换一种方式压缩图片
+ (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:@"icon"];
    }
    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;
        }
        case GMSharePlatformDouyin:{
            [self douYinShareWithParameters:parameters];
            [self shareWithName:kDouyinShare 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 {
    NSData *imageData = UIImagePNGRepresentation(image);
    //如果图片大于10M 需要对图片压缩 不然分享不出去  微信qq  要求图片在10m 以内
    if (imageData.length > (10*1024*1024)) {
        imageData = UIImageJPEGRepresentation(image, 0.1);
    } else if (imageData.length > (1024*1024)) {
        imageData = UIImageJPEGRepresentation(image, 0.6);
    }
   
    QQApiImageObject *imgObj = [QQApiImageObject objectWithData:imageData 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  image = parameters[@"images"];
    UIImage * thumbImage  = image;
    
    NSURL* url = parameters[@"url"];
    NSString *title = parameters[@"title"];
    NSString *description = parameters[@"text"];
    
    QQApiNewsObject* img = [QQApiNewsObject objectWithURL:url title:title description:description previewImageData:UIImagePNGRepresentation(thumbImage)];
    SendMessageToQQReq* req = [SendMessageToQQReq reqWithContent:img];
    img.shareDestType = ShareDestTypeQQ;
    QQApiSendResultCode sent = [QQApiInterface sendReq:req];
    [self handleSendResult:sent];
}


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

    UIImage * previewImage = nil;
    id  images = parameters[@"images"];
    if ([images isKindOfClass:[NSArray class]]) {
        NSArray * tmp = (NSArray *)images;
        previewImage = tmp.firstObject;
    } else {
        previewImage = images;
    }
    NSURL* url = parameters[@"url"];
    NSString *title = parameters[@"title"];
    NSString *description = parameters[@"text"];
    NSData *data = UIImagePNGRepresentation(previewImage);
    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:
        {
            [UIAlertController showgm_OKAlertWithTitle:@"Error" message:@"App未注册" actionTitle:@"取消" actionHandler:^{
            }];
            break;
        }
        case EQQAPIMESSAGECONTENTINVALID:
        case EQQAPIMESSAGECONTENTNULL:
        case EQQAPIMESSAGETYPEINVALID:
        {
            [UIAlertController showgm_OKAlertWithTitle:@"Error" message:@"发送参数错误" actionTitle:@"取消" actionHandler:^{
            }];
            break;
        }
        case EQQAPIQQNOTINSTALLED:
        {
//            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"未安装手Q" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [UIAlertController showgm_OKAlertWithTitle:@"Error" message:@"未安装手Q" actionTitle:@"取消" actionHandler:^{
            }];
//            [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];
            [UIAlertController showgm_OKAlertWithTitle:@"Error" message:@"未安装TIM" actionTitle:@"取消" actionHandler:^{
            }];
            break;
        }
        case EQQAPIQQNOTSUPPORTAPI:
        case EQQAPITIMNOTSUPPORTAPI:
        {

            [UIAlertController showgm_OKAlertWithTitle:@"Error" message:@"API接口不支持" actionTitle:@"取消" actionHandler:^{
            }];
            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];
            [UIAlertController showgm_OKAlertWithTitle:@"Error" message:@"当前QQ版本太低，需要更新" actionTitle:@"取消" actionHandler:^{
            }];
            break;
        }
        case ETIMAPIVERSIONNEEDUPDATE:
        {
            [UIAlertController showgm_OKAlertWithTitle:@"Error" message:@"当前QQ版本太低，需要更新" actionTitle:@"取消" actionHandler:^{
            }];
            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  image = parameters[@"images"];
    UIImage * thumbImage  = image;
    NSString *description = parameters[@"text"];
    WBMessageObject *message = [WBMessageObject message];
    message.text = description;
    WBImageObject *imageObject = [WBImageObject object];
//    imageObject.delegate = self;
    imageObject.imageData = UIImageJPEGRepresentation(thumbImage, 1);
    //这句话会crash
//    [imageObject addImages:@[,thumbImage]];
    message.imageObject = imageObject;
    return message;
}

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



#pragma mark -- weChatShare

- (void)wechatSessionShareWithParameters: (NSDictionary *)parameters scene:(int)scene {
    GMShareContentType contentType = (GMShareContentType)[parameters[@"type"] integerValue];
    switch (contentType) {
        case GMShareContentTypeAuto:{
            NSURL* url = 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 {
#ifndef APPSTORE
//    if ([GMServerDomains.apiHost isEqualToString:@"http://ibackend.igengmei.com"] || [GMServerDomains.apiHost isEqualToString:@"http://backend.igengmei.com"] || [GMServerDomains.apiHost isEqualToString:@""]) {
//        [UIAlertController gm_Alert:@"当前环境，APP和小程序未绑定在同一微信开发平台账号，无法分享成功" leftTitle:@"OK" rightTitle:@"OK" leftAlterAction:^{
//        } rightAlertAction:^{
//        }];
//        [AppDelegate.visibleController presentViewController:alert animated:YES completion:nil];
//        return;
//    }
#endif
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        WXMiniProgramObject *wxMiniObject = [WXMiniProgramObject object];
        wxMiniObject.webpageUrl = parameters[@"url"];
        wxMiniObject.userName = parameters[@"userName"];
        wxMiniObject.path = parameters[@"path"];
        // 压缩图片（不大于128K）
        NSData * hdImageData = [self requesDataWithString:parameters[@"hdImageData"]];
        hdImageData = [UIImage compressImage:[UIImage imageWithData:hdImageData] toByte:128 * 1024 size:CGSizeMake(300, 240)];
        wxMiniObject.hdImageData = hdImageData;
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = parameters[@"title"];
        message.description = parameters[@"description"];
        message.mediaObject = wxMiniObject;
        
        UIImage * thumbImage = [self originalImageWithString:parameters[@"thumbImage"]];
        thumbImage = [UIImage imageWithData:[UIImage compressImage:thumbImage toByte:32 * 1024 size:CGSizeMake(150, 150)]];
        [message setThumbImage:thumbImage];
        SendMessageToWXReq * req = [[SendMessageToWXReq alloc]init];
        req.message = message;
        req.scene = scene;   
        // 转回到主线程
        [WXApi sendReq:req completion:^(BOOL success) {
            
        }];
    });
}

- (void)wechatImageShareWithParameters: (NSDictionary *)parameters scene:(int)scene{
    id string = parameters[@"images"];
    UIImage * originlaImage = [self originalImageWithString:string];
    WXImageObject *ext = [WXImageObject object];
    ext.imageData = UIImagePNGRepresentation(originlaImage);
    //如果图片大于10M 需要对图片压缩
    if (ext.imageData.length > (10*1024*1024)) {
        ext.imageData = UIImageJPEGRepresentation(originlaImage, 0.1);
    } else if (ext.imageData.length > (1024*1024)) {
        ext.imageData = UIImageJPEGRepresentation(originlaImage, 0.6);
    }
    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 completion:^(BOOL success) {
        
    }];
}

- (void)wechatLinkShareWith:(NSDictionary *)parameters scene:(int)scene{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        id image = parameters[@"images"];
        UIImage * thumbImage  = image;
        NSURL* url = parameters[@"url"];
        NSString *title = parameters[@"title"];
        NSString *description = parameters[@"text"];
        
        WXWebpageObject *ext = [WXWebpageObject object];
        ext.webpageUrl = url.absoluteString;
        
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = title;
        message.description = description;
        message.mediaObject = ext;
        
        [message setThumbImage:[UIImage imageWithData:[UIImage compressImage:thumbImage toByte:32 * 1024 size:CGSizeMake(150, 150)]]];
        SendMessageToWXReq* req =  [self requestWithText:nil OrMediaMessage:message bText:NO InScene:scene];
        // 转回到主线程
        dispatch_sync(dispatch_get_main_queue(), ^{
            [WXApi  sendReq:req completion:^(BOOL success) {
        
    }];
        });
    });
}

- (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:@"icon"];
        }
    }
    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:@"share_smallProgram"];
            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;
}

#pragma mark -- douYin
- (void)douYinShareWithParameters:(NSDictionary *)parameters{
    DouyinOpenSDKShareReq *req = [DouyinOpenSDKShareReq new];
    req.mediaType = DouyinOpenSDKShareMediaTypeVideo;
    
    NSMutableArray *mediaUrl = [NSMutableArray array];
    NSURL *videoUrl = [NSURL new];
    if ([parameters.allKeys containsObject:@"videoUrl"]) {
        videoUrl= parameters[@"videoUrl"];
    }
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:videoUrl];
        NSString *localId = req.placeholderForCreatedAsset.localIdentifier;
        [mediaUrl addObject:localId];
        
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (success) {
            dispatch_async(dispatch_get_main_queue(), ^{
                //                            [self sendShareReq];
                // 分享视频
                req.localIdentifiers = mediaUrl;
                BOOL success = [DouyinOpenSDKApi sendReq:req];
                if (success) {
                    NSLog(@"send share req success");
                } else {
                    NSLog(@"send share req failure");
                }
            });
        }
    }];
    ////     #话题，需要额外开通，视频中会有 #变脸挑战 的话题标签, 非必须属性
    //    req.hashtag = @"变脸挑战";
    //
    //    // 小程序，在分享的视频右下角显示抖音小程序入口, 非必须属性
    //    req.mpInfo = [DouyinOpenSDKMPInfo mpInfoWithIdentifier:@"you_mp_identifier" title:@"title" desc:@"desc" startPageURL:nil];
}

@end

