import 'package:eitc_erm_dental_flutter/funcs.dart';
import 'package:flutter/material.dart';

///Webview进度条
class WebviewProgressBar extends StatefulWidget {
  final WebviewProgressBarController controller;
  final bool autoHide;
  final Color? backgroundColor;
  final Color? color;
  final Animation<Color?>? valueColor;
  final String? semanticsLabel;
  final String? semanticsValue;
  final BorderRadiusGeometry borderRadius;

  const WebviewProgressBar(
      {super.key,
      required this.controller,
      this.autoHide = true,
      this.backgroundColor,
      this.color,
      this.valueColor,
      this.semanticsLabel,
      this.semanticsValue,
      this.borderRadius = BorderRadius.zero});

  @override
  State<WebviewProgressBar> createState() => _WebviewProgressBarState();
}

class _WebviewProgressBarState extends State<WebviewProgressBar> {
  @override
  void initState() {
    super.initState();
    widget.controller.progress.addListener(_onUpdateProgress);
  }

  void _onUpdateProgress() {
    setState(() {});
  }

  @override
  void dispose() {
    super.dispose();
    widget.controller.progress.removeListener(_onUpdateProgress);
  }

  @override
  Widget build(BuildContext context) {
    WebviewProgressBarController controller = widget.controller;
    if (controller.progress.value >= 100 && widget.autoHide) {
      return SizedBox();
    }
    return LinearProgressIndicator(
      value: controller.progress.value / 100,
      backgroundColor: widget.backgroundColor,
      color: widget.color,
      valueColor: widget.valueColor,
      semanticsLabel: widget.semanticsLabel,
      semanticsValue: widget.semanticsValue,
      borderRadius: widget.borderRadius,
    );
  }
}

///Webview进度条控制器
class WebviewProgressBarController {
  ///进度
  ValueNotifier<int>? _progress;

  ///进度
  ValueNotifier<int> get progress => _progress ??= ValueNotifier(0);

  ///设置进度
  void setProgress(int value) {
    progress.value = value;
  }

  void dispose() {
    _progress?.dispose();
    _progress = null;
  }
}
