import 'package:fis_measure/view/player/controller.dart';
import 'package:fis_measure/view/player/enums.dart';
import 'package:fis_measure/view/player/events.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/lab/pages/lab_image/urm_data_processor/urm_data_processor.dart';
import 'package:get/get.dart';
import 'package:fis_vid/data_channel/progress_info.dart';
import 'package:vid/us/vid_us_image.dart';
import 'package:vid/us/vid_us_visual_area_type.dart';
import 'package:vid/us/vid_us_physical_coordinate.dart';
import 'package:vid/us/vid_us_2d_visual.dart';
import 'package:vid/us/vid_us_logical_coordinate.dart';

class ImageDataPlayerController extends GetxController {
  ImageDataPlayerController({
    this.onProgressChanged,
    this.onPlayStatusChanged,
    this.onFrameSizeChanged,
    this.onDataHostLoaded,
    this.onFirstFrameLoaded,
    this.onBufferProgressChanged,
  });

  static const imageDataPlayerId = "image_data_player";
  static const currentTimeId = "current_time";

  // 视频播放进度变化事件
  final ValueChanged<VidProgressInfo>? onProgressChanged;

  // 播放状态变更事件
  final ValueChanged<bool>? onPlayStatusChanged;

  // 视频帧尺寸变动
  final Function(int, int)? onFrameSizeChanged;

  // datahost 下载完毕通知
  final ValueChanged<VidPlayerController>? onDataHostLoaded;

  /// 首帧加载成功
  final ValueChanged<VidUsImage>? onFirstFrameLoaded;

  /// 缓冲进度变更事件
  final ValueChanged<double>? onBufferProgressChanged;

  // 当前的 URM 图像数据
  URMDataProcessor _urmDataProcessor = URMDataProcessor();

  // 组件是否已挂载
  bool mounted = false;

  // 视频播放器控制器
  VidPlayerController? playerController;

  // datahost 是否已下载完毕
  bool _dataHostLoaded = false;

  // 视频播放器可用状态
  bool get playerAvailable => playerController != null && _dataHostLoaded;

  /// 图像链接
  String? get dataUrl => playerController?.url;

  // 预览图像地址
  String previewImageUrl = "";

  /// 是否显示预览图象
  bool showPreviewImage = true;

  // 总帧数
  int _totalFrames = 0;

  // 总时长
  double _totalDuration = 0;

  double _bufferedPercent = 0;

  GlobalKey playerKey = GlobalKey();
  // 当前播放帧宽度
  int currentFrameWidth = 0;
  // 当前播放帧高度
  int currentFrameHeight = 0;

  /// 当前urm中间下面的时间
  String currentTimeString = "";
  // 当前播放帧比例
  double get currentFrameAspectRatio =>
      currentFrameHeight > 0 ? currentFrameWidth / currentFrameHeight : 1;

  /// 是不是urm 视频的vid
  bool get isURMVideoVid =>
      _urmDataProcessor.imageCode.isNotEmpty &&
      playerController != null &&
      !playerController!.isSingleFrame;

  /// 开始时间不等于结束时间 才显示
  bool get isShowTime =>
      _urmDataProcessor.startTime != _urmDataProcessor.endTime &&
      _urmDataProcessor.startTime != 0.0;

  void changeVid(String url, String previewImageUrl) {
    this.previewImageUrl = previewImageUrl;
    _closeVidPlayer();
    // 下一渲染帧执行
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _initVidPlayer(url);
    });
  }

  void changePlayStatus(bool isPlaying) {
    if (playerController != null) {
      if (isPlaying) {
        playerController!.play();
      } else {
        playerController!.pause();
      }
    }
  }

  /// 设置 URM 数据处理器
  void setURMDataProcessor(URMDataProcessor urmDataProcessor) async {
    _urmDataProcessor = urmDataProcessor;
  }

  bool onFrameChangeEvent(int frame) {
    if (playerController != null) {
      final bufferedFrameCount = (_bufferedPercent * _totalFrames).toInt();
      if (bufferedFrameCount > frame) {
        playerController!.pause();
        playerController!.gotoFrame(frame);
        return true;
      } else {
        return false;
      }
    }
    return false;
  }

  /// 初始化视频播放器
  void _initVidPlayer(String url) {
    _urmDataProcessor = URMDataProcessor();
    final newPlayerController = VidPlayerController(url);
    playerController = newPlayerController;
    if (playerController != null) {
      playerController!.firstFrameLoaded.addListener(_onFirstFrameLoaded);
      playerController!.eventHandler.addListener(_onControllerEvent);
      playerController!.dataChannel.downloadProgressChanged
          .addListener(_onBufferProgressChanged);
      _tryLoadPlayer(playerController!);
    }
  }

  void _onBufferProgressChanged(_, VidDownloadProgressInfo e) {
    _bufferedPercent = _calcRealFramesBufferPercent();
    onBufferProgressChanged?.call(e.progress);
  }

  double _calcRealFramesBufferPercent() {
    final channel = playerController!.dataChannel;
    final int fileSize = channel.getFileSize();
    final int bufferredSize = channel.getBufferSize();

    final int framesTotalSize = fileSize - playerController!.vidHeaderSize;
    final int framesBufferredSize =
        bufferredSize - playerController!.vidHeaderSize;
    double percent = framesBufferredSize / framesTotalSize;

    return percent;
  }

  // 关闭视频播放器（会重新渲染UI）
  void _closeVidPlayer() {
    if (playerController != null) {
      playerController!.eventHandler.removeListener(_onControllerEvent);
      playerController!.dispose();
      playerController = null;
      _dataHostLoaded = false;
      update([imageDataPlayerId]);
    }
  }

  /// 释放视频播放器（不重新渲染UI）
  void _disposeVidPlayer() {
    if (playerController != null) {
      playerController!.eventHandler.removeListener(_onControllerEvent);
      playerController!.dispose();
      playerController = null;
      _dataHostLoaded = false;
    }
  }

  String _formatSeconds(int seconds) {
    int minutes = seconds ~/ 60; // 使用整数除法计算分钟数
    int remainingSeconds = seconds % 60; // 计算剩余的秒数

    String minutesStr = minutes.toString().padLeft(2, '0'); // 补齐两位数
    String secondsStr = remainingSeconds.toString().padLeft(2, '0'); // 补齐两位数

    return '$minutesStr:$secondsStr';
  }

  void _onControllerEvent(Object sender, VidPlayerEvent e) {
    if (e is VidPlayerFrameIndexChangeEvent) {
      if (currentFrameWidth != e.width || currentFrameHeight != e.height) {
        currentFrameWidth = e.width;
        currentFrameHeight = e.height;
        onFrameSizeChanged?.call(e.width, e.height);
      }
      double currentTime =
          (_urmDataProcessor.endTime - _urmDataProcessor.startTime) /
                  _totalFrames *
                  e.index +
              _urmDataProcessor.startTime;
      currentTimeString = _formatSeconds(currentTime.toInt());
      update([currentTimeId]);
      onProgressChanged?.call(
        VidProgressInfo(
          currentFrame: e.index,
          totalFrames: _totalFrames,
          totalDuration: _totalDuration,
        ),
      );
    }
    if (e is VidPlayerStatusChangeEvent) {
      print("VidPlayerStatusChangeEvent: ${e.status}");
      if (e.status == VidPlayStatus.pause) {
        onPlayStatusChanged?.call(false);
      }
      if (e.status == VidPlayStatus.play) {
        onPlayStatusChanged?.call(true);
      }
    }

    if (e is VidPlayerPlayOverEvent) {
      if (playerController != null && playerController!.isEndOfPlay) {
        /// 等待1s后，自动重播
        Future.delayed(Duration(milliseconds: 100), () {
          if (playerController != null) {
            playerController!.gotoFrame(0);
            Future.delayed(Duration(milliseconds: 100), () {
              if (playerController != null) {
                playerController!.play();
              }
            });
          }
        });
      }
    }
  }

  void _tryLoadPlayer(VidPlayerController playerController) async {
    int tryCount = 0;
    const limitCount = 5;
    bool loaded = false;
    while (loaded == false) {
      if (limitCount <= tryCount) break;
      if (playerController.disposed) break;

      loaded = await playerController.load();
      tryCount++;
    }

    if (playerController.disposed) return;

    if (loaded) {
      _onImageLoaded();
    }
  }

  void _onImageLoaded() {
    // 初始化总帧数信息
    _totalFrames = playerController!.totalFramesCount;
    _totalDuration =
        playerController!.totalFramesCount / playerController!.frameRate;
    if (_totalFrames <= 1) {
      _totalDuration = 0;
    }

    // 通知图像加载完成
    onDataHostLoaded?.call(playerController!);
    _dataHostLoaded = true;

    playerController!.play();
  }

  void _onFirstFrameLoaded(_, VidUsImage e) {
    var visual = e.visuals.first;
    if (visual is VidUs2DVisual) {
      visual.physicalCoordinates;
      if (visual.physicalCoordinates.containsKey(VidUsVisualAreaType.Tissue)) {
        VidUsPhysicalCoordinate physicalCoordinate =
            visual.physicalCoordinates[VidUsVisualAreaType.Tissue]!;
        if (physicalCoordinate is VidUsLinearTissuePhysicalCoordinate) {
          physicalCoordinate.width;
        }
      }
      if (visual.logicalCoordinates.containsKey(VidUsVisualAreaType.Tissue)) {
        VidUsLogicalCoordinate logicalCoordinate =
            visual.logicalCoordinates[VidUsVisualAreaType.Tissue]!;
        logicalCoordinate.region.left;
        logicalCoordinate.region.right;
      }
    }
    onFirstFrameLoaded?.call(e);
    update([imageDataPlayerId]);
  }

  void hidePreviewImage() {
    showPreviewImage = false;
    update([imageDataPlayerId]);
  }

  @override
  void onInit() {
    super.onInit();
    mounted = true;
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
    mounted = false;
    _disposeVidPlayer();
  }

  @override
  void dispose() {
    super.dispose();
    mounted = false;
    _disposeVidPlayer();
  }
}

class VidProgressInfo {
  VidProgressInfo({
    required this.currentFrame,
    required this.totalFrames,
    required this.totalDuration,
  });

  final int currentFrame;
  final int totalFrames;
  final double totalDuration;
}
