import 'dart:async';

import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:liftmanager/common/common.dart';
import 'package:liftmanager/internal/heavy/heavy_router.dart';
import 'package:liftmanager/internal/maintenance/maintenance_router.dart';
import 'package:liftmanager/internal/message/message_router.dart';
import 'package:liftmanager/internal/project/project_router.dart';
import 'package:liftmanager/internal/repair/repair_router.dart';
import 'package:liftmanager/internal/sign/sign_router.dart';
import 'package:liftmanager/internal/team/team_router.dart';
import 'package:liftmanager/internal/work/model/banner_entity.dart';
import 'package:liftmanager/internal/work/model/count_doing_item.dart';
import 'package:liftmanager/internal/work/work_router.dart';
import 'package:liftmanager/internal/yearly/yearly_router.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/load_image.dart';
import 'package:liftmanager/widgets/my_card.dart';
import 'package:liftmanager/widgets/my_flexible_space_bar.dart';
import 'package:liftmanager/internal/work/provider/work_page_provider.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';
import 'package:liftmanager/internal/bbs/bbs_router.dart';
import 'package:liftmanager/utils/utils.dart';

const timeout = const Duration(seconds: 5);
CountDoingItem countDoingItem = CountDoingItem();

class WorkPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _WorkPageState();
  }
}

class _WorkPageState extends State<WorkPage> with TickerProviderStateMixin {
  WorkPageProvider provider = WorkPageProvider();
  TabController _tabController;
  PageController _pageController = PageController();
  int _index = 0;
  Timer _timer;
  List<BannerEntity> bannerList = [];


  @override
  void initState() {
    _tabController = TabController(length: 0, vsync: this);
    _timer = Timer.periodic(timeout, _handleTimeout);
    getBanner();
    countDoing();
    super.initState();
  }

  @override
  void dispose() {
    _tabController?.dispose();
    _timer.cancel();
    _pageController.dispose();
    super.dispose();
  }

  void getBanner() {
    ApiService(context: context).getBanner(
        onSuccess: (data) {
          if(!mounted){
            return;
          }
          bannerList = data;//todo
          if (bannerList.length > 0) {
            _pageController.jumpToPage(0);
            _tabController =
                TabController(length: bannerList.length, vsync: this);
            setState(() {});
          }
        },
        onError: (code, msg) {
          showToast(msg);
        });
  }

  void countDoing() {
    ApiService(context: context).countDoing(
        onSuccess: (data) {

          if(!mounted) return;
          setState(() {
            countDoingItem = data;//todo
          });
        },
        onError: (code, msg) {
//          showToast(msg);
        });
  }

  _handleTimeout(Timer timer) {
    _index++;
    _pageController.animateToPage(
      _index % (bannerList.length == 0 ? 1 : bannerList.length),
      duration: Duration(milliseconds: 16),
      curve: Curves.fastOutSlowIn,
    );
  }

  void _onPageChanged(int index) {
    _index = index;
    _tabController.animateTo(index);
  }

  goToPage(pagePath){
    NavigatorUtils.pushResult(context, pagePath, (res){
      countDoing();
    });
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<WorkPageProvider>(
        create: (_) => provider,
        child: Scaffold(
          backgroundColor: ThemeUtils.getTabsBg(context),
          body: CustomScrollView(
            key: const Key('statistic_list'),
            physics: ClampingScrollPhysics(),
            slivers: _sliverBuilder(),
          ),
        ));
  }

  Widget bannerWidget() {
    return Container(
        height: 100,
        child: Stack(
          children: <Widget>[
            PageView(
              children: bannerList.map((item) {
                return GestureDetector(
                  onTap: (){
                    if(item.url.length>0){
                      goToPage("${WorkRouter.webview}?title="+Uri.encodeComponent("详情")+"&url="+Uri.encodeComponent(item.url));
                    }
                  },
                  child: Image.network(
                    item.image??"",
                    fit: BoxFit.fill, //使照片占满整个屏幕
                  ),
                );
              }).toList(),
              onPageChanged: _onPageChanged,
              controller: _pageController,
            ),
            Align(
              alignment: Alignment(0.0, 0.9),
              child: TabPageSelector(
                color: Colors.white,
                selectedColor: Colours.app_main,
                controller: _tabController,
              ),
            ),
          ],
        ));
  }

  List<Widget> _sliverBuilder() {
    bool isDark = ThemeUtils.isDark(context);
    return <Widget>[
      SliverAppBar(
        brightness: Brightness.dark,
        leading: Gaps.empty,
        backgroundColor: Colors.transparent,
        elevation: 0.0,
        centerTitle: true,
        expandedHeight: 150.0,
        pinned: true,
        flexibleSpace: MyFlexibleSpaceBar(
          background: bannerWidget(),
//          const LoadAssetImage(
//            "work/statistic_bg",
//            width: double.infinity,
//            height: 138.0,
//            fit: BoxFit.fill,
//          ),
          centerTitle: true,
          titlePadding:
              const EdgeInsetsDirectional.only(start: 16.0, bottom: 14.0),
          collapseMode: CollapseMode.pin,
          title: Text(
            '',
            style: TextStyle(color: ThemeUtils.getIconColor(context)),
          ),
        ),
      ),
      SliverPersistentHeader(
        pinned: true,
        delegate: SliverAppBarDelegate(
            DecoratedBox(
              decoration: BoxDecoration(

//                  image: DecorationImage(
//                      image: ImageUtils.getAssetImage("work/statistic_bg1"),
//                      fit: BoxFit.fill)
                  ),
              child: Column(
                children: <Widget>[
                  MyCard(
                    child: Container(
                        color: isDark?Colours.dark_bg_color:Colors.white,
                        height: 90.0,
                        padding: const EdgeInsets.only(top: 8.0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: <Widget>[
                             _TabView(0, '待保养',onTap: (){
                               if (SpUtil.getString(Constant.companyId).length == 0) {
                                 showAlert(
                                     context,
                                     "提示",
                                     "尚未加入团队，是否立即加入？",
                                     "确定",
                                         () {
                                       NavigatorUtils.goBack(context);
//                                       NavigatorUtils.goBackWithParams(context, true);
                                       goToPage(TeamRouter.teamListPage);

                                     },
                                     txt2: "取消",
                                     onPre2: () {
                                       NavigatorUtils.goBack(context);
//                                       NavigatorUtils.goBackWithParams(context, true);
                                     });
                               }else{
                                 goToPage("${MaintenanceRouter.maintenanceListPage}?top_into=0");
                               }
                             },),
                             _TabView(1, '待急修',onTap: (){
                               if (SpUtil.getString(Constant.companyId).length == 0) {
                                 showAlert(
                                     context,
                                     "提示",
                                     "尚未加入团队，是否立即加入？",
                                     "确定",
                                         () {
                                       NavigatorUtils.goBack(context);
                                       goToPage(TeamRouter.teamListPage);

                                     },
                                     txt2: "取消",
                                     onPre2: () {
                                       NavigatorUtils.goBack(context);
                                     });
                               }else{
                                 goToPage("${RepairRouter.repairListPage}?top_into=1");
                               }
                             },),
                             _TabView(2, '待年检',onTap: (){
                               if (SpUtil.getString(Constant.companyId).length == 0) {
                                 showAlert(
                                     context,
                                     "提示",
                                     "尚未加入团队，是否立即加入？",
                                     "确定",
                                         () {
                                       NavigatorUtils.goBack(context);
                                       goToPage(TeamRouter.teamListPage);

                                     },
                                     txt2: "取消",
                                     onPre2: () {
                                       NavigatorUtils.goBack(context);
                                     });
                               }else{
                                 goToPage("${YearlyRouter.yearlyListPage}?top_into=1");
                               }
                             },),
                             _TabView(3, '待大修',onTap: (){
                               if (SpUtil.getString(Constant.companyId).length == 0) {
                                 showAlert(
                                     context,
                                     "提示",
                                     "尚未加入团队，是否立即加入？",
                                     "确定",
                                         () {
                                       NavigatorUtils.goBack(context);
                                       goToPage(TeamRouter.teamListPage);

                                     },
                                     txt2: "取消",
                                     onPre2: () {
                                       NavigatorUtils.goBack(context);
                                     });
                               }else{
                                 goToPage("${HeavyRouter.heavyListPage}?top_into=1");
                               }

                             },),
                          ],
                        )),
                  ),
                ],
              ),
            ),
            90.0),
      ),
      SliverToBoxAdapter(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Gaps.vGap16,
              Gaps.vGap16,
              Container(
                padding: EdgeInsets.only(left: 20, right: 20),
                child: const Text("必备工具", style: TextStyles.textBold15),
              ),
              Gaps.vGap16,
              _ToolsItem(menuTitle, menuImage, (index) {
                
                if(index == 7){
                  if(Utils.getAuthByRouter("expert_workbench", false)){
                    NavigatorUtils.push(context, BbsRouter.workPlace);
                  }else {
                    toasts("暂无权限，请申请成为专家");
                  }
                  
                  return;
                }
                if (SpUtil.getString(Constant.companyId).length == 0) {
                  showAlert(
                      context,
                      "提示",
                      "尚未加入团队，是否立即加入？",
                      "确定",
                      () {
                        NavigatorUtils.goBack(context);
                        goToPage(TeamRouter.teamListPage);

                      },
                      txt2: "取消",
                      onPre2: () {
                        NavigatorUtils.goBack(context);
                      });
                } else {
                  if (index == 0) {
                    goToPage(ProjectRouter.projectPage);
                  } else if (index == 1) {
                    goToPage(MaintenanceRouter.maintenanceListPage);
                  } else if (index == 2) {
                    goToPage(RepairRouter.repairListPage);
                  } else if (index == 3) {
                    goToPage(YearlyRouter.yearlyListPage);
                  } else if (index == 4) {
                    goToPage(MessageRouter.messageListPage);
                  } else if (index == 5) {
                    goToPage(SignRouter.signPage);
                  }else if (index == 6) {
                    goToPage(HeavyRouter.heavyListPage);
                  }
                }
              }),
              Container(
                padding: EdgeInsets.only(left: 20, right: 20),
                child: const Text("常用工具", style: TextStyles.textBold15),
              ),
              Gaps.vGap16,
              _ToolsItem(menuTitle2, menuImage2, (index) {
                if (SpUtil.getString(Constant.companyId).length == 0) {
                  showAlert(context, "提示", "尚未加入团队，是否立即加入？", "确定", () {
                    goToPage(TeamRouter.teamSearchPage);
                    NavigatorUtils.goBack(context);
                  },
                      txt2: "取消", onPre2: () {
                        NavigatorUtils.goBack(context);
                      });

                } else {
                  if (index == 0) {
                    goToPage(TeamRouter.teamListPage);
                  } else if (index == 1) {
                    goToPage(TeamRouter.teamUserPage);
                  }
                }
              }),
            ],
          ),
        ),
      )
    ];
  }
}

List<String> menuTitle = ["项目电梯", "日常保养", "急修管理", "年检管理", "消息中心", "签到打卡","大修","专家工作台"];
List<String> menuImage = [
  "icon_xmdt",
  "icon_rcby",
  "icon_jxgl",
  "icon_njgl",
  "icon_xxzx",
  "icon_dkqd",
  "icon_dx",
  "icon_zjgzt"
];
List<String> menuTitle2 = ["团队管理", "团队成员"];
List<String> menuImage2 = ["icon_tdgl", "icon_tdmp"];

class _ToolsItem extends StatelessWidget {
  _ToolsItem(this.titles, this.imgs, this.onTap, {Key key}) : super(key: key);

  List<String> titles;
  List<String> imgs;
  Function onTap;

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      shrinkWrap: true,
      padding: const EdgeInsets.fromLTRB(8.0, 0, 8.0, 12.0),
      physics: NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4, childAspectRatio: 0.9, crossAxisSpacing: 2),
      itemCount: titles.length,
      itemBuilder: (_, index) {
        return InkWell(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                LoadAssetImage(
                  "work/${imgs[index]}",
                  width: 45.0,
                  height: 45,
                ),
                Gaps.vGap10,
                Text(
                  titles[index],
                  style: TextStyles.textSize13,
                )
              ],
            ),
            onTap: () {
              onTap(index);
            });
      },
    );
  }

}

class SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  final Widget widget;
  final double height;

  SliverAppBarDelegate(this.widget, this.height);

  // minHeight 和 maxHeight 的值设置为相同时，header就不会收缩了
  @override
  double get minExtent => height;

  @override
  double get maxExtent => height;

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return widget;
  }

  @override
  bool shouldRebuild(SliverAppBarDelegate oldDelegate) {
    return true;
  }
}

class _TabView extends StatelessWidget {
  const _TabView(this.index, this.text,{this.onTap});

  final int index;
  final String text;
  final Function onTap;

  @override
  Widget build(BuildContext context) {
    var imgList = [
//      "work/icon_bywc",

      "work/icon_byz",
      "work/icon_jx",
      "work/icon_nj",
      "work/icon_dxx",
    ];
    return Consumer<WorkPageProvider>(
        builder: (_, provider, child) {
          return InkWell(
            onTap: this.onTap,
            child:  Stack(
              children: <Widget>[
                Container(
                  width: 70.0,
                  padding: const EdgeInsets.symmetric(vertical: 8.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      LoadAssetImage(
                        imgList[index],
                        width: 27.0,
                        height: 27.0,
                      ),
                      Gaps.vGap4,
                      Text(text)
                    ],
                  ),
                ),
                child
              ],
            ),
          );
        },
        child: Positioned(
          right: 0.0,
          child: (index == 0&&countDoingItem.maintain>0)||(index == 1&&countDoingItem.repair>0)||(index == 2&&countDoingItem.inspection>0)||(index == 3&&countDoingItem.capital>0)
              ? DecoratedBox(
                  decoration: BoxDecoration(
                    color: Theme.of(context).errorColor,
                    borderRadius: BorderRadius.circular(11.0),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 5.5, vertical: 2.0),
                    child: Text(
                      "${index == 0?countDoingItem.maintain:index==1?countDoingItem.repair:index==2?countDoingItem.inspection:countDoingItem.capital}",
                      style: TextStyle(
                          color: Colors.white, fontSize: Dimens.font_sp12),
                    ),
                  ),
                )
              : Gaps.empty,
        ));
  }
}
