
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:twong/router/base.dart';
import 'package:twong/utils/image_utils.dart';
import 'package:uni_links/uni_links.dart';
import 'package:flutter_app_upgrade/flutter_app_upgrade.dart';

import 'package:twong/utils/index.dart';
import 'package:twong/config/style.dart';
import 'package:twong/models/index.dart';
import 'package:twong/pages/tabs/cart.dart';
import 'package:twong/pages/tabs/home.dart';
import 'package:twong/pages/tabs/user.dart';
import 'package:twong/pages/tabs/wallet.dart';

class Tabs extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _TabsState();
  }
}

class _TabsState extends State<Tabs> with WidgetsBindingObserver {
  int _currentIndex = 0;
  List<Widget> _pageList;
  PageController _pageController;

  @override
  void initState() {
    super.initState();
    Request.init();
    Notifications.init(context);
    WidgetsBinding.instance.addObserver(this);
    getLinksStream().listen(_processUrlScheme);

    if(!Cache.checked) {
      AppUpgrade.appUpgrade(
        context,
        _checkAppInfo(),
        iosAppId: '1537411658',
      );
    }

    _pageController = PageController(initialPage: _currentIndex);
    _pageList = [ HomePage(), WalletPage(), CartPage(), UserPage()];
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    Log.d("程序切换状态 ${state.toString()}");
    switch (state) {
      case AppLifecycleState.inactive: // 处于这种状态的应用程序应该假设它们可能在任何时候暂停。
        break;
      case AppLifecycleState.resumed:// 应用程序可见，前台
        _checkUrlScheme();
        break;
      case AppLifecycleState.paused: // 应用程序不可见，后台
        break;
      case AppLifecycleState.detached:
        break;
    }
  }

  void _checkUrlScheme() async {
    String url;
    try {
      url = await getInitialLink();
      if (url == null) return;
      _processUrlScheme(url);
    } on PlatformException {
      Log.e("Failed to get url scheme");
    }
  }

  void _processUrlScheme(String url) {
    final Uri uri = Uri.parse(url.replaceFirst('twong://', 'http://'));
    Log.d("Get url scheme: ${json.encode(uri.queryParameters).toString()}");
  }

  void _onItemTap (index) async {
    if(Cache.token == null && index != 0) {
      await Navigator.pushNamed(context, RouteNames.login);
      // 取消登陆 则不进行跳转
      if(Cache.token == null) return;
    }

    setState(() {
      _currentIndex = index;
      _pageController.jumpToPage(_currentIndex);
    });
  }

  Future<AppUpgradeInfo> _checkAppInfo() async {
    return Request.getVersion().then((remote) async {
      var version = await FlutterUpgrade.appInfo;
      Cache.checked = true;
      var local = Version();
      local.version = version.versionName;
      var need = remote > local;
      Log.i("remote:\t${remote.version}\nlocal:\t${local.version}\n"
          "${need ? "need update !" :"already is the latest."}");

      if (need) {
        return AppUpgradeInfo(
          title: '新版本${remote.version}',
          contents: ['检测到有新版本更新，是否立即下载？'],
          force: false,
        );
      } else {
        return null;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    HYSizeFit.initialize(context);

    return Scaffold(
      body: GestureDetector(
        child: WillPopScope(
          onWillPop: () async {
            await Utils.backDeskTop();
            return false;
          },
          child: PageView(
            controller: _pageController,
            physics: NeverScrollableScrollPhysics(),
            children: _pageList,
            onPageChanged: (index) {
              setState(() {
                _currentIndex = index;
              });
            },
          ),
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        elevation: 10,
        onTap: _onItemTap,
        fixedColor: Colors.black,
        currentIndex: _currentIndex,
        type: BottomNavigationBarType.fixed,
        items: [
          BottomNavigationBarItem(icon: _currentIndex == 0
              ? Icon(IconFonts.home, color: DColors.Main)
              : Icon(IconFonts.home_outline), label: I18n.home),
          BottomNavigationBarItem(icon: _currentIndex == 1
              ? Icon(IconFonts.wallet, color: DColors.Main)
              : Icon(IconFonts.wallet_outline), label: I18n.wallet),
          BottomNavigationBarItem(icon: _currentIndex == 2
              ? Icon(IconFonts.cart, color: DColors.Main)
              : Icon(IconFonts.cart_outline), label: I18n.cart),
          BottomNavigationBarItem(icon: _currentIndex == 3
              ? Icon(IconFonts.user, color: DColors.Main)
              : Icon(IconFonts.user_outline), label: I18n.user),
        ],
      ),
    );
  }
}