import 'package:flutter/material.dart';
import 'package:liftmanager/common/common.dart';
import 'package:liftmanager/common/user_db.dart';
import 'package:liftmanager/internal/repair/model/repair_count_item.dart';
import 'package:liftmanager/internal/repair/provider/repair_page_provider.dart';
import 'package:liftmanager/internal/repair/repair_router.dart';
import 'package:liftmanager/internal/repair/widgets/repair_list.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/theme_utils.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:provider/provider.dart' as p;

class RepairListPage extends StatefulWidget {
  RepairListPage({this.topInto = false});

  final bool topInto;

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

class RepairListPageState extends State<RepairListPage>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  RepairPageProvider provider = RepairPageProvider();

  TabController _tabController;
  PageController _pageController = PageController(initialPage: 0);
  List<Widget> mListView = [];
  RepairCountItem countItem = RepairCountItem();

  @override
  void initState() {
    super.initState();
    initListView();
    _tabController = new TabController(vsync: this, length: 3);
//    if (widget.topInto) {
//      _tabController.animateTo(1);
//      _pageController = PageController(initialPage: 1);
//    } else {
      _pageController = PageController(initialPage: 0);
//    }
    getHasRole();
    getCount();
  }

  getCount() {
    ApiService(context: context).repairCount(onSuccess: (res) {
      if (res != null) {
        countItem = res;
        setState(() {});
      }
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  bool noRole = true;

  getHasRole() async {
    var role = await User().getCompanyRole();
    if (role == Constant.RoleAdmin ||
        role == Constant.RoleRegion ||
        role == Constant.RoleWork) {
      noRole = false;
      setState(() {});
    }
  }

  initListView() {
    mListView.add(RepairList(
        index: 0,
        callback: () {
          getCount();
        }));
    mListView.add(RepairList(
        index: 1,
        callback: () {
          getCount();
        }));
    mListView.add(RepairList(
        index: 2,
        callback: () {
          getCount();
        }));
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  _onPageChange(int index) {
    _tabController.animateTo(index);
    provider.setIndex(index);
    getCount();
  }

  goToPage(pagePath) {
    NavigatorUtils.pushResult(context, pagePath, (res) {
      getCount();
      print(_pageController.page.toInt());
      RepairList widget = mListView[_pageController.page.toInt()];
      if (widget.mState != null) {
        widget.mState.onRefresh();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return p.ChangeNotifierProvider<RepairPageProvider>(
        create: (_) => provider,
        child: WillPopScope(
          onWillPop: () {
            NavigatorUtils.goBackWithParams(context, true);
            return Future.value(false);
          },
          child: Scaffold(
            appBar: MyAppBar(
              centerTitle: "急修管理",
              actions: <Widget>[
                Offstage(
                    offstage: noRole,
                    child: FlatButton(
                      child: Text("新建", key: const Key('actionName')),
                      textColor: Colours.dark_text,
                      highlightColor: Colors.transparent,
                      onPressed: () {
                        goToPage(RepairRouter.repairCreatePage);
                      },
                    ))
              ],
            ),
            body: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                  // 隐藏点击效果
                  color: ThemeUtils.getTabsBg(context),
                  child: TabBar(
                    onTap: (index) {
                      if (!mounted) {
                        return;
                      }
                      _pageController.jumpToPage(index);
                    },
                    isScrollable: false,
                    controller: _tabController,
                    labelStyle: TextStyles.textBold18,
                    indicatorSize: TabBarIndicatorSize.label,
                labelPadding: const EdgeInsets.all(0),
                    unselectedLabelColor: Colours.text_gray,
                    labelColor: Theme.of(context).primaryColor,
                    indicatorPadding:
                        const EdgeInsets.only(left: 20.0, right: 20.0),
                    tabs: <Widget>[
                      _TabView("待修理", "(${countItem.toRepair})", 0),
                      _TabView("修理中", "(${countItem.processing})", 1),
                      _TabView("已完成", "(${countItem.complete})", 2),
                    ],
                  ),
                ),
                Gaps.line,
                Expanded(
                  child: PageView.builder(
                    key: const Key('pageView'),
                    itemCount: 3,
                    onPageChanged: _onPageChange,
                    controller: _pageController,
                    itemBuilder: (BuildContext context, int index) {
                      return Container(
                          color: ThemeUtils.getBackgroundColor(context),
                          child: mListView[index]);
                    },
                  ),
                )
              ],
            ),
          ),
        ));
  }

  @override
  bool get wantKeepAlive => true;
}

class _TabView extends StatelessWidget {
  const _TabView(this.tabName, this.tabSub, this.index);

  final String tabName;
  final String tabSub;
  final int index;

  @override
  Widget build(BuildContext context) {
    return p.Consumer<RepairPageProvider>(
      builder: (_, provider, child) {
        bool isDark = ThemeUtils.isDark(context);
        return Tab(
            child: SizedBox(
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                tabName,
                style: TextStyle(
                    fontSize: 15,
                    color: isDark ? Colours.dark_text : Colours.text),
              ),
              Padding(
                padding: const EdgeInsets.only(top: 1.0),
                child:
                    Text(tabSub, style: TextStyle(fontSize: Dimens.font_sp12)),
              ),
            ],
          ),
        ));
      },
    );
  }
}
