//
//  KKAutoOperateDemoViewController.m
//  KKLife
//
//  自动化操作测试 Demo：
//  1. 使用 WKWebView 打开百度首页
//  2. 顶部覆盖一层操作面板（播放/暂停按钮、关键字输入）
//  3. 点击“播放”后，在网页加载完成时截图 -> 调用识别接口
//  4. 拿到按钮坐标后，通过 JS 在网页内自动触发点击
//  5. 点击“暂停”移除覆层，还原为用户手动操作
//

#import "KKAutoOperateDemoViewController.h"
#import <WebKit/WebKit.h>
#import "Constants.h"
#import "UIButton+ImageTitleSpacing.h"

static NSString * const kAutoOperateRecognizeURL = @"http://local.weface.com.cn:9091/api/screenshot-recognition/recognize";

@interface KKAutoOperateDemoViewController ()<WKNavigationDelegate>

@property (nonatomic, strong) WKWebView *webView;

/// 自定义导航栏（含返回按钮）
@property (nonatomic, strong) UIView *navBarView;

/// 覆盖在页面最上方的操作层
@property (nonatomic, strong) UIView *overlayView;
@property (nonatomic, strong) UIButton *playButton;
@property (nonatomic, strong) UITextField *keywordField;

/// 当前是否处于“自动播放（自动化操作）”状态
@property (nonatomic, assign) BOOL isPlaying;

/// Web 页面是否已完成首次加载
@property (nonatomic, assign) BOOL webViewDidFinishFirstLoad;

/// 最近一次截图对应的原始像素宽高
@property (nonatomic, assign) CGFloat lastImagePixelWidth;
@property (nonatomic, assign) CGFloat lastImagePixelHeight;

@end

@implementation KKAutoOperateDemoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"自动化操作 Demo";
    
    [self setupNavBar];
    [self setupWebView];
    [self setupOverlayView];
}

#pragma mark - UI

- (void)setupNavBar {
    UIView *nav = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    nav.backgroundColor = K_MainColor;
    [self.view addSubview:nav];
    self.navBarView = nav;
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    UIImage *backImg = [UIImage imageNamed:@"返回"];
    if (backImg) {
        [backBtn setImage:backImg forState:UIControlStateNormal];
    }
    backBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    backBtn.frame = CGRectMake(0, cl_kStatusBarHeight, 80, cl_kNavBarHeight);
    [backBtn addTarget:self action:@selector(navBackButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [nav addSubview:backBtn];
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"自动化操作 Demo";
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont boldSystemFontOfSize:17];
    titleLabel.frame = CGRectMake((ScreenWidth - 160) / 2, cl_kStatusBarHeight, 160, cl_kNavBarHeight);
    [nav addSubview:titleLabel];
}

- (void)navBackButtonTapped {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setupWebView {
    CGFloat top = cl_kNavigationBarHeight;
    CGRect frame = CGRectMake(0, top, ScreenWidth, ScreenHeight - top);
    
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    WKWebView *webView = [[WKWebView alloc] initWithFrame:frame configuration:config];
    webView.navigationDelegate = self;
    webView.scrollView.showsVerticalScrollIndicator = NO;
    webView.scrollView.showsHorizontalScrollIndicator = NO;
    self.webView = webView;
    [self.view addSubview:webView];
    
    NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];
    if (url) {
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [webView loadRequest:request];
    }
}

- (void)setupOverlayView {
    // 覆层占据 webView 区域上方的一条带，点击事件在该层上处理
    UIView *overlay = [[UIView alloc] initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, 60)];
    overlay.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
    overlay.userInteractionEnabled = YES;
    self.overlayView = overlay;
    [self.view addSubview:overlay];
    
    // 播放 / 暂停按钮
    UIButton *playBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [playBtn setTitle:@"播放" forState:UIControlStateNormal];
    [playBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    playBtn.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    playBtn.frame = CGRectMake(12, 10, 72, 40);
    playBtn.layer.cornerRadius = 6;
    playBtn.layer.masksToBounds = YES;
    playBtn.backgroundColor = [UIColor colorWithRed:0.14 green:0.66 blue:0.28 alpha:1];
    [playBtn addTarget:self action:@selector(playButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [overlay addSubview:playBtn];
    self.playButton = playBtn;
    
    // 关键字输入框：默认“百度一下”作为要识别的按钮文案
    UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(playBtn.frame) + 12, 10, ScreenWidth - CGRectGetMaxX(playBtn.frame) - 24, 40)];
    field.placeholder = @"需要识别的按钮文案，例如：百度一下";
    field.textColor = [UIColor whiteColor];
    field.tintColor = [UIColor whiteColor];
    field.font = [UIFont systemFontOfSize:14];
    field.text = @"百度一下";
    field.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.15];
    field.layer.cornerRadius = 6;
    field.layer.masksToBounds = YES;
    field.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 8, 40)];
    field.leftViewMode = UITextFieldViewModeAlways;
    self.keywordField = field;
    [overlay addSubview:field];
    
    self.isPlaying = NO;
    self.webViewDidFinishFirstLoad = NO;
}

#pragma mark - Actions

- (void)playButtonTapped {
    self.isPlaying = !self.isPlaying;
    
    if (self.isPlaying) {
        [self.playButton setTitle:@"暂停" forState:UIControlStateNormal];
        // 播放时：覆层覆盖整个 webView 区域，阻止用户误触
        CGFloat navH = cl_kNavigationBarHeight;
        self.overlayView.frame = CGRectMake(0, navH, ScreenWidth, ScreenHeight - navH);
        self.overlayView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.25];
        [self.view bringSubviewToFront:self.overlayView];
        
        if (self.webViewDidFinishFirstLoad) {
            [self startAutoOperateFlow];
        }
    } else {
        [self.playButton setTitle:@"播放" forState:UIControlStateNormal];
        // 暂停时：去掉页面覆层，只保留顶部操作条，方便用户自己操作
        self.overlayView.frame = CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, 60);
        self.overlayView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.2];
    }
}

#pragma mark - 自动化主流程

/// 开始一次“截图 -> 识别 -> 自动点击”的流程
- (void)startAutoOperateFlow {
    if (!self.isPlaying) {
        return;
    }
    
    // 1. 对 webView 截图
    WKSnapshotConfiguration *config = [[WKSnapshotConfiguration alloc] init];
    config.rect = self.webView.bounds;
    __weak typeof(self) weakSelf = self;
    [self.webView takeSnapshotWithConfiguration:config completionHandler:^(UIImage * _Nullable snapshotImage, NSError * _Nullable error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if (!strongSelf) return;
        
        if (error || !snapshotImage) {
            NSLog(@"[自动化 Demo] 截图失败: %@", error);
            return;
        }
        
        CGFloat scale = snapshotImage.scale;
        strongSelf.lastImagePixelWidth = snapshotImage.size.width * scale;
        strongSelf.lastImagePixelHeight = snapshotImage.size.height * scale;
        
        NSString *base64 = [strongSelf base64StringFromImage:snapshotImage];
        if (base64.length == 0) {
            NSLog(@"[自动化 Demo] 图片转 base64 失败");
            return;
        }
        
        NSString *keyword = strongSelf.keywordField.text.length > 0 ? strongSelf.keywordField.text : @"百度一下";
        [strongSelf callRecognizeAPIWithImageBase64:base64 keyword:keyword];
    }];
}

- (NSString *)base64StringFromImage:(UIImage *)image {
    NSData *data = UIImagePNGRepresentation(image);
    if (!data) {
        data = UIImageJPEGRepresentation(image, 0.9);
    }
    return [data base64EncodedStringWithOptions:0];
}

/// 调用后端识别接口
- (void)callRecognizeAPIWithImageBase64:(NSString *)imageBase64 keyword:(NSString *)keyword {
    if (!self.isPlaying) {
        return;
    }
    
    NSURL *url = [NSURL URLWithString:kAutoOperateRecognizeURL];
    if (!url) {
        NSLog(@"[自动化 Demo] 识别接口 URL 无效");
        return;
    }
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    NSDictionary *body = @{
        @"image": imageBase64 ?: @"",
        @"keyword": keyword ?: @"",
        @"imageWidth": @(self.lastImagePixelWidth),
        @"imageHeight": @(self.lastImagePixelHeight)
    };
    
    NSError *jsonError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&jsonError];
    if (jsonError || !jsonData) {
        NSLog(@"[自动化 Demo] JSON 序列化失败: %@", jsonError);
        return;
    }
    request.HTTPBody = jsonData;
    
    __weak typeof(self) weakSelf = self;
    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if (!strongSelf) return;
        
        if (error) {
            NSLog(@"[自动化 Demo] 识别接口请求失败: %@", error);
            return;
        }
        if (!data) {
            NSLog(@"[自动化 Demo] 识别接口返回空数据");
            return;
        }
        
        NSError *parseError = nil;
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&parseError];
        if (parseError || ![json isKindOfClass:[NSDictionary class]]) {
            NSLog(@"[自动化 Demo] 识别接口解析失败: %@", parseError);
            return;
        }
        
        BOOL success = [json[@"success"] boolValue];
        if (!success) {
            NSLog(@"[自动化 Demo] 识别失败: %@", json[@"message"]);
            return;
        }
        
        NSDictionary *centerPoint = json[@"centerPoint"];
        if (![centerPoint isKindOfClass:[NSDictionary class]]) {
            NSLog(@"[自动化 Demo] 返回数据缺少 centerPoint");
            return;
        }
        
        NSNumber *xNum = centerPoint[@"x"];
        NSNumber *yNum = centerPoint[@"y"];
        if (![xNum isKindOfClass:[NSNumber class]] || ![yNum isKindOfClass:[NSNumber class]]) {
            NSLog(@"[自动化 Demo] centerPoint 坐标格式错误");
            return;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [strongSelf triggerAutoClickWithImagePoint:CGPointMake(xNum.floatValue, yNum.floatValue)];
        });
    }] resume];
}

/// 将图片坐标转换为 Web 视口坐标，并在页面内自动触发点击
- (void)triggerAutoClickWithImagePoint:(CGPoint)imagePoint {
    if (!self.isPlaying || self.lastImagePixelWidth <= 0 || self.lastImagePixelHeight <= 0) {
        return;
    }
    
    // 截图 = 当前可视区域，API 返回的是截图像素坐标，映射到视口（viewport）坐标
    CGFloat viewWidth = CGRectGetWidth(self.webView.bounds);
    CGFloat viewHeight = CGRectGetHeight(self.webView.bounds);
    if (viewWidth <= 0 || viewHeight <= 0) {
        return;
    }
    
    CGFloat scaleX = viewWidth / self.lastImagePixelWidth;
    CGFloat scaleY = viewHeight / self.lastImagePixelHeight;
    CGFloat viewX = imagePoint.x * scaleX;
    CGFloat viewY = imagePoint.y * scaleY;
    // elementFromPoint 使用视口坐标，不需要加 contentOffset
    int px = (int)round(viewX);
    int py = (int)round(viewY);
    
    // 先 .click()，再尝试派发 mousedown/mouseup/click 提高兼容性（部分站点如百度会监听这些事件）
    NSString *js = [NSString stringWithFormat:
                    @"(function(){"
                    " var x = %d, y = %d;"
                    " var el = document.elementFromPoint(x, y);"
                    " if(!el) return 'no-element';"
                    " el.click();"
                    " try {"
                    "   var r = el.getBoundingClientRect();"
                    "   var cx = r.left + r.width/2, cy = r.top + r.height/2;"
                    "   ['mousedown','mouseup','click'].forEach(function(n){"
                    "     var e = new MouseEvent(n, { bubbles:true, cancelable:true, view:window, clientX:cx, clientY:cy });"
                    "     el.dispatchEvent(e);"
                    "   });"
                    " } catch(err) {}"
                    " return 'clicked';"
                    "})();",
                    px, py];
    
    [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        if (error) {
            NSLog(@"[自动化 Demo] JS 自动点击失败: %@", error);
        } else {
            NSLog(@"[自动化 Demo] JS 自动点击结果: %@", result);
        }
    }];
}

#pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    self.webViewDidFinishFirstLoad = YES;
    
    // 若用户已点击“播放”，则在页面加载完成后自动开始一次识别流程
    if (self.isPlaying) {
        [self startAutoOperateFlow];
    }
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"[自动化 Demo] 网页加载失败: %@", error);
}

@end

