//
//  OLTermsHelper.m
//  OneLoginExample
//
//  Created by Niko Xu on 2025/8/21.
//  Copyright © 2025 geetest. All rights reserved.
//

#import "OLTermsHelper.h"
#import "OLAlertViewController.h"

static NSString * const kTermsAcceptedKey = @"TermsAccepted";

@interface UIApplication (OLKeywindow)

- (UIWindow *)currentKeyWindow;
- (UIViewController *)currentRootViewController;

@end

@implementation UIApplication (OLKeywindow)

- (UIWindow *)currentKeyWindow {
    if (@available(iOS 13.0, *)) {
        // 依次遍历所有 foregroundActive 的 UIWindowScene
        for (UIScene *scene in self.connectedScenes) {
            if ([scene isKindOfClass:[UIWindowScene class]] &&
                scene.activationState == UISceneActivationStateForegroundActive) {
                UIWindowScene *windowScene = (UIWindowScene *)scene;
                for (UIWindow *window in windowScene.windows) {
                    if (window.isKeyWindow) {
                        return window;
                    }
                }
            }
        }
        return nil;
    } else {
        // iOS 12 及更早版本
        return self.keyWindow;
    }
}

- (UIViewController *)currentRootViewController {
    return self.currentKeyWindow.rootViewController;
}

@end

#pragma mark - 内部私有类：负责富文本 + 链接点击
@interface OLTermsAlertController : UIAlertController <UITextViewDelegate, UITextFieldDelegate>

@property (nonatomic, copy) void (^onAccept)(BOOL);

+ (instancetype)alertWithTitle:(NSString *)title content:(NSAttributedString *)content onAccept:(void (^)(BOOL))onAccept;

@end

@implementation OLTermsHelper

#pragma mark - 公开接口
+ (BOOL)hasAcceptedTermsWithAlert:(BOOL)flag {
    BOOL status = [[NSUserDefaults standardUserDefaults] boolForKey:kTermsAcceptedKey];
    if (!status && flag) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"体验产品前请同意服务协议以及隐私政策"
                                                 message:@"如果不小心点了\"不同意\"，请重启 App 再次进行确认"
                                      preferredStyle:UIAlertControllerStyleAlert];
        // 按钮
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK"
                                                        style:UIAlertActionStyleDefault
                                                      handler:nil];
        [alertVC addAction:okAction];
        [[[UIApplication sharedApplication] currentRootViewController] presentViewController:alertVC animated:YES completion:nil];
    }
    return status;
}

+ (void)showTermsAlertFrom:(UIViewController *)presentingVC
                 onAccept:(void (^)(BOOL accepted))onAccept {
    
    NSString *title = @"使用前请同意相关协议";
    
    // 富文本内容
    NSString *plain =
        @"请阅读并同意《服务协议》和《隐私政策》后才能继续使用本 Demo 进行相关产品的体验";
    NSMutableAttributedString *attr =
        [[NSMutableAttributedString alloc] initWithString:plain
                                               attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
    
    [attr addAttribute:NSLinkAttributeName
                 value:@"https://www.geetest.com/Service"
                 range:[plain rangeOfString:@"《服务协议》"]];
    
    [attr addAttribute:NSLinkAttributeName
                 value:@"https://www.geetest.com/Private/onelogin"
                 range:[plain rangeOfString:@"《隐私政策》"]];
    
    if (@available(iOS 13.0, *)) {
        OLAlertViewController *alert = [OLAlertViewController alertWithTitle:title content:attr confirmButtonText:@"同意" cancelButtonText:@"不同意" confirmHandler:^{
            [[NSUserDefaults standardUserDefaults] setBool:YES
                                                    forKey:kTermsAcceptedKey];
            [[NSUserDefaults standardUserDefaults] synchronize];
            if (onAccept) {
                onAccept(YES);
            }
        } cancelHandler:^{
            if (onAccept) {
                onAccept(NO);
            }
        }];
        alert.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        [presentingVC presentViewController:alert animated:YES completion:nil];
    }
    else {
        OLTermsAlertController *alert = [OLTermsAlertController alertWithTitle:title content:attr onAccept:onAccept];
        [presentingVC presentViewController:alert animated:YES completion:nil];
    }
}

@end

@implementation OLTermsAlertController

+ (instancetype)alertWithTitle:(NSString *)title content:(NSAttributedString *)content onAccept:(void (^)(BOOL))onAccept {
    
    OLTermsAlertController *alert =
    [OLTermsAlertController alertControllerWithTitle:title
                                                 message:@""
                                      preferredStyle:UIAlertControllerStyleAlert];
    alert.onAccept = onAccept;
    
    // 按钮
    UIAlertAction *agree = [UIAlertAction actionWithTitle:@"同意"
                                                    style:UIAlertActionStyleDefault
                                                  handler:^(UIAlertAction * _Nonnull action) {
        [[NSUserDefaults standardUserDefaults] setBool:YES
                                                forKey:kTermsAcceptedKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
        if (alert.onAccept) alert.onAccept(YES);
    }];
    
    UIAlertAction *disagree = [UIAlertAction actionWithTitle:@"不同意"
                                                       style:UIAlertActionStyleCancel
                                                     handler:^(UIAlertAction * _Nonnull action) {
        if (alert.onAccept) alert.onAccept(NO);
    }];
    
    [alert addAction:agree];
    [alert addAction:disagree];
    
    if (@available(iOS 13.0, *)) {
    }
    else {
        // 用 UITextView 装富文本
        UITextView *textView = [[UITextView alloc] init];
        textView.attributedText = content;
        textView.editable = NO;
        textView.scrollEnabled = NO;
        textView.textContainerInset = UIEdgeInsetsZero;
        textView.textContainer.lineFragmentPadding = 0;
        textView.backgroundColor = nil;
        textView.delegate = alert;
        [textView sizeToFit];
        
        [alert setValue:textView forKey:@"contentViewController"]; // KVC 注入
    }
    
    return alert;
}

#pragma mark - UITextViewDelegate 处理点击链接


- (BOOL)textView:(UITextView *)textView
shouldInteractWithURL:(NSURL *)URL
         inRange:(NSRange)characterRange {
    
    if (@available(iOS 10.0, *)) {
        if ([[UIApplication sharedApplication] canOpenURL:URL]) {
            [[UIApplication sharedApplication] openURL:URL options:@{} completionHandler:^(BOOL finish){
                
            }];
        }
    }
    else {
        if ([[UIApplication sharedApplication] canOpenURL:URL]) {
            [[UIApplication sharedApplication] openURL:URL];
        }
    }
    return NO;  // 已手动处理
}

@end
