//
//  RNHelper.m
//  ab
//
//  Created by xuyazhong on 2022/7/12.
//

#import "RNHelper.h"
#import "ScanVC.h"
#import "AppManager.h"
#import <SGQRCode/SGQRCode.h>

@implementation RNHelper
{
  RCTResponseSenderBlock mCallback;
}
- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}
RCT_EXPORT_MODULE()

RCT_EXPORT_METHOD(qr:(RCTResponseSenderBlock)callback) {
  mCallback = callback;
  dispatch_async(dispatch_get_main_queue(), ^{
    
    UIViewController *root = [AppManager getTopViewController];
    SGAuthorization *authorization = [[SGAuthorization alloc] init];
    authorization.openLog = YES;
    [authorization AVAuthorizationBlock:^(SGAuthorization * _Nonnull authorization, SGAuthorizationStatus status) {
      if (status == SGAuthorizationStatusSuccess) {
        ScanVC *vc = [[ScanVC alloc] init];
        vc.block = ^(NSString * _Nonnull result) {
          [self invokeSuccessWithResult:result];
        };
        vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
        [root presentViewController:vc animated:NO completion:nil];
      } else if (status == SGAuthorizationStatusFail) {
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请去-> [设置 - 隐私 - 相机 - 伏羲编程] 打开访问开关" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        }];
        
        [alertC addAction:alertA];
        dispatch_async(dispatch_get_main_queue(), ^{
          [root presentViewController:alertC animated:YES completion:nil];
        });
      } else {
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"未检测到您的摄像头" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
          
        }];
        
        [alertC addAction:alertA];
        dispatch_async(dispatch_get_main_queue(), ^{
          [root presentViewController:alertC animated:YES completion:nil];
        });
      }
    }];
    
  });
}

- (void)invokeError:(NSString *)result {
  if (mCallback != nil) {
    mCallback(@[result]);
    mCallback = nil;
  }
}

- (void)invokeSuccessWithResult:(NSString *)result {
  if (mCallback != nil) {
    mCallback(@[[NSNull null], result]);
    mCallback = nil;
  }
}

@end
  
