import 'dart:convert';

import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:get/get.dart';

import '../controller.dart';

class NodePlayerDeviceLivePanel extends FStatelessWidget {
  NodePlayerDeviceLivePanel() {
    controller = Get.find<DeviceLiveDetailMobileController>();
  }
  late final DeviceLiveDetailMobileController controller;

  @override
  FWidget build(BuildContext context) {
    return QuickFWidget(
      InAppWebView(
        initialFile: "assets/webview/device_live_m.html",
        initialOptions: InAppWebViewGroupOptions(
          crossPlatform: InAppWebViewOptions(
            transparentBackground: true,
            mediaPlaybackRequiresUserGesture: false,
            disableHorizontalScroll: true,
            disableVerticalScroll: true,
            allowFileAccessFromFileURLs: true,
            allowUniversalAccessFromFileURLs: true,
          ),
          ios: IOSInAppWebViewOptions(
            allowsInlineMediaPlayback: true,
          ),
          android: AndroidInAppWebViewOptions(
            allowFileAccess: true,
            allowContentAccess: true,
          ),
        ),
        onWebViewCreated: (c) {
          c.addJavaScriptHandler(
            handlerName: "Dart_GetLiveData",
            callback: (args) async {
              return jsonEncode(controller.state.liveInfo!.dto!.toJson());
            },
          );
          c.addJavaScriptHandler(
            handlerName: "Dart_CheckLiveState",
            callback: (args) async {
              // controller.checkLiveDeviceState();
              final result = await controller.checkLiveDeviceState();
              if (result == 2) {
                // 更新直播信息, 刷新页面
                Future.delayed(const Duration(milliseconds: 100), () {
                  c.reload();
                });
              }
              return result == 1;
            },
          );
        },
        onLoadStop: (c, url) async {
          // c.evaluateJavascript(source: "load('$json')");
        },
        onConsoleMessage: (c, consoleMessage) {
          // logger.d(
          //     "[WebView Console][${consoleMessage.messageLevel}] ${consoleMessage.message}");
        },
      ),
    );
  }
}
