import 'package:fis_measure/index.dart';
import 'package:fis_measure/view/player/controller_old.dart';
import 'package:fis_measure/view/player/enums.dart';
import 'package:fis_measure/view/player/events.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:fis_vid/data_host/data_host.dart';
import 'package:flyinsono/architecture/define.dart';

/// 用于图像快速预览的简单播放器
/// 构造结束后自动播放一遍，然后显示第一帧
class FQuickPreview extends FStatefulWidget {
  final String vidUrl;
  final String imageUrl;
  final double? width;
  final double? height;

  FQuickPreview(
      {required this.vidUrl, required this.imageUrl, this.width, this.height});

  @override
  _FQuickPreviewState createState() => _FQuickPreviewState();
}

class _FQuickPreviewState extends FState<FQuickPreview> {
  late final VidPlayerControllerNoSharing _playerController;
  bool isShowCover = true;
  bool isShowLoading = true;

  @override
  void initState() {
    final dataHost = VidDataHost(widget.vidUrl);
    final playerController = VidPlayerControllerNoSharing(dataHost: dataHost);
    _playerController = playerController;
    loadVidDataHost(_playerController);
    _playerController.eventHandler.addListener(onControllerEvent);
    super.initState();
  }

  @override
  void dispose() {
    _playerController.eventHandler.removeListener(onControllerEvent);
    _playerController.dispose();
    super.dispose();
  }

  void onControllerEvent(Object sender, VidPlayerEvent e) {
    if (e is VidPlayerStatusChangeEvent) {
      if (e.status == VidPlayStatus.pause) {
        setState(() {
          isShowCover = true;
        });
      }
    }
  }

  void loadVidDataHost(VidPlayerControllerNoSharing playerController) async {
    int retryCount = 0;
    while (retryCount < 3) {
      try {
        bool success = await playerController.load();
        if (!success) {
          throw "loadVidDataHost failed";
        }
        setState(() {
          isShowLoading = false;
        });
        if (playerController.totalFramesCount <= 1) {
          return; // 单帧图只显示封面，不播放
        }
        playerController.play();
        await Future.delayed(const Duration(milliseconds: 100));
        setState(() {
          isShowCover = false;
        });
        return;
      } catch (e) {
        retryCount++;
        if (retryCount == 3) {
          setState(() {
            isShowLoading = false;
          });
        } else if (!mounted) {
          return; // 如果组件已经被销毁，则停止重试
        }
      }
    }
  }

  @override
  FWidget build(BuildContext context) {
    return FStack(children: <FWidget>[
      FOffstage(
        offstage: !isShowCover,
        child: FContainer(
          child: FImage.network(
            widget.imageUrl,
            width: widget.width,
            height: widget.height,
            fit: BoxFit.contain,
            loadingBuilder: (context, child, loadingProgress) =>
                loadingProgress == null
                    ? child
                    : Center(
                        child: CircularProgressIndicator(
                          value: loadingProgress.expectedTotalBytes != null
                              ? loadingProgress.cumulativeBytesLoaded /
                                  loadingProgress.expectedTotalBytes!
                              : null,
                        ),
                      ),
          ),
        ),
      ),
      // 使用 Offstage 组件来控制第二个组件的可见性
      FOffstage(
          offstage: isShowCover,
          child: FCenter(
            child: FRepaintBoundary(
              child: QuickFWidget(
                VidPlayer(_playerController),
              ),
            ),
          )),
      FAlign(
          alignment: Alignment.topRight,
          child: FOffstage(
            child: FContainer(
              padding: EdgeInsets.all(10),
              width: 50,
              height: 50,
              child: FCircularProgressIndicator(),
            ),
            offstage: !isShowLoading,
          )),
    ]);
  }
}
