import 'dart:async';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_user_agent/flutter_user_agent.dart';
import 'package:zhiying_base_widget/pages/launch_page/launch_page.dart';
import 'package:zhiying_comm/util/log/let_log.dart';
import 'package:zhiying_comm/util/empty_util.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:zhiying_comm/util/shared_prefe_util.dart';
import 'package:zhiying_comm/util/global_config.dart';

class BaseWebview extends StatefulWidget {
  final Map<String, dynamic> model;

  const BaseWebview(this.model, {Key key}) : super(key: key);

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

class _BaseWebviewState extends State<BaseWebview> {
  String _url;
  String _title;
  WebViewController _webViewController;
  bool _isiOSReview = false;
  double progress = 0.0;
  Timer timer;

  @override
  void initState() {
    _url = widget.model['url'] ?? '';
    _settingIosReview();
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    timer?.cancel();
    super.dispose();
  }

  loadData() {
    print("加载数据");
    progress = 0.0;
    if (timer?.isActive ?? false) {
      timer?.cancel();
    }
    timer = Timer.periodic(Duration(milliseconds: 10), (timer) {
      if (progress > 0.8) {
        progress = progress + 0.01;
      } else if (progress > 0.7) {
        progress = progress + 0.002;
      } else if (progress > 0.5) {
        progress += 0.005;
      } else {
        progress = progress + 0.01;
      }
      if (progress > 1.1) {
        timer.cancel();
      }
      setState(() {});
    });
  }

  void _settingIosReview() async {
    String is_ios_review = await SharedPreferencesUtil.getStringValue(GlobalConfig.IS_IOS_REVIEW, defaultVal: '0');
    setState(() {
      if (is_ios_review == '1') {
        _isiOSReview = true;
        print(_isiOSReview);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    print("设备："+FlutterUserAgent.webViewUserAgent);
    return Scaffold(
      appBar: _createNav(),
      backgroundColor: Colors.white,
      body: Stack(
        children: <Widget>[
          WebView(
            initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow,
            initialUrl: _url,
            userAgent: FlutterUserAgent.userAgent,
            javascriptMode: JavascriptMode.unrestricted,
            onWebViewCreated: (WebViewController webViewController) {
              _webViewController = webViewController;
              loadData();
            },

            navigationDelegate: (NavigationRequest request) async {

              print("重定向" + request.url);
              // 解决Android的拼多多webview 转发的问题
              if (Platform.isAndroid) {
                String url = request?.url?.toString();
                if (!EmptyUtil.isEmpty(url) && !url.startsWith('https://') && !url.startsWith('http://')) {
                  Logger.log('navigation url = $url');
                  if (await canLaunch(url)) {
                    await launch(url);
                  }
                  return NavigationDecision.prevent;
                }
              }
              return NavigationDecision.navigate;
            },
            onPageStarted: (String url) {
              print('Page started loading: $url');
            },
            onPageFinished: (String url) {
              if (progress < 0.8) {
                progress = 0.8;
              }
              //setState(() {});
              print('Page finished loading: $url');
              _webViewController.getTitle().then((title) {
                _title = title;
                // setState(() {});
              });
            },
            gestureNavigationEnabled: true,
          ),
          progress <= 1.0 ? _createProgress() : Container(),
        ],
      ),
    );
  }

// 导航栏
  Widget _createNav() {
    return CupertinoNavigationBar(
      border: Border(
        bottom: BorderSide(
          width: 0.0, // One physical pixel.
          style: BorderStyle.none,
        ),
      ),
      backgroundColor: Colors.white,
      leading: Navigator.canPop(context)
          ? GestureDetector(
              child: Container(
                padding: EdgeInsets.zero,
                child: Icon(
                  Icons.arrow_back_ios,
                  size: 20,
                ),
              ),
              onTap: () {
                if (Navigator.canPop(context)) {
                  Navigator.pop(context);
                }
              },
            )
          : Container(),
      middle: Text(
        _title ?? '',
        maxLines: 1,
        style: TextStyle(
          fontSize: 15,
          color: Color(0xff333333),
        ),
      ),
      trailing: GestureDetector(
        child: _isiOSReview
            ? Container()
            : Icon(
                Icons.refresh,
                size: 20,
              ),
        onTap: () {
          _webViewController.reload();
          loadData();
        },
      ),
    );
  }

  _createProgress() {
    return Container(
      constraints: BoxConstraints(maxHeight: 2),
      child: LinearProgressIndicator(
        backgroundColor: Colors.white,
        valueColor: AlwaysStoppedAnimation<Color>(Colors.red),
        value: progress,
      ),
    );
  }
}
