//
//  XMJDPayModule.m
//  XinMai
//
//  Created by mac on 2020/10/19.
//

#import "bjyLiveModule.h"

#import "ProRNBJSellViewController.h"
#import "UIViewController+ModalPresentation.h"
#import "WXLlcRoomViewController.h"
#import "WXPlayBackRoomViewController.h"
#import <BJPlaybackUI/BJPlaybackUI.h>
#import <BJVideoPlayerCore/BJVideoPlayerCore.h>
#import <React/RCTBridge.h>
#import <React/RCTEventDispatcher.h>

static bjyLiveModule *shareManager = nil;
static NSString *const XMOTHERLOGIN = @"OTHERLOGIN";
static NSString *const XMONEKEYLOGIN = @"ONEKEYLOGIN";
@implementation bjyLiveModule {
    RCTResponseSenderBlock _OTOCallback;
    RCTResponseSenderBlock _normalCallback;
    RCTResponseSenderBlock _sellCallback;
    RCTResponseSenderBlock _scLCallback;
    RCTResponseSenderBlock _roomCallback;
}
@synthesize bridge = _bridge;

RCT_EXPORT_MODULE(BjyModule);

+ (instancetype)shareManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareManager = [[super allocWithZone:NULL] init];
    });
    return shareManager;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    return [bjyLiveModule shareManager];
}

- (instancetype)copyWithZone:(struct _NSZone *)zone {
    return [bjyLiveModule shareManager];
}
- (instancetype)mutableCopyWithZone:(struct _NSZone *)zone {
    return [bjyLiveModule shareManager];
}


RCT_EXPORT_METHOD(initSdkDomain
                  : (NSString *)domainName) {
    [BJLRoom setPrivateDomainPrefix:domainName];
    [[BJVAppConfig sharedInstance] setPrivateDomainPrefix:domainName];
}

///普通直播课
RCT_EXPORT_METHOD(playNormalLive
                  : (NSDictionary *)map callback
                  : (RCTResponseSenderBlock)callback) {
    _normalCallback = callback;
    NSString *roomID = [map objectForKey:@"roomId"];
    NSString *sign = [map objectForKey:@"sign"];
    NSString *user_number = [map objectForKey:@"user_number"];
    NSString *group_id = [map objectForKey:@"group_id"];
    NSString *user_name = [map objectForKey:@"user_name"];
    NSString *user_role = [map objectForKey:@"user_role"];
    NSString *user_avatar = [map objectForKey:@"user_avatar"];
    BJLUser *user = [BJLUser userWithNumber:user_number name:user_name groupID:[group_id integerValue] avatar:user_avatar role:[user_role integerValue]];
    BJLRoomID *bJLRoom = [BJLRoomID new];
    bJLRoom.apiSign = sign;
    bJLRoom.roomID = roomID;
    bJLRoom.user = user;
    WXLlcRoomViewController *roomController = [WXLlcRoomViewController instanceWithRoomType:(BJLRoomVCTypeBigClass) roomID:bJLRoom];
    __weak typeof(self) weakSelf = self;
    roomController.exitBackBlock = ^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf->_normalCallback(@[[NSNull null], map]);
    };
    [[self getCurrentWindowVC] presentModalViewController:roomController animated:YES completion:nil];
}

///一对一 标准直播课
RCT_EXPORT_METHOD(playOTOLive
                  : (NSDictionary *)map callback
                  : (RCTResponseSenderBlock)callback) {
    _OTOCallback = callback;
    NSString *roomID = [map objectForKey:@"roomId"];
    NSString *sign = [map objectForKey:@"sign"];
    NSString *user_number = [map objectForKey:@"user_number"];
    NSString *group_id = [map objectForKey:@"group_id"];
    NSString *user_name = [map objectForKey:@"user_name"];
    NSString *user_role = [map objectForKey:@"user_role"];
    NSString *user_avatar = [map objectForKey:@"user_avatar"];
    BJLUser *user = [BJLUser userWithNumber:user_number name:user_name groupID:[group_id integerValue] avatar:user_avatar role:[user_role integerValue]];
    BJLRoomID *bJLRoom = [BJLRoomID new];
    bJLRoom.apiSign = sign;
    bJLRoom.roomID = roomID;
    bJLRoom.user = user;
    WXLlcRoomViewController *smallRoomController = [WXLlcRoomViewController instanceWithRoomType:(BJLRoomVCTypeSmallClass) roomID:bJLRoom];
    __weak typeof(self) weakSelf = self;
    smallRoomController.exitBackBlock = ^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf->_OTOCallback(@[[NSNull null], map]);
    };
    [[self getCurrentWindowVC] presentModalViewController:smallRoomController animated:YES completion:nil];
}

///三分屏
RCT_EXPORT_METHOD(playScRoomLive
                  : (NSDictionary *)map callback
                  : (RCTResponseSenderBlock)callback) {
    _scLCallback = callback;
    NSString *roomID = [map objectForKey:@"roomId"];
    NSString *sign = [map objectForKey:@"sign"];
    NSString *user_number = [map objectForKey:@"user_number"];
    NSString *group_id = [map objectForKey:@"group_id"];
    NSString *user_name = [map objectForKey:@"user_name"];
    NSString *user_role = [map objectForKey:@"user_role"];
    NSString *user_avatar = [map objectForKey:@"user_avatar"];
    BJLUser *user = [BJLUser userWithNumber:user_number name:user_name groupID:[group_id integerValue] avatar:user_avatar role:[user_role integerValue]];
    BJLRoomID *bJLRoom = [BJLRoomID new];
    bJLRoom.apiSign = sign;
    bJLRoom.roomID = roomID;
    bJLRoom.user = user;
    WXLlcRoomViewController *roomController = [WXLlcRoomViewController instanceWithRoomType:(BJLRoomVCTypeBigClass) roomID:bJLRoom];
    __weak typeof(self) weakSelf = self;
    roomController.exitBackBlock = ^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf->_scLCallback(@[[NSNull null], map]);
    };
    [[self getCurrentWindowVC] presentModalViewController:roomController animated:YES completion:nil];
}


///回放
RCT_EXPORT_METHOD(playBackRoom
                  : (NSDictionary *)map callback
                  : (RCTResponseSenderBlock)callback) {
    _roomCallback = callback;
    NSString *roomID = [map objectForKey:@"roomId"];
    NSString *token = [map objectForKey:@"token"];
    BJPPlaybackOptions *playbackOptions = [[BJPPlaybackOptions alloc] init];
    playbackOptions.playerType = BJVPlayerType_AVPlayer;
    WXPlayBackRoomViewController *playBackRoom = [WXPlayBackRoomViewController onlinePlaybackRoomWithClassID:roomID
                                                                                                   sessionID:nil
                                                                                                       token:token
                                                                                                   accessKey:nil
                                                                                                     options:playbackOptions];
    __weak typeof(self) weakSelf = self;
    playBackRoom.exitBackBlock = ^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf->_roomCallback(@[[NSNull null], map]);
    };
    [[self getCurrentWindowVC] presentModalViewController:playBackRoom animated:YES completion:nil];
}

///直播带货
RCT_EXPORT_METHOD(playBJSellLive
                  : (NSDictionary *)map callback
                  : (RCTResponseSenderBlock)callback) {
    _sellCallback = callback;
    NSString *roomID = [NSString stringWithFormat:@"%@", [map objectForKey:@"room_id"]];
    ;
    NSString *sign = [map objectForKey:@"sign"];
    NSString *user_number = [NSString stringWithFormat:@"%@", [map objectForKey:@"user_number"]];
    ;
    NSString *group_id = [NSString stringWithFormat:@"%@", [map objectForKey:@"group_id"]];
    NSString *user_name = [map objectForKey:@"user_name"];
    NSString *user_role = [map objectForKey:@"user_role"];
    NSString *user_avatar = [map objectForKey:@"user_avatar"];
    BJLUser *user = [BJLUser userWithNumber:user_number name:user_name groupID:[group_id integerValue] avatar:user_avatar role:[user_role integerValue]];
    ProRNBJSellViewController *roomController = [ProRNBJSellViewController instanceWithID:roomID apiSign:sign user:user];
    __weak typeof(self) weakSelf = self;
    roomController.course_id = [map objectForKey:@"course_id"];
    roomController.exitBackBlock = ^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf->_sellCallback(@[[NSNull null], map]);
    };
    [[self getCurrentWindowVC] presentModalViewController:roomController animated:YES completion:nil];
}


RCT_EXPORT_METHOD(showLive
                  : (NSDictionary *)map
                      resolver
                  : (RCTPromiseResolveBlock)resolve
                      rejecter
                  : (RCTPromiseRejectBlock)reject) {
    NSString *orderID = [map objectForKey:@"orderId"];
    NSString *merchant = [map objectForKey:@"merchant"];
    NSString *appId = [map objectForKey:@"appId"];
    NSString *signData = [map objectForKey:@"signData"];
    NSString *extraInfo = [map objectForKey:@"extraInfo"];
}

- (UIViewController *)getCurrentWindowVC {
    UIViewController *result = nil;
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    //app默认windowLevel是UIWindowLevelNormal，如果不是，找到它
    if (window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for (UIWindow *tmpWin in windows) {
            if (tmpWin.windowLevel == UIWindowLevelNormal) {
                window = tmpWin;
                break;
            }
        }
    }
    id nextResponder = nil;
    UIViewController *appRootVC = window.rootViewController;
    //1、通过present弹出VC，appRootVC.presentedViewController不为nil
    if (appRootVC.presentedViewController) {
        nextResponder = appRootVC.presentedViewController;
    }
    else {
        //2、通过navigationcontroller弹出VC
        UIView *frontView = [[window subviews] objectAtIndex:0];
        nextResponder = [frontView nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            result = nextResponder;
        }
        else {
            result = window.rootViewController;
        }
        return result;
    }
    return nextResponder;
}

- (dispatch_queue_t)methodQueue {
    return dispatch_get_main_queue();
}

+ (BOOL)requiresMainQueueSetup {
    return YES;
}
@end
