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

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

///
/// url 在 app 内部打开
/// 目前就 ios 和 Android ，pc 端还是打开浏览器
///
class InnerWebviewPage extends GetView<InnerWebviewController> {
  const InnerWebviewPage({Key? key}) : super(key: key);

  static Future<void> open(String url) async {
    Uri uri = Uri.parse(url);
    if (GetPlatform.isDesktop) {
      if (await canLaunchUrl(uri)) {
        final result = await launchUrl(
          uri,
          mode: LaunchMode.externalApplication,
          webViewConfiguration: WebViewConfiguration(headers: <String, String>{
            O2ApiManager.instance.tokenName:
                O2ApiManager.instance.o2User?.token ?? ''
          }),
        );
        if (!result) {
          OLogger.e('打开 url $url 失败！');
        }
      } else {
        Loading.showError('common_error_url'.trArgs([url]));
      }
    } else {
      await Get.toNamed(O2OARoutes.commonInnerWebview,
          arguments: {"uri": uri}, preventDuplicates: false);
    }
  }

  // 主视图
  Widget _buildView() {
    return InAppWebView(
        key: controller.webViewKey,
        initialUrlRequest: URLRequest(url: controller.state.openUri),
        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");
        });
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<InnerWebviewController>(
      builder: (_) {
        return WillPopScope(
            // 拦截物理返回
            onWillPop: () {
              controller.tapBackBtn();
              return Future.value(false);
            },
            child: Scaffold(
              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: Obx(() => Text(controller.state.title)))
                  ],
                ),
                actions: [
                  Obx(() => Visibility(
                      visible: controller.state.openUri != null,
                      child: IconButton(
                        icon: const Icon(Icons.more_vert),
                        onPressed: controller.tapShowMenu,
                      )))
                ],
              ),
              body: SafeArea(
                  child: Obx(
                () => controller.state.openUri == null
                    ? const Center(child: CircularProgressIndicator())
                    : _buildView(),
              )),
            ));
      },
    );
  }
}
