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/utils/index.dart';
import '../../../common/widgets/index.dart';
import 'index.dart';

class InnerWebviewController extends GetxController implements JsNavigationInterface {
  InnerWebviewController();

  final state = InnerWebviewState();

  // webview控件的控制器
  final GlobalKey webViewKey = GlobalKey();
  InAppWebViewController? webviewController;
  // 安装转化js
  var isInstallJsName = false;
  // webview 通用方法
  final webviewHelper = WebviewHelper();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    final map = Get.arguments;
    if (map != null) {
      final uri = map['uri'] as Uri?;
      if (uri != null) {
        openUrl(uri);
      } else {
        Loading.showError('args_error'.tr);
        Get.back();
      }
    }
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  @override
  void closeWindow() {
    OLogger.d('执行了 jsapi close ');
    Get.back();
  }
  
  @override
  void goBack() {
    OLogger.d('执行了 jsapi goBack ');
    tapBackBtn();
  }
  
  @override
  void setNavigationTitle(String title) {
    OLogger.d('执行了 jsapi setNavigationTitle $title ');
    state.title = title;
  }

  void openUrl(Uri? uri) async {
    if (uri == null) {
      return ;
    }
    var host = O2ApiManager.instance.getWebHost();
    var domain = uri.host;
    // if (host.isNotEmpty && host.isIPv4) {
    //   domain = host; // ip地址
    // } else {
    //   domain = uri.host;
    // }
    var tokenName = O2ApiManager.instance.tokenName;
    var token = O2ApiManager.instance.o2User?.token ?? '';
    OLogger.d(
        "加载webview cookie，url: $uri domain: $domain tokenName: $tokenName token: $token");
    if (token.isNotEmpty) {
      CookieManager cookieManager = CookieManager.instance();
      await cookieManager.deleteAllCookies();
      await cookieManager.setCookie(
          url: uri,
          name: tokenName,
          value: token,
          domain: (domain.isEmpty ? host : domain));
    }
    
    state.openUri = uri;
    OLogger.d("打开网址： $uri");
  }

  ///
  /// 点击appbar 返回按钮
  ///
  void tapBackBtn() async {
    if (await webviewController?.canGoBack() == true) {
      webviewController?.goBack();
    } else {
      Get.back();
    }
  }

  void tapCloseBtn() {
    Get.back();
  }

  /// 
  void tapShowMenu() {
    final context = Get.context;
    if (context == null){
      return;
    }
    O2UI.showBottomSheetWithCancel(context, [
      ListTile(
        title: Align(
                alignment: Alignment.center,
                child: Text('common_open_with_default_browser'.tr,
                    style: Theme.of(context).textTheme.bodyMedium),
              ),
        onTap: () {
           Navigator.pop(context);
          _openCurrentUrlWithDefaultBrowser();
        },
      )
    ]);
  }

  void _openCurrentUrlWithDefaultBrowser() async {
    final uri = await webviewController?.getUrl();
    if (uri != null) {
      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 ${uri.toString()} 失败！');
        }
      }
    }
  }

  ///
  /// 加载js通道
  /// 在 webview onWebViewCreated 的时候加载
  ///
  void setupWebviewJsHandler(InAppWebViewController c) async {
    webviewController = c;
    webviewHelper.setupWebviewJsHandler(c);
    webviewHelper.setupJsNavigationInterface(this);
  }
  /// 
  /// webview 加载进度
  /// progressChanged == 100的时候加载
  /// 
  void progressChanged(InAppWebViewController c, int p) {
    OLogger.d("o2Webview process progress: $p");
    // 这里把  inappwebview的 js handler 方式修改成 我们自定义的
    if (p == 100 && !isInstallJsName) {
      isInstallJsName = true;
      webviewHelper.changeJsHandlerFunName(c);
    }
  }

}
