import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/services/notification.m.dart';
import 'package:fis_measure/utils/prompt_box.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/notifications/handlers/college/change_share_live_course_handler.dart';
import 'package:flyinsono/notifications/handlers/college/index.dart';
import 'package:flyinsono/notifications/handlers/college/leave_course_handler.dart';
import 'package:flyinsono/notifications/handlers/college/live_interactive_board_data_notification.dart';
import 'package:flyinsono/notifications/handlers/other_platform_notification_handler.dart';
import 'package:flyinsono/pages/college/controller.dart';
import 'package:flyinsono/pages/college/widgets/upload_media_library/upload_media_library_web.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'package:flyinsono/views/mobile/full_screen_player/index.dart';
import 'interfaces/entities/operations.dart';
import 'interfaces/webview_controller.dart';
import 'live_course_manager.dart';

class LiveCourseListeningManager {
  late final LiveCourseManager manager;

  LiveCourseListeningManager(LiveCourseManager m) {
    manager = m;
    _initListener();
  }

  void _initListener() {
    var joinLiveCourseHandler = Get.find<JoinLiveCourseHandler>();
    joinLiveCourseHandler.subscribe(_onJoinLiveCourseHandler);
    var networkErrCourseHandler = Get.find<NetworkErrCourseHandler>();
    networkErrCourseHandler.subscribe(_onNetworkErrCourseHandler);
    var muteLiveCourseHandler = Get.find<MuteLiveCourseHandler>();
    muteLiveCourseHandler.subscribe(_onMuteLiveCourseHandler);
    var heartRateLeaveCourse = Get.find<HeartRateLeaveCourseHandler>();
    heartRateLeaveCourse.subscribe(_onHeartRateLeaveCourse);
    var heartRateJoin = Get.find<HeartRateJoinCourseHandler>();
    heartRateJoin.subscribe(_onHeartRateJoin);
    var closeLiveCourseNotification = Get.find<CloseLiveCourseHandler>();
    closeLiveCourseNotification.subscribe(_onCloseLiveCourseHandler);
    var switchLiveCourseVideoHandler = Get.find<SwitchLiveCourseVideoHandler>();
    switchLiveCourseVideoHandler.subscribe(_onSwitchLiveCourseVideoHandler);
    var leaveLiveCourseHandler = Get.find<LeaveLiveCourseHandler>();
    leaveLiveCourseHandler.subscribe(_onLeaveLiveCourseHandler);
    var sendLiveInteractiveBoardDataNotification =
        Get.find<SendLiveInteractiveBoardDataHandler>();
    sendLiveInteractiveBoardDataNotification
        .subscribe(_onLiveInteractiveBoardDataHandler);
    var changeShareInLiveCourseHandler =
        Get.find<ChangeShareInLiveCourseHandler>();
    changeShareInLiveCourseHandler.subscribe(_onChangeShareInLiveCourseHandler);
    var otherPlatformNotificationHandler =
        Get.find<OtherPlatformNotificationHandler>();
    otherPlatformNotificationHandler
        .subscribe(onOtherPlatformNotificationHandler);
    var courseStatusHandler = Get.find<CourseStatusHandler>();
    courseStatusHandler.subscribe(_onCourseStatusHandler);
  }

  void _onJoinLiveCourseHandler(JoinLiveCourseNotification e) {
    manager.onJoinLiveCourse.emit(this, e);
  }

  void _onNetworkErrCourseHandler(NetworkErrCourseNotification e) {
    manager.onNetworkErr.emit(this, e);
  }

  void _onMuteLiveCourseHandler(MuteLiveCourseNotification e) {
    manager.onMute.emit(this, e);
  }

  void _onHeartRateLeaveCourse(HeartRateLeaveCourseNotification e) {
    manager.onHeartRateLeave.emit(this, e);
  }

  void _onHeartRateJoin(HeartRateJoinCourseNotification e) {
    manager.onHeartRateJoin.emit(this, e);
  }

  void _onCloseLiveCourseHandler(CloseLiveCourseNotification e) {
    manager.onCloseLiveCourse.emit(this, e);
  }

  void _onSwitchLiveCourseVideoHandler(SwitchLiveCourseVideoNotification e) {
    manager.onSwitchVideoOpend.emit(this, e);
  }

  void _onLeaveLiveCourseHandler(LeaveLiveCourseNotification e) {
    manager.onLeave.emit(this, e);
  }

  void _onLiveInteractiveBoardDataHandler(
      SendLiveInteractiveBoardDataNotification e) {
    manager.onBoardDataReceive.emit(this, e);
  }

  void _onChangeShareInLiveCourseHandler(
      ChangeShareInLiveCourseNotification e) {
    manager.onChangeShareInLiveCourse.emit(this, e);
  }

  Future<void> onOtherPlatformNotificationHandler(
      CourseEntryNotification e) async {
    ///noticeData 示例：target=liveCourse?AE55FH3JFI2SDHUS3561Q&token=CSDFAE55FH3JFI2SDHUS3561Q
    if (e.noticeData == null) {
      return;
    }
    var noticeDatas = e.noticeData!.split('?');
    if (noticeDatas.isEmpty) {
      return;
    }
    var target = noticeDatas.first;
    var targetOperate = target.split('=').last;
    logger.i('targetOperate:$targetOperate,noticeDatas:$noticeDatas');
    if (targetOperate == Operations.joinCourse && noticeDatas.length > 1) {
      var courseCode = _getCourseCode(noticeDatas);
      var token = _getToken(noticeDatas);
      if (token != null && token != Store.user.token) {
        return;
      }
      var courseInfo = await manager.getCourseInfo(courseCode);
      var isStudent = (courseInfo.experts
              ?.any((element) => element.code == Store.user.code) ??
          false);
      if (courseInfo.teacherCode == Store.user.code || isStudent) {
        if (courseInfo.status != CourseStatusEnum.Started && isStudent) {
          PromptBox.toast(i18nBook.college.courseNotStreaming.t);
          return;
        }

        ///进入小班化页面
        manager.openLiveCoursePage(courseCode);
      }
    } else if (targetOperate == Operations.download && noticeDatas.length > 1) {
      _downloadFile(noticeDatas);
    } else if (targetOperate == Operations.record && noticeDatas.length > 1) {
      var courseCode = _getCourseCode(noticeDatas);
      manager.startRecording(courseCode);
    } else if (targetOperate == Operations.endRecord) {
      manager.stopRecording();
    } else if (targetOperate == Operations.openStorageDir) {
      try {
        final controller = Get.find<FlyinsonoCollegeController>();
        controller.openRecordPath();
      } catch (e) {
        logger.e('openStorageDir error:$e');
      }
    } else if (targetOperate == Operations.openIOSFullScreenPlayer &&
        noticeDatas.length > 1) {
      try {
        var parameter = noticeDatas[1];
        var url = parameter.split('=').last;
        print('openIOSFullScreenPlayer parameter:$url');
        Get.to(() => FullScreenPlayerPage(flvUrl: url));
      } catch (e) {
        logger.e('openIOSFullScreenPlayer error:$e');
      }
    } else if (targetOperate == Operations.copyToClipboard &&
        noticeDatas.length > 1) {
      try {
        var parameter = noticeDatas[1];
        var url = parameter.split('=').last;
        print('copyToClipboard parameter:$url');
        rpc.platform.copyToClipboard(url);
      } catch (e) {
        logger.e('copyToClipboard error:$e');
      }
    }
  }

  String _getCourseCode(List<String> noticeDatas) {
    var parameter = noticeDatas[1];
    if (parameter.contains('&')) {
      var parameters = parameter.split('&');
      var courseCode = parameters.first.split('=').last;
      return courseCode;
    } else {
      var parameters = parameter.split('=');
      var courseCode = parameters.last;
      return courseCode;
    }
  }

  String? _getToken(List<String> noticeDatas) {
    var parameter = noticeDatas[1];
    if (parameter.contains('&')) {
      var parameters = parameter.split('&');
      var token = parameters.last.split('=').last;
      return token;
    }
    return null;
  }

  Future<void> _downloadFile(List<String> noticeDatas) async {
    var parameter = noticeDatas[1];
    logger.i('download info:$parameter');
    var tokenInfos = parameter.split('&');
    var token = tokenInfos.first.split('=').last;
    var fileName = tokenInfos.last.split('=').last;
    rpc.platform.downloadBigFile(token, fileName);
    final webviewControllerManager = Get.find<IWebviewControllerManager>();
    if (webviewControllerManager.webViewXController != null) {
      webviewControllerManager.webViewXController!.setIgnoreAllGestures(true);
    }
    bool isDownload = false;
    manager.onProcessChange.addListener((sender, e) {
      if (e == 1 && !isDownload) {
        isDownload = true;
        if (CartSystemPlatform.isCartSystemVersion) {
          PromptBox.toast(i18nBook.common.downloadSuccess.t);
        } else {
          PromptBox.toast(i18nBook.college.downloadSuccess.t);
        }
      }
      print('downloadFile process value:$e');
    });
    await router.dialog(
      () => ShowProgressCircle(
        manager.onProcessChange,
        hintText: i18nBook.college.downloadProgress.t,
        onCancel: () {
          if (webviewControllerManager.webViewXController != null) {
            webviewControllerManager.webViewXController!
                .setIgnoreAllGestures(false);
          }
          rpc.platform.cancelDownloadBigFile();
          router.back();
        },
      ),
      dismissible: false,
    );
    if (webviewControllerManager.webViewXController != null) {
      webviewControllerManager.webViewXController!.setIgnoreAllGestures(false);
    }
  }

  void _onCourseStatusHandler(CourseStatusNotification e) {
    if (e.status == CourseStatusEnum.HasEnded) {
      manager.timer?.cancel();
      manager.timer = null;
      manager.onCourseStatusChange.emit(this, e);
    }
  }
}
