import 'dart:async';

import 'package:fis_common/index.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:fis_jsonrpc/services/notification.m.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/services.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/global.dart';
import 'package:flyinsono/managers/interfaces/entities/live_consultation.dart';
import 'package:flyinsono/managers/interfaces/live_consultation.dart';
import 'package:flyinsono/pages/consultation_dialogs/request_dialog.dart';
import 'package:flyinsono/pages/main/home/widgets/dialog_page.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/live_consultation/controller.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';

import 'popup_timer.dart';

class ConsulationPopup {
  static bool get isPc => !kIsMobile;
  static bool _stopTimer = false;
  static bool _isPlaying = false;
  static PopupTimer? _timer;
  static const String audioPath = 'assets/audio/LiveTalkingMessage.opus';
  static const String iosAudioPath = 'assets/audio/LiveTalkingMessage.wav';
  static FlutterSoundPlayer _flutterSound =
      FlutterSoundPlayer(logLevel: Level.nothing);
  static void startListening() {
    var liveConsultationManager = Get.find<ILiveConsultationManager>();

    ///开始会诊通知事件 11
    liveConsultationManager.onInviteLiveConsultation
        .addListener(onInviteLiveConsultation);

    //会诊过程中邀请成员的通知(通知被邀请者) 8
    liveConsultationManager.onInviteeInLiveConsultation
        .addListener(onJoinLiveConsultation);

    //取消会诊过程中邀请成员的通知(通知被邀请者) 7
    liveConsultationManager.onCancelInvitingConsultation
        .addListener(onCancelInvitingConsultation);

    //邀请者取消接听会诊事件
    liveConsultationManager.onCancelConsultation
        .addListener(onCancelConsultation);

    //取消呼叫 to 客户端 68
    liveConsultationManager.onCancelInvitingInLiveCourseNotification
        .addListener(onJoinLiveConsultationInOtherDevice);

    ///关闭会诊事件（通知所有成员） 16
    liveConsultationManager.onCloseConsultation
        .addListener(onCloseLiveConsultation);
  }

  ///接受会诊弹窗
  static Future<void> onInviteLiveConsultation(
      Object sender, LiveConsultation e) async {
    if (_isPlaying) {
      _stopTimer = true;
      _isPlaying = false;
      _flutterSound.stopPlayer();
      _timer?.resetTimer();
      router.back();
    }
    _requestDialog(e);
  }

  /// 会诊过程中取消呼叫
  static void onCancelInvitingConsultation(Object sender, LiveConsultation e) {
    print('onCancelInvitingConsultation');
    if (e.userCode != Store.user.code) {
      return;
    }
    if (_isPlaying) {
      _isPlaying = false;
      _flutterSound.stopPlayer();
      _timer?.resetTimer();
      router.back();
    }
  }

  /// 会诊开始前取消呼叫
  static void onCancelConsultation(Object sender, LiveConsultation e) {
    if (_isPlaying) {
      _isPlaying = false;
      _flutterSound.stopPlayer();
      _timer?.resetTimer();
      router.back();
    }
  }

  // 在另一台设备上进入会诊
  static void onJoinLiveConsultationInOtherDevice(
      Object sender, CancelInvitingInLiveCourseNotification e) {
    if (_isPlaying) {
      _isPlaying = false;
      _flutterSound.stopPlayer();
      _timer?.resetTimer();
      router.back();
    }
  }

  ///关闭会诊
  static void onCloseLiveConsultation(Object sender, LiveConsultation e) {
    try {
      final controller = Get.find<LiveConsultationController>();
      if (controller.state.selectedConsultationCode == e.consultationCode) {
        controller.sendInteractiveBoardData('', true);
        controller.onClearCanavsHandler.emit('', Store.user.code);
        controller.leaveConsultation();
      }
    } catch (e) {
      logger.e('onCloseLiveConsultation ex:', e);
    }
  }

  ///加入会诊弹窗
  static void onJoinLiveConsultation(Object sender, LiveConsultation e) {
    if (_isPlaying) {
      _stopTimer = true;
      _isPlaying = false;
      _flutterSound.stopPlayer();
      _timer?.resetTimer();
      router.back();
    }
    _requestDialog(e, isJoin: true);
  }

  //播放铃声
  static void _startPlayer(FlutterSoundPlayer flutterSound, Uint8List buffer) {
    _stopTimer = false;
    flutterSound.openPlayer();
    flutterSound.startPlayer(
      fromDataBuffer: buffer,
      codec: FPlatform.isIOS ? Codec.pcm16WAV : Codec.opusWebM,
      whenFinished: () {
        if (_stopTimer) {
          return;
        }
        Future.delayed(Duration(milliseconds: 200), () {
          if (_stopTimer) {
            _isPlaying = false;
            return;
          }
          _startPlayer(flutterSound, buffer);
        });
      },
    );
  }

  static Future<void> _requestDialog(LiveConsultation e,
      {bool isJoin = false}) async {
    if (_timer == null) {
      _timer = PopupTimer();
    }
    _timer!.startTimer(onTimerComplete: () {
      _timer?.resetTimer();
      router.back();
    });
    try {
      Global.assetBundle
          .load(FPlatform.isIOS ? iosAudioPath : audioPath)
          .then((buf) {
        var buffer = buf.buffer.asUint8List();
        _startPlayer(_flutterSound, buffer);
        _isPlaying = true;
      });

      if (isPc) {
        Get.find<FWebviewInteractiveController>().onDialogCreate();
      }
      await router.dialog(
        () => ConsulationRequestDialog(
          e,
          () {
            _stopTimer = true;
            _isPlaying = false;
            _timer?.resetTimer();
            _flutterSound.stopPlayer();
          },
          isJoin,
        ),
        dismissible: false,
      );
      if (isPc) {
        Get.find<FWebviewInteractiveController>().onDialogDispose();
      }
    } catch (e) {
      _isPlaying = false;
      logger.e('', e);
    }
    _stopTimer = true;
    _isPlaying = false;
    _timer?.resetTimer();
    _flutterSound.stopPlayer();
  }
}
