import 'package:fis_common/index.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/widgets/functional/popup_menu_button.dart';
import 'package:fis_ui/widgets/webview/webview.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/managers/server_config_manager.dart';
import 'package:flyinsono/pages/college/controller.dart';
import 'package:flyinsono/pages/college/view.dart';
import 'package:flyinsono/views/mobile/past_videos/view.dart';
import 'package:get/get.dart';
import 'package:webviewx/webviewx.dart';
import '../../../views/mobile/past_videos/controller.dart';
import 'my_course/mock_page.dart';

class MobileFlyinsonoCollege extends FStatefulWidget implements FPage {
  @override
  String get pageName => "MobileFlyinsonoCollege";

  @override
  FState<FStatefulWidget> createState() {
    return MobileFlyinsonoCollegeState();
  }
}

class MobileFlyinsonoCollegeState extends FState<MobileFlyinsonoCollege> {
  final controller = Get.find<FlyinsonoCollegeController>();
  CollegeRouteEnum currRoute = CollegeRouteEnum.pastVideos;
  String initialContent = ServerConfigManager.flyinsonoSchoolUrl +
      'all_courses/${Store.user.token}/${FPlatform.current.index}/${i18nBook.locale.languageCode.toLowerCase()}';
  @override
  FWidget build(BuildContext context) {
    return FScaffold(
      appBar: FAppBar(
        title: _buildAppBarNavTabs(),
        titleTextStyle: TextStyle(fontSize: 14),
        centerTitle: true,
        elevation: 0,
        // actionsIconTheme: IconThemeData(color: Colors.white),
        leading: FIconButton(
          icon: FIcon(
            Icons.keyboard_arrow_left,
            color: Colors.white,
          ),
          onPressed: () {
            router.back();
          },
          businessParent: widget,
          name: 'flyinsonoCollegeBack',
        ),
      ),
      body: _buildBodyByState(currRoute),
    );
  }

  FWidget _buildBodyByState(CollegeRouteEnum currRoute) {
    switch (currRoute) {
      case CollegeRouteEnum.courseHome:
        String url = ServerConfigManager.flyinsonoSchoolUrl +
            'all_courses/${Store.user.token}/${FPlatform.current.index}/${i18nBook.locale.languageCode.toLowerCase()}';
        return _buildWebviewByURL(url);
      case CollegeRouteEnum.myCourses:
        // String url = "http://localhost:5173/#/" +
        //       'my_course/${Store.user.token}/${FPlatform.current.index}/${i18nBook.locale.languageCode.toLowerCase()}';
        String url = ServerConfigManager.flyinsonoSchoolUrl +
            'my_course/${Store.user.token}/${FPlatform.current.index}/${i18nBook.locale.languageCode.toLowerCase()}';
        return _buildWebviewByURL(url);
      case CollegeRouteEnum.pastVideos:
        return _buildPastVideoView();
      case CollegeRouteEnum.mock:
        return MockPage();
    }
  }

  FWidget _buildWebviewByURL(String url) {
    return QuickFWidget(_buildMobileWebviewPlayer(url));

    /// Webviewx 无法开启全屏

    // return FLayoutBuilder(
    //   key: UniqueKey(),
    //   builder: (context, constraints) {
    //     final webview = FWebViewX(
    //       height: constraints.maxHeight,
    //       width: constraints.maxWidth,
    //       initialContent: url,
    //       initialSourceType: SourceType.url,
    //       javascriptMode: JavascriptMode.unrestricted,
    //       ignoreAllGestures: false,
    //       onWebViewCreated: (controller) {
    //         // webViewController = controller;
    //       },
    //     );
    //     return FContainer(
    //       height: MediaQuery.of(context).size.height,
    //       width: MediaQuery.of(context).size.width,
    //       child: webview,
    //     );
    //   },
    // );
  }

  Widget _buildMobileWebviewPlayer(url) {
    return InAppWebView(
      key: UniqueKey(),
      initialUrlRequest: URLRequest(url: Uri.parse(url)),
      initialOptions: InAppWebViewGroupOptions(
        crossPlatform: InAppWebViewOptions(
          transparentBackground: true,
          mediaPlaybackRequiresUserGesture: false,
          allowFileAccessFromFileURLs: true,
          allowUniversalAccessFromFileURLs: true,
        ),
        ios: IOSInAppWebViewOptions(
          allowsInlineMediaPlayback: true,
        ),
        android: AndroidInAppWebViewOptions(
          allowFileAccess: true,
          allowContentAccess: true,
        ),
      ),
      onWebViewCreated: (c) {},
      onLoadStop: (c, url) async {
        // controller.onWebviewLoadFinished();
      },
      onLoadError: (controller, url, code, message) {
        print("webview onLoadError");
      },
      onLoadHttpError: (controller, url, statusCode, description) {
        print("webview onLoadHttpError");
      },
      onConsoleMessage: (c, consoleMessage) {
        // logger.d(
        //     "[WebView Console][${consoleMessage.messageLevel}] ${consoleMessage.message}");
      },
      onEnterFullscreen: (c) {
        /// 允许屏幕旋转
        if (FPlatform.isAndroid) {
          // 安卓设备只允许右横屏
          SystemChrome.setPreferredOrientations([
            DeviceOrientation.landscapeRight,
          ]);
          return;
        } else {
          SystemChrome.setPreferredOrientations([
            DeviceOrientation.landscapeLeft,
            DeviceOrientation.landscapeRight,
          ]);
        }
      },
      onExitFullscreen: (c) {
        /// 禁止屏幕旋转
        SystemChrome.setPreferredOrientations([
          DeviceOrientation.portraitUp,
        ]);
      },
    );
  }

  FWidget _buildPastVideoView() {
    return FisBuilder<PastVideosController>(
        init: PastVideosController(),
        builder: (context) {
          return PastVideosPage(singleMobilePage: true);
        });
  }

  FWidget _buildAppBarNavTabs() {
    final enumList = [
      CollegeRouteEnum.pastVideos,
      CollegeRouteEnum.courseHome,
      CollegeRouteEnum.myCourses,
    ];
    if (kDebugMode) {
      enumList.add(CollegeRouteEnum.mock);
    }
    return FRow(
      children: enumList
          .map((e) => _AppBarNavTabWidget(e, this.currRoute, _switchCurrRoute))
          .toList(),
    );
  }

  void _switchCurrRoute(CollegeRouteEnum value) {
    if (value != currRoute) {
      setState(() {
        currRoute = value;
      });
    }
  }
}

class _AppBarNavTabWidget extends FStatelessWidget {
  final CollegeRouteEnum route;
  final CollegeRouteEnum selectedRoute;
  final ValueChanged<CollegeRouteEnum> onTap;

  _AppBarNavTabWidget(this.route, this.selectedRoute, this.onTap);

  @override
  FWidget build(BuildContext context) {
    bool isSelected = this.selectedRoute == route;
    return FGestureDetector(
      businessParent: FVirtualPageWidget("MobileFlyinsonoCollege"),
      name: "College_Tab-${route.name}",
      onTap: () {
        onTap.call(this.route);
      },
      child: FContainer(
        margin: EdgeInsets.only(right: 2),
        padding: EdgeInsets.symmetric(vertical: 10, horizontal: 6),
        child: FText(
          _getName(),
          style: TextStyle(fontSize: 14, color: Colors.white),
        ),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(4.0),
          color: isSelected ? Colors.white.withOpacity(.4) : null,
        ),
      ),
    );
  }

  String _getName() {
    switch (route) {
      case CollegeRouteEnum.courseHome:
        return i18nBook.common.courseHome.t;
      case CollegeRouteEnum.myCourses:
        return i18nBook.college.myCourses.t;
      case CollegeRouteEnum.pastVideos:
        return i18nBook.college.pastVideo.t;
      case CollegeRouteEnum.mock:
        return 'debug';
    }
  }
}
