import 'package:flutter/material.dart';
import 'package:liftmanager/internal/heavy/provider/heavy_page.dart';
import 'package:liftmanager/internal/message/model/message_list_entity.dart';
import 'package:liftmanager/internal/message/widgets/messageList.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/fast_notification.dart';
import 'package:liftmanager/utils/theme_utils.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/widgets/load_image.dart';
import 'package:liftmanager/widgets/popup_window.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart' as p;

class MessageListPage extends StatefulWidget {
  @override
  MessageListPageState createState() => MessageListPageState();
}

class MessageListPageState extends State<MessageListPage>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  HeavyPageProvider provider = HeavyPageProvider();
  List<Map> tabs = [
    {"id": 1, "name": "团队消息"},
    {"id": 2, "name": "保养消息"},
    {"id": 3, "name": "急修消息"},
    {"id": 4, "name": "工作消息"}
  ];
  TabController _tabController;
  PageController _pageController = PageController(initialPage: 0);
  GlobalKey _addKey = GlobalKey();
  GlobalKey _msgListKey = GlobalKey();
  List msgIdList = [];
  @override
  void initState() {
    super.initState();
    _tabController = new TabController(vsync: this, length: tabs.length);
    // FastNotification.addListener("msgListChage", (mgsList) {
    //   if (mounted) {
    //     msgIdList = [];
    //     for (MessageListItem item in mgsList) {
    //       msgIdList.add(item.id);
    //     }
    //   }
    //   // setState(() {});
    // });
  }

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

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

  _showAddMenu() {
    final RenderBox button = _addKey.currentContext.findRenderObject();
    final RenderBox overlay = Overlay.of(context).context.findRenderObject();
    var a = button.localToGlobal(
        Offset(button.size.width - 8.0, button.size.height - 12.0),
        ancestor: overlay);
    var b = button.localToGlobal(button.size.bottomLeft(Offset(0, -12.0)),
        ancestor: overlay);
    final RelativeRect position = RelativeRect.fromRect(
      Rect.fromPoints(a, b),
      Offset.zero & overlay.size,
    );
    final Color backgroundColor = ThemeUtils.getBackgroundColor(context);
    final Color _iconColor = ThemeUtils.getIconColor(context);
    showPopupWindow(
      context: context,
      fullWidth: false,
      isShowBg: true,
      position: position,
      elevation: 0.0,
      child: GestureDetector(
        onTap: () => NavigatorUtils.goBack(context),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(right: 12.0),
              child: LoadAssetImage(
                "icon_jt",
                width: 8.0,
                height: 4.0,
              ),
            ),
            SizedBox(
              width: 120.0,
              height: 40.0,
              child: FlatButton.icon(
                  textColor: Theme.of(context).textTheme.body1.color,
                  onPressed: () {
                    changeNoticeState(msgIdList);
                    Navigator.pop(context);
                    // NavigatorUtils.pushResult(
                    //     context, '${TeamRouter.teamCreatePage}', (res) {
                    //   _onRefresh();
                    // });
                  },
                  color: backgroundColor,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(8.0),
                        topRight: Radius.circular(8.0)),
                  ),
                  icon: Icon(
                    const IconData(0xe62f, fontFamily: "Iconfont"),
                    size: 16.0,
                    color: _iconColor,
                  ),
                  // icon: LoadAssetImage(
                  //   "wode/icon_team_add",
                  //   width: 16.0,
                  //   height: 16.0,
                  //   color: _iconColor,
                  // ),
                  label: const Text("一键已读")),
            ),
            Container(width: 120.0, height: 0.6, color: Colours.line),
            SizedBox(
              width: 120.0,
              height: 40.0,
              child: FlatButton.icon(
                  textColor: Theme.of(context).textTheme.body1.color,
                  color: backgroundColor,
                  onPressed: () {
                    clearData(provider.index + 1);
                    Navigator.pop(context);
                    // NavigatorUtils.push(
                    //     context, '${TeamRouter.teamSearchPage}');
                  },
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.only(
                        bottomLeft: Radius.circular(8.0),
                        bottomRight: Radius.circular(8.0)),
                  ),
                  icon: Icon(
                    const IconData(0xe715, fontFamily: "Iconfont"),
                    size: 16.0,
                    color: _iconColor,
                  ),

                  // LoadAssetImage(
                  //   "wode/icon_team_add",
                  //   width: 16.0,
                  //   height: 16.0,
                  //   color: _iconColor,
                  // ),
                  label: const Text("一键清空")),
            ),
          ],
        ),
      ),
    );
  }

  Future changeNoticeState(idList) async {
    print(idList);
    //  showLoading(context, "正在提交...");
    await NewApiService().markMessagesRead(idList, onSuccess: (res) {
      // dismissLoading(context);
      // String initThisNotice = randomInt(1111, 9999).toString() +
      //     DateTime.now().millisecondsSinceEpoch.toString();
      // FastNotification.push("initNotice", initThisNotice);
      // _onRefresh();

      showToast('标记已读成功');
      FastNotification.push('msgList');

      // setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  Future clearData(type, {List ids}) async {
    await NewApiService().deleteAllMessage(type, ids: ids, onSuccess: (res) {
      // String initThisNotice = randomInt(1111, 9999).toString() +
      //     DateTime.now().millisecondsSinceEpoch.toString();
      // FastNotification.push("initNotice", initThisNotice);
      // _onRefresh();
      FastNotification.push('msgList');
      // FastNotification.push('msgListChage');
      // setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  @override
  Widget build(BuildContext context) {
    return p.ChangeNotifierProvider<HeavyPageProvider>(
        create: (_) => provider,
        child: WillPopScope(
          onWillPop: () {
            NavigatorUtils.goBackWithParams(context, true);
            return Future.value(false);
          },
          child: Scaffold(
            appBar: MyAppBar(
              centerTitle: "消息中心",
              actions: [
                // PopupMenuButton<String>(
                //     itemBuilder: (BuildContext context) =>
                //         <PopupMenuItem<String>>[
                //           PopupMenuItem<String>(
                //               value: '一键已读',
                //               child: Row(children: <Widget>[
                //                 Padding(
                //                     padding:
                //                         EdgeInsets.fromLTRB(0.0, 0.0, 8.0, 0.0),
                //                     child: Icon(IconData( 0xe62f,
                //                           fontFamily: "Iconfont"))

                //                     ),
                //                 Text('一键已读')
                //               ])),
                //           PopupMenuItem<String>(
                //               value: '一键清空',
                //               child: Row(children: <Widget>[
                //                 Padding(
                //                     padding:
                //                         EdgeInsets.fromLTRB(0.0, 0.0, 8.0, 0.0),
                //                     child: Icon(IconData( 0xe715,
                //                           fontFamily: "Iconfont"))),
                //                 Text('一键清空')
                //               ])),
                //         ],
                //     onSelected: (String value) {
                //       // setState(() { _bodyStr = value; });
                //     })
                InkWell(
                  key: _addKey,
                  onTap: () {
                    _showAddMenu();
                    // JhPopMenus.showLinePop(context,
                    //     clickCallback: (selectIndex, selectText) {});
                    // print('object');
                  },
                  child: Icon(Icons.more_horiz),
                ),
                SizedBox(
                  width: 5,
                )
              ],
            ),
            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: 5.0, right: 5.0),
                      tabs: tabs.map((map) {
                        return _TabView("${map["name"]}", "", 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: Color(0xffF6F6F6),
                          // Color(0xffF6F6F6),
                          // ThemeUtils.getBackgroundColor(context),
                          child: MessageList(
                            index: index + 1,
                            returnMsgList: (msgList) {
                              msgIdList = [];
                              for (MessageListItem item in msgList) {
                                msgIdList.add(item.id);
                              }
                            },
                          ));
                    },
                  ),
                )
              ],
            ),
          ),
        ));
  }

  @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<HeavyPageProvider>(
      builder: (_, provider, child) {
        return Tab(
            child: SizedBox(
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                tabName,
                style: TextStyle(fontSize: 15),
              ),
              Offstage(
                  offstage: provider.index != index,
                  child: Padding(
                    padding: const EdgeInsets.only(top: 1.0),
                    child: Text(tabSub,
                        style: TextStyle(fontSize: Dimens.font_sp12)),
                  )),
            ],
          ),
        ));
      },
    );
  }
}
