#import "DemoViewController.h"
#import "ConfiguratorDemoViewController.h"
#import <TencentQianWebView/TencentQianWebView.h>

#pragma mark - UIColor / UIFont 兼容（iOS 11-12 回退静态值）

static UIColor *DemoBackground(void) {
    if (@available(iOS 13.0, *)) { return [UIColor systemBackgroundColor]; }
    return [UIColor whiteColor];
}
static UIColor *DemoSecondaryBackground(void) {
    if (@available(iOS 13.0, *)) { return [UIColor secondarySystemBackgroundColor]; }
    return [UIColor colorWithWhite:0.95 alpha:1];
}
static UIColor *DemoSecondaryLabel(void) {
    if (@available(iOS 13.0, *)) { return [UIColor secondaryLabelColor]; }
    return [UIColor darkGrayColor];
}
static UIFont *DemoMonoFont(void) {
    if (@available(iOS 13.0, *)) { return [UIFont monospacedSystemFontOfSize:12 weight:UIFontWeightRegular]; }
    return [UIFont fontWithName:@"Menlo" size:12] ?: [UIFont systemFontOfSize:12];
}

@interface DemoViewController ()
@property (nonatomic, strong) UITextField *urlField;
@property (nonatomic, strong) UITextView *logView;
@property (nonatomic, strong) UITextField *prewarmBizTypeField;
@property (nonatomic, strong) NSMutableArray<NSString *> *bizTypeOptions;
@end

@implementation DemoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Tencent Qian H5 Demo";
    self.view.backgroundColor = DemoBackground();

    UILabel *hint = [[UILabel alloc] init];
    hint.text = @"粘贴客户后端发起的 flowId URL,演示三种集成方式:";
    hint.numberOfLines = 0;
    hint.font = [UIFont systemFontOfSize:13];
    hint.textColor = DemoSecondaryLabel();

    UITextField *urlField = [[UITextField alloc] init];
    urlField.placeholder = @"https://quick.qian.tencent.cn/sign/...?flowId=...";
    urlField.borderStyle = UITextBorderStyleRoundedRect;
    urlField.font = [UIFont systemFontOfSize:14];
    urlField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    urlField.autocorrectionType = UITextAutocorrectionTypeNo;
    urlField.returnKeyType = UIReturnKeyDone;
    urlField.delegate = self;
    self.urlField = urlField;

    UIButton *btn1 = [self makeButtonWithTitle:@"① 容器模式打开签署页" action:@selector(onContainer)];
    UIButton *btn2 = [self makeButtonWithTitle:@"② 配置模式改造既有 WebView" action:@selector(onConfigurator)];
    UIButton *btn3 = [self makeButtonWithTitle:@"③ 打开自检页(beta)" action:@selector(onCompatibility)];

    // ── 预热档位（真机验证）：bizType 输入 + 一行三档，颜色由浅到深表达「预热深度递增」 ──
    UILabel *prewarmLabel = [[UILabel alloc] init];
    prewarmLabel.text = @"预热bizType:";
    prewarmLabel.font = [UIFont systemFontOfSize:13];
    prewarmLabel.textColor = DemoSecondaryLabel();
    [prewarmLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];

    UITextField *prewarmBizTypeField = [[UITextField alloc] init];
    prewarmBizTypeField.text = @"single-sign";
    prewarmBizTypeField.borderStyle = UITextBorderStyleRoundedRect;
    prewarmBizTypeField.font = [UIFont systemFontOfSize:13];
    prewarmBizTypeField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    prewarmBizTypeField.autocorrectionType = UITextAutocorrectionTypeNo;
    self.prewarmBizTypeField = prewarmBizTypeField;
    [prewarmBizTypeField setContentHuggingPriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];
    [prewarmBizTypeField setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];

    self.bizTypeOptions = [@[ @"single-sign", @"batch-sign", @"enterprise-register", @"join-enterprise" ] mutableCopy];

    UIButton *bizTypePickerBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [bizTypePickerBtn setTitle:@"▼" forState:UIControlStateNormal];
    bizTypePickerBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [bizTypePickerBtn setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
    [bizTypePickerBtn setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
    [bizTypePickerBtn addTarget:self action:@selector(onShowBizTypePicker) forControlEvents:UIControlEventTouchUpInside];

    UIStackView *prewarmRow = [[UIStackView alloc] initWithArrangedSubviews:@[prewarmLabel, prewarmBizTypeField, bizTypePickerBtn]];
    prewarmRow.axis = UILayoutConstraintAxisHorizontal;
    prewarmRow.spacing = 8;
    prewarmRow.alignment = UIStackViewAlignmentCenter;

    UIButton *btnMinimal = [self makePrewarmButtonWithTitle:@"迷你·DNS"
                                                      color:[UIColor colorWithRed:0x8C/255.0 green:0x8C/255.0 blue:0x8C/255.0 alpha:1]
                                                     action:@selector(onPrewarmMinimal)];
    UIButton *btnLight = [self makePrewarmButtonWithTitle:@"LIGHT·内核"
                                                    color:[UIColor colorWithRed:0x52/255.0 green:0xC4/255.0 blue:0x1A/255.0 alpha:1]
                                                   action:@selector(onPrewarmLight)];
    UIButton *btnHeavy = [self makePrewarmButtonWithTitle:@"HEAVY·池"
                                                    color:[UIColor colorWithRed:0x23/255.0 green:0x78/255.0 blue:0x04/255.0 alpha:1]
                                                   action:@selector(onPrewarmHeavy)];
    UIStackView *prewarmButtons = [[UIStackView alloc] initWithArrangedSubviews:@[btnMinimal, btnLight, btnHeavy]];
    prewarmButtons.axis = UILayoutConstraintAxisHorizontal;
    prewarmButtons.spacing = 8;
    prewarmButtons.distribution = UIStackViewDistributionFillEqually;

    UIButton *btnRelease = [self makePrewarmButtonWithTitle:@"释放预热池（签署完成后主动释放）"
                                                      color:[UIColor colorWithRed:0xFF/255.0 green:0x4D/255.0 blue:0x4F/255.0 alpha:1]
                                                     action:@selector(onReleasePool)];

    UITextView *logView = [[UITextView alloc] init];
    logView.font = DemoMonoFont();
    logView.editable = NO;
    logView.backgroundColor = DemoSecondaryBackground();
    logView.layer.cornerRadius = 6;
    logView.textContainerInset = UIEdgeInsetsMake(8, 8, 8, 8);
    self.logView = logView;

    UILabel *logTitle = [[UILabel alloc] init];
    logTitle.text = @"SDK 回调日志";
    logTitle.font = [UIFont boldSystemFontOfSize:14];
    UIButton *clearBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [clearBtn setTitle:@"清空" forState:UIControlStateNormal];
    [clearBtn addTarget:self action:@selector(onClear) forControlEvents:UIControlEventTouchUpInside];
    UIStackView *logHeader = [[UIStackView alloc] initWithArrangedSubviews:@[
        logTitle, [[UIView alloc] init], clearBtn
    ]];
    logHeader.axis = UILayoutConstraintAxisHorizontal;
    logHeader.alignment = UIStackViewAlignmentCenter;

    UIStackView *stack = [[UIStackView alloc] initWithArrangedSubviews:@[
        prewarmRow, prewarmButtons, btnRelease, hint, urlField, btn1, btn2, btn3, logHeader, logView
    ]];
    stack.axis = UILayoutConstraintAxisVertical;
    stack.spacing = 8;
    stack.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:stack];

    [NSLayoutConstraint activateConstraints:@[
        [stack.topAnchor      constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor constant:16],
        [stack.leadingAnchor  constraintEqualToAnchor:self.view.leadingAnchor constant:16],
        [stack.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-16],
        [stack.bottomAnchor   constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor constant:-16],
    ]];

    // 配置预热（UA 与 buildConfig 对齐，池实例才能复用）
    TQPrewarmConfig *prewarmCfg = [TQPrewarmConfig defaultConfig];
    prewarmCfg.environment = TQPrewarmEnvironmentBeta;
    prewarmCfg.userAgentExtra = @"qianwv-demo/1.0.0";
    prewarmCfg.preferredLanguage = @"zh-CN";
    [TQWebViewPrewarmer configure:prewarmCfg];

    [TQWebViewPrewarmer getMenuBizTypes:^(NSArray<NSString *> *bizTypes) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.bizTypeOptions = [bizTypes mutableCopy];
        });
    }];
}

- (UIButton *)makeButtonWithTitle:(NSString *)title action:(SEL)action {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    [btn setTitle:title forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightMedium];
    btn.backgroundColor = [UIColor systemBlueColor];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.layer.cornerRadius = 8;
    btn.contentEdgeInsets = UIEdgeInsetsMake(12, 12, 12, 12);
    [btn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    return btn;
}

#pragma mark - 三按钮

- (void)onContainer {
    NSString *url = [self currentUrl];
    if (!url) return;
    TQWebViewConfig *cfg = [TQWebViewConfig defaultConfig];
    cfg.topBarTitle = @"电子签署(容器模式)";
    cfg.userAgentExtra = @"qianwv-demo/1.0.0";
    cfg.confirmBeforeClose = YES;
    [TQWebView openFromPresenter:self
                              url:url
                           config:cfg
                        callbacks:[self makeCallbacks]
                         animated:YES
                       completion:nil];
}

- (void)onConfigurator {
    NSString *url = [self currentUrl];
    if (!url) return;
    ConfiguratorDemoViewController *vc =
        [[ConfiguratorDemoViewController alloc] initWithUrl:url callbacks:[self makeCallbacks]];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)onCompatibility {
    [TQWebView openCompatibilityTestFromPresenter:self
                                         customUrl:nil
                                            config:nil
                                         callbacks:[self makeCallbacks]
                                          animated:YES];
}

- (void)onClear {
    self.logView.text = @"";
}

- (void)onShowBizTypePicker {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选择 bizType"
                                                                    message:nil
                                                             preferredStyle:UIAlertControllerStyleActionSheet];
    for (NSString *biz in self.bizTypeOptions) {
        [alert addAction:[UIAlertAction actionWithTitle:biz style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            self.prewarmBizTypeField.text = biz;
        }]];
    }
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 预热（真机验证）

- (void)triggerPrewarm:(TQPrewarmLevel)level {
    NSString *bizType = [(self.prewarmBizTypeField.text ?: @"")
                         stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (bizType.length == 0) bizType = @"single-sign";
    if (level == TQPrewarmLevelMinimal) {
        [TQWebViewPrewarmer prewarm:TQPrewarmLevelMinimal bizType:nil];
        [self appendLog:@"[prewarm] MINIMAL (DNS) triggered"];
    } else if (level == TQPrewarmLevelLight) {
        [TQWebViewPrewarmer prewarm:TQPrewarmLevelLight bizType:bizType];
        [self appendLog:[NSString stringWithFormat:@"[prewarm] LIGHT (kernel init) bizType=%@ triggered", bizType]];
    } else {
        [TQWebViewPrewarmer prewarm:TQPrewarmLevelHeavy bizType:bizType];
        [self appendLog:[NSString stringWithFormat:@"[prewarm] HEAVY (off-screen pool) bizType=%@ triggered", bizType]];
    }
    [self showToast:@"已触发预热"];
}

- (void)onPrewarmMinimal { [self triggerPrewarm:TQPrewarmLevelMinimal]; }
- (void)onPrewarmLight   { [self triggerPrewarm:TQPrewarmLevelLight]; }
- (void)onPrewarmHeavy   { [self triggerPrewarm:TQPrewarmLevelHeavy]; }

- (void)onReleasePool {
    [TQWebViewPrewarmer releaseAll];
    [self appendLog:@"[prewarm] pool released (releaseAll)"];
    [self showToast:@"已释放预热池"];
}

/// 【接入方示范】业务入口页销毁 == 业务流程结束 → 释放预热池。
///
/// 建议在承载签署流程的业务入口页/会话终点（如本 VC 的 dealloc）调用 releaseAll：
/// 它会销毁预热 WKWebView 实例 并重置去重状态，使预热系统回到初始态——
/// 这样用户下次再进入同一业务流程时，prewarm 能重新生效。
/// 若只想临时回收内存、仍保留“本会话已预热过”的去重记账，则改用 release。
- (void)dealloc {
    [TQWebViewPrewarmer releaseAll];
}

- (UIButton *)makePrewarmButtonWithTitle:(NSString *)title color:(UIColor *)color action:(SEL)action {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    [btn setTitle:title forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    btn.backgroundColor = color;
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.layer.cornerRadius = 6;
    btn.contentEdgeInsets = UIEdgeInsetsMake(10, 8, 10, 8);
    [btn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    return btn;
}

#pragma mark - 工具

- (nullable NSString *)currentUrl {
    NSString *s = [(self.urlField.text ?: @"")
                   stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (s.length == 0) {
        UIAlertController *alert =
            [UIAlertController alertControllerWithTitle:nil
                                                message:@"请先粘贴 flowId URL"
                                         preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        return nil;
    }
    return s;
}

- (TQSignCallbacks *)makeCallbacks {
    __weak __typeof(self) weakSelf = self;
    return [TQSignCallbacks callbacksWithOnSignResult:^(TQSignResult *result) {
        __strong __typeof(weakSelf) self = weakSelf;
        if (!self) return;
        [self appendLog:[NSString stringWithFormat:@"⮞ SignResult action=%@ result=%@ flowId=%@ extras=%@",
                          result.action, result.result, result.flowId, result.extras]];

        NSString *human;
        if      ([result.action isEqualToString:TQSignActionSign])       human = @"签署";
        else if ([result.action isEqualToString:TQSignActionFill])       human = @"填写";
        else if ([result.action isEqualToString:TQSignActionRejectSign]) human = @"拒签";
        else if ([result.action isEqualToString:TQSignActionRejectFill]) human = @"拒填";
        else if ([result.action isEqualToString:TQSignActionView])       human = @"查看";
        else if (result.action.length == 0)                              human = @"无 action";
        else human = [NSString stringWithFormat:@"未知 action(%@)", result.action];

        BOOL ok = [result.result isEqualToString:TQSignResultStatusSuccess];
        UIAlertController *alert =
            [UIAlertController alertControllerWithTitle:nil
                                                message:[NSString stringWithFormat:@"%@ %@",
                                                         human, ok ? @"成功" : @"未成功"]
                                         preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定"
                                                  style:UIAlertActionStyleDefault
                                                handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
    } onEvent:^(id<TQSdkEvent> event) {
        __strong __typeof(weakSelf) self = weakSelf;
        if (!self) return;
        [self appendLog:[NSString stringWithFormat:@"• %@", event]];

        // 演示:客户可在 onEvent 中根据事件类型做 UI 反馈
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([event isKindOfClass:[TQWebContentProcessTerminatedEvent class]]) {
                [self showToast:@"页面异常,正在恢复…"];
            }
        });
    }];
}

- (void)appendLog:(NSString *)line {
    dispatch_async(dispatch_get_main_queue(), ^{
        self.logView.text = [self.logView.text stringByAppendingFormat:@"%@\n", line];
        NSRange bottom = NSMakeRange(MAX((NSInteger)self.logView.text.length - 1, 0), 1);
        [self.logView scrollRangeToVisible:bottom];
    });
}

/// 简易 Toast 演示(iOS 无原生 Toast,用临时 UILabel 模拟)
- (void)showToast:(NSString *)message {
    UILabel *label = [[UILabel alloc] init];
    label.text = message;
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:14];
    label.textColor = [UIColor whiteColor];
    label.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.75];
    label.layer.cornerRadius = 8;
    label.clipsToBounds = YES;
    label.numberOfLines = 0;
    label.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:label];
    [NSLayoutConstraint activateConstraints:@[
        [label.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],
        [label.bottomAnchor  constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor constant:-60],
        [label.widthAnchor   constraintLessThanOrEqualToAnchor:self.view.widthAnchor constant:-40],
        [label.heightAnchor  constraintGreaterThanOrEqualToConstant:36],
    ]];
    label.layoutMargins = UIEdgeInsetsMake(8, 16, 8, 16);
    [UIView animateWithDuration:0.3
                          delay:2.0
                        options:UIViewAnimationOptionCurveEaseOut
                     animations:^{ label.alpha = 0; }
                     completion:^(BOOL finished) { [label removeFromSuperview]; }];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

@end
