import 'package:auto_route/annotations.dart';
import 'package:eitc_erm_dental_flutter/exts.dart';
import 'package:eitc_erm_dental_flutter/funcs.dart';
import 'package:eitc_erm_dental_flutter/widget/webview_progress_bar.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:retrofit/dio.dart';

import '../../http/api_exception.dart';

///Webview页面
@RoutePage(name: "webviewRoute")
class WebviewPage extends StatefulWidget {
  final String url;
  final String? title;
  final Future<HttpResponse<String>>? htmlFuture;

  const WebviewPage(
      {super.key, required this.url, this.title, this.htmlFuture});

  @override
  State<WebviewPage> createState() => _WebviewPageState();
}

class _WebviewPageState extends State<WebviewPage> {
  final GlobalKey _webViewKey = GlobalKey();

  InAppWebViewController? _webViewController;
  final InAppWebViewSettings _settings = InAppWebViewSettings(
      isInspectable: kDebugMode,
      mediaPlaybackRequiresUserGesture: false,
      allowsInlineMediaPlayback: true,
      iframeAllow: "camera",
      iframeAllowFullscreen: true,
      javaScriptEnabled: true);

  final WebviewProgressBarController _progressBarController =
      WebviewProgressBarController();

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

  @override
  void dispose() {
    super.dispose();
    _progressBarController.dispose();
  }

  void _load() async {
    if (widget.htmlFuture != null) {
      try {
        HttpResponse<String> response = await widget.htmlFuture!;
        _webViewController?.loadData(data: response.data);
      } catch (e) {
        loge("加载webview html异常", error: ApiException.from(e));
      }
    } else {
      _webViewController?.loadUrl(
          urlRequest: URLRequest(url: WebUri(widget.url)));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: widget.title.isNullOrEmpty ? null : Text(widget.title!),
        centerTitle: true,
      ),
      //body: SafeArea(child: WebViewWidget(controller: _controller)),
      body: SafeArea(
        child: Stack(
          children: [
            InAppWebView(
              key: _webViewKey,
              initialSettings: _settings,
              onWebViewCreated: (controller) {
                _webViewController = controller;
                _load();
              },
              onLoadStart: (controller, url) {
                logd("onLoadStart,url=$url");
              },
              onPermissionRequest: (controller, request) async {
                return PermissionResponse(
                    resources: request.resources,
                    action: PermissionResponseAction.GRANT);
              },
              onLoadStop: (controller, url) async {
                logd("onLoadStop,url=$url");
              },
              onReceivedError: (controller, request, error) {
                loge("onReceivedError", error: error);
              },
              onProgressChanged: (controller, progress) {
                logd("onProgressChanged,progress=$progress");
                _progressBarController.setProgress(progress);
              },
              onConsoleMessage: (controller, consoleMessage) {
                if (kDebugMode) {
                  logd(consoleMessage);
                }
              },
            ),
            Align(
              alignment: Alignment.topLeft,
              child: WebviewProgressBar(controller: _progressBarController),
            )
          ],
        ),
      ),
    );
  }
}
