import 'package:flutter/material.dart';
import 'package:liftmanager/internal/maintenance/model/maintenance_count_item.dart';
import 'package:liftmanager/internal/maintenance/provider/maintenance_page_provider.dart';
import 'package:liftmanager/internal/maintenance/widgets/maintenance_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/widgets/app_bar.dart';
import 'package:liftmanager/widgets/calendar/flutter_calendar.dart';
import 'package:provider/provider.dart' as p;

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

  final bool topInto;
  @override
  MaintenanceListPageState createState() => MaintenanceListPageState();
}

class MaintenanceListPageState extends State<MaintenanceListPage>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  MaintenancePageProvider provider = MaintenancePageProvider();
  List<Map> tabs = [
    {"id": 0, "name": "待保养"},
    {"id": 1, "name": "保养中"},
    {"id": 2, "name": "已完成"},
    {"id": 3, "name": "超期"}
  ];
  TabController _tabController;
  PageController _pageController;
  Calendar mCalendar;
  DateTime selectedDate = DateTime.now();
  DateTime _pageDate = DateTime.now();
  List<MantenanceCountItem> _arrCount = [];
  List<Widget> mListView = [];

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

  initListView() {
    mListView.add(MaintenanceList(index: 0, date: DateTime.now(),callback: (){
      getCalenderDate();
    },));
    mListView.add(MaintenanceList(index: 1, date: DateTime.now(),callback: (){
      getCalenderDate();
    }));
    mListView.add(MaintenanceList(index: 2, date: DateTime.now(),callback: (){
      getCalenderDate();
    }));
    mListView.add(MaintenanceList(index: 3, date: DateTime.now(),callback: (){
      getCalenderDate();
    }));
  }

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

  _onPageChange(int index) {
    _tabController.animateTo(index);
    provider.setIndex(index);
    MaintenanceList widget = mListView[_pageController.page.toInt()];
    if(widget.mState !=null){
      widget.mState.onRefresh();
    }

  }

  void getCalenderDate() {
    ApiService(context: context)
        .maintenanceCount(_pageDate.toString().split(" ")[0], onSuccess: (res) {
      _arrCount = res;
      initHeaderTitle();
      setState(() {});
    }, onError: (code, msg) {});
  }

  void initHeaderTitle() {
    mCalendar.updateState(_arrCount);
  }

  mCount(int key) {
    int str = 0;
    for (var i = 0; i < _arrCount.length; i++) {
      if (DateTime.parse('${_arrCount[i].planDate}').year == mCalendar.currentSelected().year&&
          DateTime.parse('${_arrCount[i].planDate}').month == mCalendar.currentSelected().month&&
          DateTime.parse('${_arrCount[i].planDate}').day == mCalendar.currentSelected().day) {
        switch(key){
          case 0:
            str = _arrCount[i].waitingMaintenance;
            break;
          case 1:
            str = _arrCount[i].inProgress;
            break;
          case 2:
            str = _arrCount[i].complete;
            break;
          case 3:
            str = _arrCount[i].overdue;
            break;

        }
      }
    }
    return "(${str})";
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return p.ChangeNotifierProvider<MaintenancePageProvider>(
      create: (_) => provider,
      child: WillPopScope(
      onWillPop:(){
        NavigatorUtils.goBackWithParams(context,true);
        return Future.value(false);
      },
      child:Scaffold(
        appBar: MyAppBar(
          centerTitle: "保养管理",
          actions: <Widget>[
            FlatButton(
              child: Text("今天"),
              textColor: Colours.dark_text,
              highlightColor: Colors.transparent,
              onPressed: () {
                mCalendar.today();
              },
            )
          ],
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            calendarWidget(),
            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.only(left: 0),
                  unselectedLabelColor: Colours.text_gray,
                  labelColor: Theme.of(context).primaryColor,
                  indicatorPadding:
                      const EdgeInsets.only(left: 20.0, right: 20.0),
                  tabs: tabs.map((map) {
                    return _TabView(
                        "${map["name"]}", "${mCount(map["id"])}", map["id"]);
                  }).toList()),
            ),
            Gaps.line,
            Expanded(
              child: PageView.builder(
                key: const Key('pageView'),
                itemCount: tabs.length,
                onPageChanged: _onPageChange,
                controller: _pageController,
                itemBuilder: (BuildContext context, int index) {
                  return Container(
                      color: ThemeUtils.getBackgroundColor(context),
                      child: mListView[index]);
                },
              ),
            )
          ],
        ),
      ),
    ));
  }

  Widget calendarWidget() {
    if (mCalendar == null) {
      mCalendar = Calendar(
        showTodayAction: false,
        showChevronsToChangeRange: false,
        showCalendarPickerIcon: false,
        onSelectedRangeChange: (range) {
          print("Range1 is ${range.item1}, ${range.item2}");
          _pageDate = range.item1;
          getCalenderDate();
        },
        onDateSelected: (res) {
          selectedDate = res;
          initHeaderTitle();
          print(_pageController.page);
          for(var i=0;i<mListView.length;i++){
            MaintenanceList widget = mListView[i];
            widget.date = res;
          }
          MaintenanceList widget = mListView[_pageController.page.toInt()];
          widget.date = res;
          if(widget.mState !=null){
            widget.mState.onRefresh();
          }
          setState(() {});
          print("currentSelected is ${mCalendar.currentSelected()}");
          print("Range2 is ${res}");
        },
        isExpandable: true,
      );
    }
    return mCalendar;
  }

  @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<MaintenancePageProvider>(
      builder: (_, provider, child) {
        bool isDark = ThemeUtils.isDark(context);
        return Tab(
            child: SizedBox(
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(right: 3),
                width: 8,
                height: 8,
                decoration: BoxDecoration(
                  color: index==0?Colors.grey:index==1?Colors.yellow:index==2?Color(0xFF9CD19E):Colors.red,
                  borderRadius: BorderRadius.circular(4)
                ),
              ),
              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)),
              )
            ],
          ),
        ));
      },
    );
  }
}



