import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter/services.dart';

class CaptchaPage extends StatefulWidget {
  const CaptchaPage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  State<CaptchaPage> createState() => _CaptchaPageState();
}

class _CaptchaPageState extends State<CaptchaPage> {
  InAppWebViewController? _controller;

  @override
  void initState() {
    super.initState();
  }

  // 处理验证码验证结果
  void _handleCaptchaResult(dynamic captchaVerifyParam) {
    try {
      print('收到验证码参数: $captchaVerifyParam');
      
      // 检查参数是否为空
      if (captchaVerifyParam == null) {
        throw Exception('收到空的验证参数');
      }
      
      // 直接发送验证参数到服务端
      _sendToServer(captchaVerifyParam);
      
    } catch (e) {
      print('处理验证码参数失败: $e');
      _showSnackBar('验证参数处理失败: $e', isError: true);
    }
  }

  // 发送验证参数到服务端（示例）
  Future<void> _sendToServer(dynamic captchaVerifyParam) async {
    try {
      // 这里调用您的服务端API进行二次验证
      print('准备发送到服务端验证: $captchaVerifyParam');
      
      // 模拟服务端验证成功
      _showSnackBar('服务端验证成功', isError: false);
    } catch (e) {
      print('服务端验证失败: $e');
      _showSnackBar('服务端验证失败: $e', isError: true);
    }
  }

  void _showSnackBar(String message, {bool isError = false}) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: isError ? Colors.red : Colors.green,
        duration: const Duration(seconds: 3),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: _buildWebViewContent(),
    );
  }


  // 构建WebView内容
  Widget _buildWebViewContent() {
    return Stack(
      children: [
        InAppWebView(
          initialData: InAppWebViewInitialData(
            data: "",
          ),
          initialOptions: InAppWebViewGroupOptions(
            crossPlatform: InAppWebViewOptions(
              javaScriptEnabled: true,
              useShouldOverrideUrlLoading: true,
            ),
          ),
          onWebViewCreated: (InAppWebViewController controller) async {
            _controller = controller;
            
            // 添加JavaScript处理器
            _controller!.addJavaScriptHandler(
              handlerName: 'testInterface',
              callback: (args) {
                if (args.isNotEmpty) {
                  _handleCaptchaResult(args[0]);
                }
              },
            );
            
            // 加载HTML内容
            try {
              String htmlContent = await rootBundle.loadString('assets/captcha.html');
              await _controller!.loadData(data: htmlContent, baseUrl: WebUri('https://localhost'));
            } catch (e) {
              print('加载HTML失败: $e');
              _showSnackBar('加载验证码页面失败: $e', isError: true);
            }
          },
        ),
      ],
    );
  }
}
