import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../consts/color.dart';
import '../services/permission_view_manger.dart';
import '../utils/GetConfig.dart';

class Index extends StatefulWidget {
  @override
  _IndexState createState() => _IndexState();
}

class _IndexState extends State<Index> {
  int _currentIndex = 0;
  PermissionViewManger permissionManger;
  List barItems;
  String theme;

  @override
  void initState() {
    super.initState();
    SharedPreferences.getInstance().then((sp) {
      this.theme = sp.getString("theme") ?? KColorConstant.DEFAULT_COLOR;
      var companyData = sp.get("companyList");
      //var userHaveToDo = sp.get("userHaveToDo");
      if (null != companyData) {
        dynamic userPowers = jsonDecode(companyData);
        // dynamic userHaveList= jsonDecode(userHaveToDo);
        permissionManger = PermissionViewManger(userPowers, this.theme);
        setState(() {});
      } else {
        Navigator.of(context).pop();
      }
    });
  }

  // BottomNavigationBar items 需要大于两项
  @override
  Widget build(BuildContext context) {
    List<BottomNavigationBarItem> barItems = permissionManger.getBarItems();
    List<Widget> views = permissionManger.getViews();
    if (barItems.length >= 2) {
      return Scaffold(
        body: views[_currentIndex],
        // IndexedStack(
        //   index: _currentIndex,
        //   children: views,
        // ),
        bottomNavigationBar: BottomNavigationBar(
          unselectedFontSize: Theme.of(context).tabBarTheme.labelStyle.fontSize,
          selectedFontSize: Theme.of(context).tabBarTheme.labelStyle.fontSize,
          items: barItems,
          fixedColor: GetConfig.getColor(theme),
          currentIndex: _currentIndex,
          type: BottomNavigationBarType.fixed,
          onTap: (index) {
            setState(() {
              _currentIndex = index;
            });
          },
        ),
      );
    } else {
      return Scaffold(
        body: IndexedStack(
          index: _currentIndex,
          children: views,
        ),
      );
    }
  }
}
