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

import '../../../common/utils/index.dart';
import '../../../common/values/index.dart';
import '../../../common/widgets/index.dart';
import 'index.dart';

class PortalPage extends GetView<PortalController> {
  @override
  final String? tag;

  const PortalPage({Key? key, required this.tag}) : super(key: key);

  static void open(String portalId, {String title = '', String? pageId, String? portalParameters}) async {
    Get.lazyPut<PortalController>(() => PortalController(), tag: portalId);
    await Get.to(PortalPage(tag: portalId),
        arguments: {"portalId": portalId, "title": title, "pageId": pageId, "portalParameters": portalParameters},
        preventDuplicates: false);
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<PortalController>(
      tag: tag,
      builder: (_) {
        return Obx(() {
          AppBar? appBar;
          if (controller.state.isPage) {
            appBar = AppBar(
                automaticallyImplyLeading: false,
                title: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    IconButton(
                      icon: const Icon(Icons.arrow_back),
                      onPressed: () => controller.tapBackBtn(),
                    ),
                    IconButton(
                      icon: const Icon(Icons.close),
                      onPressed: () => controller.tapCloseBtn(),
                    ),
                    Expanded(flex: 1, child: Text(controller.state.title))
                  ],
                ),
                actions: [O2UI.webviewPopupMenu(() => controller.copyLink())]);
          } else if (!controller.state.hiddenAppBar) {
            appBar = AppBar(
              title: Text(controller.state.title),
            );
          }
          return WillPopScope(
            // 拦截物理返回
            onWillPop: () async {
              return await controller.tapBackBtn();
            },
            child: Scaffold(
              appBar: appBar,
              body: SafeArea(
                  child: controller.state.url.isEmpty
                      ? const Center(child: CircularProgressIndicator())
                      : _buildView()),
            ),
          );
        });
      },
    );
  }

  // 主视图
  Widget _buildView() {
    return InAppWebView(
        key: controller.webViewKey,
        initialUrlRequest: URLRequest(url: Uri.parse(controller.state.url)),
        pullToRefreshController: controller.pullToRefreshController,
        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,
            )),
        androidOnGeolocationPermissionsShowPrompt: (controller, origin) async {
          return GeolocationPermissionShowPromptResponse(
              origin: origin, allow: true, retain: true);
        },
        onWebViewCreated: (c) {
          controller.setupWebviewJsHandler(c);
        },
        onLoadStop: (c, url) async {
          controller.pullToRefreshController.endRefreshing();
          OLogger.d("=====> onLoadStop url: $url");
        },
        onScrollChanged: (c, x, y) {
          OLogger.d("=====> onScrollChanged x: $x y: $y");
        },
        onLoadError: (c, url, code, message) {
          OLogger.d("=====> onLoadError url: $url code: $code message: $message");
        },
        onOverScrolled: (controller, x, y, clampedX, clampedY) {
          OLogger.d("=====> onOverScrolled x: $x y: $y clampedX: $clampedX clampedY: $clampedY");
        },
        // onCreateWindow: (c, createWindowRequest) async {
        //   OLogger.d("创建新窗口，，，，${createWindowRequest.request.url}");
        // },
        shouldOverrideUrlLoading: (c, navigationAction) async {
          var uri = navigationAction.request.url!;
          OLogger.d("shouldOverrideUrlLoading uri: $uri");
          // c.loadUrl(urlRequest: URLRequest(url: uri));
          return NavigationActionPolicy.ALLOW;
        },
        onProgressChanged: (c, p) {
          controller.progressChanged(c, p);
          if (p == 100) {
            controller.pullToRefreshController.endRefreshing();
          }
        },
        // h5下载文件
        onDownloadStartRequest: (c, request) async {
          controller.webviewHelper.onFileDownloadStart(request);
        },
        onTitleChanged: ((c, title) {
          OLogger.d('修改网页标题： $title');
          if (title != null && title.isNotEmpty && controller.state.isPage) {
            controller.state.title = title;
          }
        }),
        onConsoleMessage: (c, consoleMessage) {
          OLogger.i("console: $consoleMessage");
        });
  }
}
