#import "CDVSharkShare.h"
#import <Cordova/CDVPlugin.h>

#import <ShareSDK/ShareSDK.h>
#import <MOBFoundation/MOBFoundation.h>

////腾讯开放平台（对应QQ和QQ空间）SDK头文件
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import <ShareSDKExtension/SSEShareHelper.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import <ShareSDKUI/SSUIShareActionSheetStyle.h>
#import <ShareSDKUI/SSUIShareActionSheetCustomItem.h>
#import <ShareSDK/ShareSDK+Base.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
#import <ShareSDKExtension/ShareSDK+Extension.h>

//微信SDK头文件
#import "WXApi.h"

//新浪微博
#import "WeiboSDK.h"
#import <UIKit/UIKit.h>
@implementation CDVSharkShare
#pragma mark "API"
- (void)pluginInitialize {
    
    NSString* sharesdkAppKey = [[self.commandDelegate settings] objectForKey:@"sharesdkappkey"];
    NSString* wechatAppId = [[self.commandDelegate settings] objectForKey:@"wechatappid"];
    NSString* wechatAppSecret = [[self.commandDelegate settings] objectForKey:@"wechatappsecret"];
    NSString* qqAppId = [[self.commandDelegate settings] objectForKey:@"qqappid"];
    NSString* qqAppKey = [[self.commandDelegate settings] objectForKey:@"qqappkey"];
    NSString* wbAppKey = [[self.commandDelegate settings] objectForKey:@"wbappkey"];
    NSString* wbAppSecret = [[self.commandDelegate settings] objectForKey:@"wbappsecret"];
    NSString* wbRedirectUrl = [[self.commandDelegate settings] objectForKey:@"wbredirecturl"];
    
    if(wechatAppId && wechatAppSecret && qqAppId && qqAppKey && wbAppKey && wbAppSecret && wbRedirectUrl && sharesdkAppKey){
        /*Share SDK config*/
        
        
        /**
         *  设置ShareSDK的appKey，如果尚未在ShareSDK官网注册过App，请移步到http://mob.com/login 登录后台进行应用注册，
         *  在将生成的AppKey传入到此方法中。我们Demo提供的appKey为内部测试使用，可能会修改配置信息，请不要使用。
         *  方法中的第二个参数用于指定要使用哪些社交平台，以数组形式传入。第三个参数为需要连接社交平台SDK时触发，
         *  在此事件中写入连接代码。第四个参数则为配置本地社交平台时触发，根据返回的平台类型来配置平台信息。
         *  如果您使用的时服务端托管平台信息时，第二、四项参数可以传入nil，第三项参数则根据服务端托管平台来决定要连接的社交SDK。
         */
        [ShareSDK registerApp:sharesdkAppKey
              activePlatforms:@[
                                @(SSDKPlatformTypeSinaWeibo),
                                @(SSDKPlatformTypeWechat),
                                @(SSDKPlatformTypeQQ)
                                ]
                     onImport:^(SSDKPlatformType platformType) {
                         
                         switch (platformType)
                         {
                             case SSDKPlatformTypeWechat:
                                 //                             [ShareSDKConnector connectWeChat:[WXApi class]];
                                 [ShareSDKConnector connectWeChat:[WXApi class] delegate:self];
                                 break;
                             case SSDKPlatformTypeQQ:
                                 [ShareSDKConnector connectQQ:[QQApiInterface class]
                                            tencentOAuthClass:[TencentOAuth class]];
                                 break;
                             case SSDKPlatformTypeSinaWeibo:
                                 [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                                 break;
                                 
                             default:
                                 break;
                         }
                     }
              onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo) {
                  
                  switch (platformType)
                  {
                      case SSDKPlatformTypeSinaWeibo:
                          //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                          [appInfo SSDKSetupSinaWeiboByAppKey:wbAppKey
                                                    appSecret:wbAppSecret
                                                  redirectUri:wbRedirectUrl
                                                     authType:SSDKAuthTypeBoth];
                          break;
                          
                      case SSDKPlatformTypeWechat:
                          [appInfo SSDKSetupWeChatByAppId:wechatAppId
                                                appSecret:wechatAppSecret];
                          break;
                      case SSDKPlatformTypeQQ:
                          [appInfo SSDKSetupQQByAppId:qqAppId
                                               appKey:qqAppKey
                                             authType:SSDKAuthTypeBoth];
                          break;
                          
                      default:
                          break;
                  }
              }];
        
        
        
    }
}

- (void)share:(CDVInvokedUrlCommand*)command {
    
    
    
    NSString* title = [command.arguments objectAtIndex:0];
    NSString* text = [command.arguments objectAtIndex:1];
    NSString* imageUrl = [command.arguments objectAtIndex:2];
    NSString* url = [command.arguments objectAtIndex:3];
    
    
    
    //1、创建分享参数（必要）
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    
    //    NSArray* imageArray = @[[UIImage imageNamed:@"shareImg.png"]];
    
    [shareParams SSDKSetupShareParamsByText:text
                                     images:@[imageUrl]
                                        url:[NSURL URLWithString:url]
                                      title:title
                                       type:SSDKContentTypeAuto];
    
    
    if(text.length > 37)
    {
        text = [[text substringToIndex:36] stringByAppendingString:@"..."];
    }
    if(title.length>27)
        title = [[title substringToIndex:26] stringByAppendingString:@"..."];
    [shareParams SSDKSetupQQParamsByText:text title:title url:[NSURL URLWithString:url] thumbImage:@[imageUrl] image:@[imageUrl] type:SSDKContentTypeAuto forPlatformSubType:SSDKPlatformSubTypeQQFriend];
    NSArray* plateforms = [NSArray arrayWithObjects:[NSNumber numberWithInteger:SSDKPlatformTypeSinaWeibo],[NSNumber numberWithInteger:SSDKPlatformSubTypeQQFriend],[NSNumber numberWithInteger:SSDKPlatformSubTypeWechatSession],[NSNumber numberWithInteger:SSDKPlatformSubTypeWechatTimeline], nil];
    
    [ShareSDK showShareActionSheet:nil
                             items:plateforms
                       shareParams:shareParams
               onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                   
                   CDVPluginResult* pluginResult = nil;
                   switch (state) {
                           
                       case SSDKResponseStateBegin:
                       {
                           break;
                       }
                       case SSDKResponseStateSuccess:
                       {
                           pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
                           
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                               message:nil
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"确定"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                           
                           [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
                           
                           
                           break;
                       }
                       case SSDKResponseStateFail:
                       {
                           NSLog(@"分享失败,错误码:%ld,错误描述:%@", [error code], [error localizedDescription]);
                           UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                           message:[NSString stringWithFormat:@"%@",error]
                                                                          delegate:nil
                                                                 cancelButtonTitle:@"OK"
                                                                 otherButtonTitles:nil, nil];
                           [alert show];
                           
                           pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK ];
                           
                           
                           
                           [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];                       }
                       case SSDKResponseStateCancel:
                       {
                           pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
                           
                           [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
                           break;
                       }
                       default:
                           break;
                   }
                   
                   
               }];
    
    
}



@end

