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

import '../../../../common/api/index.dart';
import '../../../../common/models/webview/js_message.dart';
import '../../../../common/utils/index.dart';
import '../../../../common/values/index.dart';
import '../../../../common/widgets/index.dart';
import 'index.dart';
import 'subject_reply/index.dart';

class BbsSubjectController extends GetxController implements JsNavigationInterface {
  BbsSubjectController();

  final state = BbsSubjectState();
  final channel = O2FlutterMethodChannelUtils();

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

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

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    var map = Get.arguments;
    if (map == null) {
      Loading.toast('args_error'.tr);
      Get.back();
      return;
    }
    subjectId = map["subjectId"] ?? "";
    OLogger.d("主题id: $subjectId ");
    if (subjectId.isEmpty) {
      Loading.toast('args_error'.tr);
      Get.back();
      return;
    }
    state.title = map["title"] ?? "bbs_subject_view".tr;
    OLogger.d("主题标题 title: ${state.title} ");
    _initBBSSubjectUrl(subjectId);
    _loadSubjectPermission(subjectId);
    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;
  }

  // 初始化帖子webview
  void _initBBSSubjectUrl(String id) async {
    var url = O2ApiManager.instance.getBBSSubjectUrl(id) ?? "";
    if (url.isNotEmpty) {
      final uurl = Uri.parse(url);
      var host = O2ApiManager.instance.getWebHost();
      var domain = uurl.host;
      var tokenName = O2ApiManager.instance.tokenName;
      var token = O2ApiManager.instance.o2User?.token ?? '';
      OLogger.d(
          "加载webview cookie，url: $url domain: $domain tokenName: $tokenName token: $token");
      CookieManager cookieManager = CookieManager.instance();
      await cookieManager.deleteAllCookies();
      await cookieManager.setCookie(
          url: uurl,
          name: tokenName,
          value: token,
          domain: (domain.isEmpty ? host : domain));
      state.url = url;
    }
    OLogger.d("打开网址： $url");
  }

  // 请求查询回帖权限
  Future<void> _loadSubjectPermission(String id) async {
    final p = await BBSAssembleControlService.to.subjectPermission(id);
    if (p != null) {
      state.canWriteComment = p.replyPublishAble == true;
      state.canDelete = p.manageAble == true || p.editAble == true;
    }
  }

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

  void deleteSubject() {
    final context = Get.context;
    if (context != null) {
      O2UI.showConfirm(context, 'bbs_subject_delete_confirm'.tr, okPressed: ()=> _deleteSubjectRequest());
    }
  }

  Future<void> _deleteSubjectRequest() async {
    final id = await BBSAssembleControlService.to.deleteSubject(subjectId);
    if (id != null) {
      Get.back();
      Loading.toast('common_delete_success'.tr);
    }
  }
  ///
  /// 写评论
  void writecomments() {
    openWriteComments();
  }


  void openWriteComments({String parentId = '', String replyHint = ''}) async {
    dynamic id = await SubjectReplyPage.open(subjectId, replyParentId: parentId, replyHint: replyHint);
    if (id != null && id is String) {
      OLogger.d('有返回id：$id');
      await webviewController?.evaluateJavascript(source: 'window.layout.showReply("$id")');
    }
  } 

  ///
  /// 加载js通道
  ///
  void setupWebviewJsHandler(InAppWebViewController c) async {
    webviewController = c;
    webviewController?.addJavaScriptHandler(
        handlerName: O2.webviewChannelNameCommonKey,
        callback: (msgs) {
          OLogger.d(
              "js 通信， name: ${O2.webviewChannelNameCommonKey} msg: $msgs");
          if (msgs.isNotEmpty) {
            String msg = msgs[0] as String? ?? "";
            _jsChannelMessageReceived(msg);
          }
        });
    webviewHelper.setupWebviewJsHandler(c);
    webviewHelper.setupJsNavigationInterface(this);
  }
  

  ///
  /// 接收js通道返回数据
  ///   h5上调用js执行flutter这边的原生方法
  ///
  // void jsChannelMessageReceived(JavascriptMessage message) {
  // if (message.message.isNotEmpty) {
  void _jsChannelMessageReceived(String message) {
    OLogger.d("h5执行原生方法，message: $message");
    if (message.isEmpty) {
      return;
    }
    var jsMessage = JsMessage.fromJson(O2Utils.parseStringToJson(message));
    switch (jsMessage.type) {
      // case "closeWork":
      //   _closeWork();
      //   break;
      case "bbsReply":
        _bbsReply(jsMessage.data);
        break;
      default:
        break;
    }
    _executeCallbackJs(jsMessage.callback, null);
  }

  ///
  /// 如果有callback函数 就执行
  ///
  void _executeCallbackJs(String? callback, dynamic result) {
    if (callback != null && callback.isNotEmpty) {
      if (result != null) {
        webviewController?.evaluateJavascript(source: '$callback($result)');
      } else {
        webviewController?.evaluateJavascript(source: '$callback()');
      }
    }
  }

  void _bbsReply(Map<String, dynamic>? data) async {
    if (data != null) {
      String parentId = data['parentId'] ?? '';
      OLogger.d('来自webview的回复 parentId: $parentId');
      if (parentId.isNotEmpty) {
        var replyInfo = await BBSAssembleControlService.to.getReplyInfo(parentId);
        if (replyInfo != null) {
          String hint = '';
          if (replyInfo.creatorNameShort != null && replyInfo.creatorNameShort?.isNotEmpty == true) {
            hint = 'bbs_subject_reply_parent_hint'.trArgs([replyInfo.creatorNameShort??'']);
          } else  if (replyInfo.creatorName != null && replyInfo.creatorName?.isNotEmpty == true) {
            hint = 'bbs_subject_reply_parent_hint'.trArgs([replyInfo.creatorName??'']);
          }
          openWriteComments(parentId: parentId, replyHint: hint);
        }
      }
    }
  }


}
