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

import '../../../../common/index.dart';
import '../index.dart';

class WebviewOutStatefulWidget extends StatefulWidget {
  const WebviewOutStatefulWidget({Key? key, required this.tag}) : super(key: key);
  final String tag;
  @override
  State<WebviewOutStatefulWidget> createState() =>
      _WebviewOutStatefulWidgetState();
}

class _WebviewOutStatefulWidgetState extends State<WebviewOutStatefulWidget> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return  WebviewWidget(tag: widget.tag);
  }
}

/// WebviewWidget
class WebviewWidget extends GetView<ProcessWebviewController> {
  const WebviewWidget({Key? key, required this.tag}) : super(key: key);
  @override
  final String? tag;
  @override
  Widget build(BuildContext context) {
    return Center(
      child: InAppWebView(
          key: GlobalKey(),
          initialUrlRequest: URLRequest(url: Uri.parse(controller.state.url)),
          initialOptions: InAppWebViewGroupOptions(
              crossPlatform: InAppWebViewOptions(
                useShouldOverrideUrlLoading: true,
                useOnDownloadStart: true,
                javaScriptCanOpenWindowsAutomatically: true,
                mediaPlaybackRequiresUserGesture: false,
                applicationNameForUserAgent: O2.webviewUserAgent
              ),
              android: AndroidInAppWebViewOptions(
                useHybridComposition: true,
                supportMultipleWindows: true,
              ),
              ios: IOSInAppWebViewOptions(
                allowsInlineMediaPlayback: true,
              )),
          onWebViewCreated: (c) {
            controller.setupWebviewJsHandler(c);
          },
          // onCreateWindow: (c, createWindowRequest) async {
          //   OLogger.d("创建新窗口，，，，${createWindowRequest.request.url}");
          // },
          shouldOverrideUrlLoading: (c, navigationAction) async {
            var uri = navigationAction.request.url!;
            OLogger.d("shouldOverrideUrlLoading uri: $uri");
            return NavigationActionPolicy.ALLOW;
          },
          onProgressChanged: (c, p) {
            controller.progressChanged(c, p);
          },
          // h5下载文件
          onDownloadStartRequest: (c, request) async {
            controller.webviewHelper.onFileDownloadStart(request);
          },
          onTitleChanged: ((c, title) {
            OLogger.d('修改网页标题： $title');
            if (title != null && title.isNotEmpty) {
              controller.state.title = title;
            }
          }),
          onConsoleMessage: (c, consoleMessage) {
            OLogger.i("console: $consoleMessage");
          }),
    );
  }
}
