// ignore_for_file: must_be_immutable

import 'package:account_center/account_center.dart';
import 'package:account_center/page/account_company/company_auth/widget/common/gesture_tap.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class CustomWebView extends StatefulWidget {
  String url = "";
  String? title;

  CustomWebView({
    super.key,
    required this.url,
    this.title,
  });

  @override
  State<StatefulWidget> createState() {
    return _CustomWebView();
  }
}

class _CustomWebView extends State<CustomWebView> {
  WebViewController controller = WebViewController();

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

    controller
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(Colors.white)
      ..loadRequest(
        Uri.parse(widget.url),
      )
      ..setNavigationDelegate(NavigationDelegate(
        onPageStarted: (url) {
          print('-----------onPageStarted:$url');
        },
        onPageFinished: (url) {
          print('-----------onPageFinished:$url');
        },
        onProgress: (progress) {
          print('-----------onProgress:$progress----${Uri.parse(widget.url)}');
        },
        onWebResourceError: (error) {
          print('-----------onWebResourceError:${error.description}');
          print('-----------onWebResourceError:${error.errorType}');
        },
        onNavigationRequest: (request) {
          if (request.url.startsWith("alipays")) {
            canLaunchUrl(Uri.parse(request.url)).then((value) {
              launchUrl(
                Uri.parse(request.url),
                mode: LaunchMode.externalApplication,
              );
            });
            return NavigationDecision.prevent;
          }
          return NavigationDecision.navigate;
        },
      ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
        color: Colors.white,
        child: Stack(children: [
          Expanded(child: WebViewWidget(controller: controller)),
          GestureTapWidget(
            onTap: () {
              controller.canGoBack().then((value) {
                if (value) {
                  controller.goBack();
                } else {
                  Get.back();
                }
              });
            },
            child: Container(
              padding: const EdgeInsets.only(left: 15),
              alignment: Alignment.centerLeft,
              width: 75,
              height: 44,
              child: Icon(
                Icons.arrow_back_ios,
                color: Colors.black,
                size: 20,
              ),
            ),
          )
        ]),
      ),
    );
  }
}
