
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:twong/api/index.dart';
import 'package:twong/providers/user.dart';
import 'package:twong/utils/pay.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/router/base.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';
import 'package:twong/utils/image_utils.dart';

class Tabs extends StatefulWidget {
  final int index;
  Tabs({this.index = 0});
  @override
  State<StatefulWidget> createState() {
    return TabsState();
  }
}

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

  static TabsState _inst;
  static TabsState get inst => _inst;

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

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

    // if(!Cache.checked) {
    //   Utils.checkUpdate();
    // }
  }

  @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 {
    try {
      var 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: ${uri.queryParameters.toString()}");
  }

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

    setState(() {
      _currentIndex = index;
      _pageController.jumpToPage(_currentIndex);
      Log.d("jump to page $_currentIndex");
    });
  }

  @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: doItemTap,
        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),
        ],
      ),
    );
  }
}