import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:news_getx/config/server.dart';
import 'package:news_getx/data/model/news.dart';
import 'package:webview_flutter/webview_flutter.dart';

import 'detail_state.dart';

class DetailController extends GetxController {
  /// 响应式成员变量
  // 页面是否加载完成
  var isPageFinished = false.obs;

  // webView高度
  var webViewHeight = 200.0.obs;

  /// 成员变量
  // 页面详情
  final DetailState state = DetailState();

  WebViewController webViewController = WebViewController();

  /// 方法
  // 注册js回调
  void _invokeJavascriptChannel() {
    webViewController.addJavaScriptChannel(
      'Invoke',
      onMessageReceived: (JavaScriptMessage message) {
        var webHeight = double.tryParse(message.message);
        if (webHeight != null) {
          webViewHeight.value = webHeight;
        }
      },
    );
  }

  // 获取页面高度
  _getWebViewHeight() async {
    // 一直变动高度的 设置最大高度变更次数
    await webViewController.runJavaScript("""
      // 设置最大高度变更次数
      let retryNum = 3;
      const resizeObserver = new ResizeObserver(entries => {
        if (retryNum > 0) {
          Invoke.postMessage(document.documentElement.scrollHeight.toString());
          retryNum -= 1;
        }
      });
      resizeObserver.observe(document.body);
    """);
  }

  void initWebController() {
    // 控制器设置
    webViewController.setJavaScriptMode(JavaScriptMode.unrestricted);
    webViewController.setBackgroundColor(Colors.transparent);
    webViewController.setNavigationDelegate(NavigationDelegate(
      onProgress: (int progress) {},
      onPageStarted: (String url) {},
      onPageFinished: (String url) {
        _getWebViewHeight();
        isPageFinished.value = true;
      },
      onWebResourceError: (WebResourceError error) {},
      onNavigationRequest: (NavigationRequest request) {
        // 限制内部导航的url
        if (request.url != '$ServerApiUrl/news/content/${state.item.id}') {
          return NavigationDecision.prevent;
        }
        return NavigationDecision.navigate;
      },
    ));
    // 注册js回调
    _invokeJavascriptChannel();
  }

  /// 声明周期
  @override
  void onInit() {
    super.onInit();
    NewsItem newsItem = Get.arguments;
    state.item = newsItem;
    // 初始化WebViewController信息
    initWebController();
    // TODO 如果遇到页面是固定100vh的，那么获取到的高度就是初始的SizeBox的高度
    // const url = "https://www.baidu.com/#iact=wiseindex%2Ftabs%2Fnews%2Factivity%2Fnewsdetail%3D%257B%2522linkData%2522%253A%257B%2522name%2522%253A%2522iframe%252Fmib-iframe%2522%252C%2522id%2522%253A%2522feed%2522%252C%2522index%2522%253A0%252C%2522url%2522%253A%2522https%253A%252F%252Fmbd.baidu.com%252Fnewspage%252Fdata%252Flandingpage%253Fs_type%253Dnews%2526dsp%253Dwise%2526context%253D%25257B%252522nid%252522%25253A%252522news_9417572788407561368%252522%25257D%2526pageType%253D1%2526n_type%253D1%2526p_from%253D-1%2526rec_src%253D52%2526innerIframe%253D1%2526browserId%253D25%2522%252C%2522isThird%2522%253Afalse%252C%2522title%2522%253Anull%257D%257D";
    // const url = "https://blog.csdn.net/m0_55635384/article/details/129020261";
    webViewController.loadRequest(Uri.parse(newsItem.url!));
  }
}
