import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';

// 图像放大预览插件
class FImageZoomInPlugin extends FStatefulWidget {
  const FImageZoomInPlugin({
    super.key,
    this.imageUrl,
    this.child,
  }) : super();
  final String? imageUrl;
  final FWidget? child;

  @override
  FState<FImageZoomInPlugin> createState() => FImageZoomInPluginState();
}

class FImageZoomInPluginState extends FState<FImageZoomInPlugin> {
  OverlayEntry? _entry;

  void _createNewEntry() {
    final OverlayState overlayState = Overlay.of(
      context,
      debugRequiredFor: widget,
    );

    final Size screenSize = MediaQuery.of(context).size;
    //截取屏幕大小的0.8倍宽高
    final double width = screenSize.width * 0.85;
    final double height = screenSize.height * 0.85;
    //宽高比为4:3，如果高度超出，按高度等比缩放，如果宽度超出，按宽度等比缩放
    final ifWidthLonger = width / height > 4 / 3;
    final double imageWidth = ifWidthLonger ? height * 4 / 3 : width;
    final double imageHeight = ifWidthLonger ? height : width * 3 / 4;
    // 边距
    final double marginHorizontal = (screenSize.width - imageWidth) / 2;
    final double marginVertical = (screenSize.height - imageHeight) / 2;
    final Widget overlay = IgnorePointer(
      child: Container(
        decoration: BoxDecoration(
          color: Colors.black.withOpacity(0.7),
          borderRadius: BorderRadius.circular(4),
        ),
        margin: EdgeInsets.symmetric(
            horizontal: marginHorizontal, vertical: marginVertical),
        child: Center(
          child: Image.network(
            widget.imageUrl!,
            width: imageWidth,
            height: imageHeight,
            fit: BoxFit.contain,
            loadingBuilder: (context, child, loadingProgress) =>
                loadingProgress == null
                    ? child
                    : Center(
                        child: CircularProgressIndicator(
                          value: loadingProgress.expectedTotalBytes != null
                              ? loadingProgress.cumulativeBytesLoaded /
                                  loadingProgress.expectedTotalBytes!
                              : null,
                        ),
                      ),
          ),
        ),
      ),
    );
    _entry = OverlayEntry(builder: (BuildContext context) => overlay);
    overlayState.insert(_entry!);
  }

  @override
  FWidget build(BuildContext context) {
    return FMouseRegion(
      onEnter: (event) {
        _showOverlay();
      },
      onExit: (event) {
        _hideOverlay();
      },
      child: FContainer(
        child: widget.child,
      ),
    );
  }

  /// 显示
  void _showOverlay() {
    _createNewEntry();
  }

  /// 隐藏
  void _hideOverlay() {
    _entry?.remove();
    _entry = null;
  }

  @override
  void dispose() {
    super.dispose();
    if (_entry != null) {
      _entry?.remove();
      _entry = null;
    }
  }
}
