import 'dart:convert';

import 'package:fis_ui/index.dart';
import 'package:fis_ui/widgets/webview/webview.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/app_parameters.dart';
import 'package:flyinsono/architecture/utils/webviewx.dart';
import 'package:flyinsono/managers/interfaces/webview_controller.dart';
import 'package:flyinsono/views/common/device_live/device_live_detail/state.dart';
import 'package:flyinsono/views/desktop/device_live/device_live_detail/widgets/device_live_webview_from_fis_plus.dart';
import 'package:get/get.dart';
import 'package:webviewx/webviewx.dart';

import '../controller.dart';

class DeviceLivePanel extends FStatelessWidget {
  final int index;

  late final DeviceLiveDetailDesktopController controller;
  final webviewControllerManager = Get.find<IWebviewControllerManager>();

  DeviceLivePanel(this.index) {
    controller = Get.find<DeviceLiveDetailDesktopController>();
  }

  @override
  FWidget build(BuildContext context) {
    final sourceUrl = AppParameters.data.externalLivePlayerUrl;
    if (sourceUrl.isNotEmpty && sourceUrl.contains("fis.plus")) {
      final DeviceStateModel model = controller.state.deviceList[index];
      return DeviceLiveWebViewFromFisPlus(
        deviceCode: model.dto.deviceCode ?? "",
        sourceUrl: sourceUrl,
      );
    }
    late WebViewXController webViewController;
    return FFutureBuilder<String>(
      future: DefaultAssetBundle.of(context)
          .loadString("assets/webview/device_live.html"),
      builder: (context, snapshot) {
        if (snapshot.connectionState != ConnectionState.done ||
            snapshot.data == null) {
          return const FCenter(
            child: FSizedBox(
              width: 20,
              height: 20,
              child: FCircularProgressIndicator(),
            ),
          );
        }
        return FLayoutBuilder(
          builder: (context, constraints) {
            final webview = FWebViewX(
              height: constraints.maxHeight,
              width: constraints.maxWidth,
              initialContent: snapshot.data!,
              initialSourceType: SourceType.html,
              javascriptMode: JavascriptMode.unrestricted,
              ignoreAllGestures: false,
              onWebViewCreated: (controller) {
                webViewController = controller;
                webviewControllerManager.initWebviewController(controller);
              },
              onPageFinished: (p0) {
                webviewControllerManager.disposeWebviewController();
                // webViewController.callJsMethod('load', [json]);
              },
              dartCallBacks: {
                DartCallback(
                  name: "Dart_GetLiveData",
                  callBack: (_) {
                    final model = controller.state.deviceList[index];
                    final dto = model.liveInfo!.dto!;
                    final json = jsonEncode(dto.toJson());
                    return json;
                  },
                ),
                WebviewXDartAsyncCallback(
                  controllerGetter: () => webViewController,
                  methods: {
                    "checkLiveState": (data) async {
                      final result =
                          await controller.checkLiveDeviceState(data);
                      if (result == 2) {
                        // 更新直播信息，重载页面
                        Future.delayed(const Duration(milliseconds: 100), () {
                          webViewController.reload();
                        });
                      }
                      return result == 1;
                    },
                  },
                ),
              },
            );
            return webview;
          },
        );
      },
    );
  }
}
