import 'package:fis_i18n/i18n.dart';
import 'package:fis_live/fis_live.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/managers/interfaces/device.dart';
import 'package:flyinsono/managers/interfaces/entities/device_entities.dart';
import 'package:daniulive/controllers/merge_play_controller.dart';
import 'package:daniulive/controllers/play_controller.dart';
import 'package:get/get.dart';

import 'state.dart';

class DeviceLiveDetailMobileController extends FControllerBase {
  final state = DeviceLiveDetailMobileState();

  final deviceManager = Get.find<IDeviceManager>();

  LiveController? mainChannelController;
  LiveController? camera01Controller;

  MergePlayController? mergePlayController;

  PlayController? mainViewPlayController;
  PlayController? subViewPlayController;

  @override
  void onReady() {
    state.deviceCode = Get.parameters['code']!;
    _startPull();
    super.onReady();
  }

  @override
  onClose() {
    _disposeDaniuLive();
    _stopPull();
    state.isLiveInfoInited = false;
    super.onClose();
  }

  /// 返回
  void handlePageBack() {
    Get.back();
  }

  /// 检查设置直播设备状态
  ///
  /// remarks: 1表示正常，0表示失败；2表示需要重载webview
  Future<int> checkLiveDeviceState() async {
    try {
      final code = state.deviceCode;

      // 直播信息变更or不在直播中
      // 重新进入直播
      final liveInfo = await deviceManager.enterLiveRoom(code);
      if (liveInfo != null) {
        // 进入直播成功
        // 更新设备直播信息
        state.liveInfo = liveInfo;
        state.isOldPlatform = liveInfo.isOldPlatform;
        return 2; // 通知webview reload
      }
    } catch (e) {
      //
    }
    return 0;
  }

  /// 重新加载大牛直播，在 checkLiveDeviceState 之后执行
  void reLoadDaniuLive() async {
    state.isLiveInfoInited = false;
    final DeviceLiveDisplayInfoModel? liveInfo = state.liveInfo;
    if (liveInfo == null) return;
    _disposeDaniuLive();
    // 延迟 300ms，等待播放器释放
    await Future.delayed(const Duration(milliseconds: 300));
    state.isOldPlatform = liveInfo.isOldPlatform;
    _initDaniuLive(liveInfo);
    state.isLiveInfoInited = true;
  }

  /// 开始拉流
  Future<void> _startPull() async {
    try {
      final DeviceLiveDisplayInfoModel? liveInfo =
          await deviceManager.enterLiveRoom(state.deviceCode);
      if (liveInfo == null) return;
      state.liveInfo = liveInfo;
      state.isOldPlatform = liveInfo.isOldPlatform;
      state.isSupportNodePlayer =
          _isContainFisPlus(liveInfo.sources[0].httpFlvUrl);
      if (state.isSupportNodePlayer) {
        _initNodePlayer(liveInfo.sources);
      } else {
        _initDaniuLive(liveInfo);
      }
      state.isLiveInfoInited = true;
    } catch (e) {
      PromptBox.error(i18nBook.common.networkInstability.t);
    }
  }

  /// 停止拉流
  Future<void> _stopPull() async {
    await deviceManager.exitLiveRoom(state.deviceCode);
  }

  /// nodePlayer 直播控制器数据初始化
  void _initNodePlayer(List<DeviceLiveSourceInfoModel> liveSources) {
    mainChannelController = LiveController(
      source: LiveSource(
        liveSources[0].httpFlvUrl,
      ),
    );
    if (liveSources.length > 1) {
      final source = liveSources[1];
      camera01Controller = LiveController(
        source: LiveSource(
          source.httpFlvUrl,
          width: source.width,
          height: source.height,
        ),
      );
    }
  }

  /// daniuLive 直播控制器数据初始化
  void _initDaniuLive(DeviceLiveDisplayInfoModel liveInfo) {
    state.isRtmpUseMerge = liveInfo.useMerge;

    /// 合图模式
    if (state.isRtmpUseMerge) {
      final mainViewSource = liveInfo.sources[0];
      state.rtmpMainViewWidth = mainViewSource.width;
      state.rtmpMainViewHeight = mainViewSource.height;
      mergePlayController = MergePlayController(
        mainViewSource.rtmpUrl,
        userId: "DeviceMainChannel",
        mergeWidth: liveInfo.mergeWidth, // 先不传，后续会由 fixMergedSize 修复
        mergeHeight: liveInfo.mergeHeight, // 先不传，后续会由 fixMergedSize 修复
        subViewCount: 0,
      );
      if (liveInfo.sources.length > 1) {
        final subViewSource = liveInfo.sources[1];
        state.rtmpSubViewWidth = subViewSource.width;
        state.rtmpSubViewHeight = subViewSource.height;
        state.isRtmpSubViewExist = true;
      } else {
        state.isRtmpSubViewExist = false;
      }
      mergePlayController!.init();
    } else {
      /// 非合图模式
      final mainViewSource = liveInfo.sources[0];
      mainViewPlayController = PlayController(
        liveInfo.sources[0].rtmpUrl,
        userId: "DeviceMainChannel",
      );
      state.rtmpMainViewWidth = mainViewSource.width;
      state.rtmpMainViewHeight = mainViewSource.height;
      mainViewPlayController!.init();
      if (liveInfo.sources.length > 1) {
        final subViewSource = liveInfo.sources[1];
        state.rtmpSubViewWidth = subViewSource.width;
        state.rtmpSubViewHeight = subViewSource.height;
        subViewPlayController = PlayController(
          subViewSource.rtmpUrl,
          userId: "DeviceSubChannel",
        );
        state.isRtmpSubViewExist = true;
        subViewPlayController!.init();
      } else {
        state.isRtmpSubViewExist = false;
      }
    }
  }

  /// 释放 daniuLive ，重要！！！
  void _disposeDaniuLive() {
    if (mergePlayController != null) {
      mergePlayController!.stop();
      mergePlayController!.dispose();
      mergePlayController = null;
    }
    if (mainViewPlayController != null) {
      mainViewPlayController!.stop();
      mainViewPlayController!.dispose();
      mainViewPlayController = null;
    }
    if (subViewPlayController != null) {
      subViewPlayController!.stop();
      subViewPlayController!.dispose();
      subViewPlayController = null;
    }
  }

  // 根据拉流地址来判断是否使用 NodePlayer，如果拉流地址一级域名是 fis.plus 则使用 NodePlayer
  bool _isContainFisPlus(String url) {
    final uri = Uri.parse(url);
    return uri.host.contains('fis.plus');
  }

  /// 初始化 daniuLive 播放器
  void initDaniuPlayerAfterViewCreated() {
    if (mergePlayController != null) {
      // 延迟 300ms，等待播放器初始化完成
      Future.delayed(const Duration(milliseconds: 300), () {
        mergePlayController!.play();
      });
    }
  }

  void foldSubView() {
    state.isDaniuSubViewExpanded = !state.isDaniuSubViewExpanded;
  }

  void switchSubViewPosition() {
    state.isDaniuSubViewAlignRight = !state.isDaniuSubViewAlignRight;
  }
}
