import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../consts/color.dart';
import '../../model/message/MessageDetail.dart';
import '../../model/message/MessageType.dart';
import '../../services/message_service.dart';
import '../../utils/GetConfig.dart';
import '../../view/message/message_detail.dart';

class MessageListPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MessageListPageState();
  }
}

class _MessageListPageState extends State<MessageListPage> {
  List<Map<String, dynamic>> types = [];
  List<MessageDetail> initData = [];

  // 当前页码
  int pageIndex = 0;

  // 是否有下一页
  bool hasNext = false;

  // 分页所需控件
  // GlobalKey<EasyRefreshState> _easyRefreshKey =  GlobalKey<EasyRefreshState>();
  // GlobalKey<RefreshHeaderState> _headerKey =  GlobalKey<RefreshHeaderState>();
  // GlobalKey<RefreshFooterState> _footerKey =  GlobalKey<RefreshFooterState>();
  final EasyRefreshController _controllers = EasyRefreshController();
  bool isAnimating = false;
  MessageType condition;
  String theme = '';
  bool has = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: const Color.fromRGBO(242, 246, 249, 1),
        appBar: AppBar(
          title: const Text(
            '消息提醒',
            style:
                TextStyle(color: Color.fromRGBO(51, 51, 51, 1), fontSize: 18),
          ),
          centerTitle: true,
          elevation: 0.2,
          brightness: Brightness.light,
          backgroundColor: Colors.white,
          leading:  Container(
            child: GestureDetector(
              onTap: () => Navigator.pop(context, has),
              child: Icon(Icons.keyboard_arrow_left,
                  color: GetConfig.getColor(theme), size: 32),
            ),
          ),
        ),
        body: ModalProgressHUD(
          child: _getWidget(),
          inAsyncCall: isAnimating,
          opacity: 0.7,
          progressIndicator: CircularProgressIndicator(),
        ));
  }

  Widget _getWidget() {
    return buildInnerListHeaderDropdownMenu();
  }

  ScrollController scrollController =  ScrollController();
  GlobalKey globalKey2 =  GlobalKey();

  Widget buildInnerListHeaderDropdownMenu() {
    return  DefaultDropdownMenuController(
        onSelected: ({int menuIndex, int index, int subIndex, dynamic data}) {
          print(data);
          setState(() {
            pageIndex = 0;
            this.condition =
                MessageType.fromParams(data["title"], data["id"].toString());
            initData = [];
          });
          if (condition.id == "-1") {
            getData(null);
          } else {
            getData(condition);
          }
        },
        child:  Stack(
          children: <Widget>[
             CustomScrollView(
                controller: scrollController,
                slivers: <Widget>[
                   SliverList(
                      key: globalKey2,
                      delegate:  SliverChildBuilderDelegate(
                          (BuildContext context, int index) {
                        return  Container(
                          color: Colors.black26,
                        );
                      }, childCount: 1)),
                   SliverPersistentHeader(
                    delegate:  DropdownSliverChildBuilderDelegate(
                        builder: (BuildContext context) {
                      return  Container(
                          color: Colors.white,
                          child: buildDropdownHeader(onTap: this._onTapHead));
                    }),
                    pinned: true,
                    floating: true,
                  ),
                   SliverList(
                      delegate:  SliverChildBuilderDelegate(
                          (BuildContext context, int index) {
                  }, childCount: 10)),
                ]),
             Padding(
                padding:  const EdgeInsets.only(top: 46.0),
                child:  Stack(children: <Widget>[
                   Column(
                    children: <Widget>[
                       Expanded(
                          child:  Container(
                        child: GestureDetector(
                          child: Center(
                            child: EasyRefresh(
                              enableControlFinishRefresh: false,
                              enableControlFinishLoad: true,
                              controller: _controllers,
                              footer: MaterialFooter(),
                              header: MaterialHeader(),
                              child: ListView.builder(
                                //ListView的Item
                                itemCount: 1,
                                itemBuilder: (BuildContext context, int index) {
                                  return Column(
                                    children: initData.map((f) {
                                      return GestureDetector(
                                        child: Container(
                                          child: Card(
                                              elevation: 0.2,
                                              child: Column(
                                                children: <Widget>[
                                                  Container(
                                                    height: 30,
                                                    color: Colors.grey[100],
                                                    child: Row(
                                                      children: <Widget>[
                                                        getTitle(f.msgType)
                                                      ],
                                                    ),
                                                  ),
                                                  Container(
                                                    child: Row(
                                                      children: <Widget>[
                                                        Container(
                                                            width: MediaQuery.of(
                                                                        context)
                                                                    .size
                                                                    .width -
                                                                70,
                                                            child: Text(
                                                              f.body
                                                                  .replaceAll(
                                                                      r"<br />",
                                                                      "\r\n")
                                                                  .replaceAll(
                                                                      r"<br>",
                                                                      "\r\n"),
                                                              style: TextStyle(
                                                                  color: f.isRead
                                                                      ? Colors
                                                                          .grey
                                                                      : Colors
                                                                          .black),
                                                              maxLines: 10,
                                                              overflow:
                                                                  TextOverflow
                                                                      .ellipsis,
                                                            )),
                                                        Container(
                                                          width: 40,
                                                          child: Icon(
                                                            Icons
                                                                .keyboard_arrow_right,
                                                            color: GetConfig
                                                                .getColor(
                                                                    theme),
                                                          ),
                                                          alignment: Alignment
                                                              .centerRight,
                                                        )
                                                      ],
                                                    ),
                                                    padding: const EdgeInsets.only(
                                                        left: 10,
                                                        top: 10,
                                                        bottom: 10),
                                                  )
                                                ],
                                              )),
                                          margin: const EdgeInsets.only(
                                              left: 5, right: 5),
                                        ),
                                        onTap: () {
                                          Navigator.push(context,
                                               MaterialPageRoute(builder:
                                                  (BuildContext context) {
                                            return  MessageDetailPage(f);
                                          })).then((v) {
                                            setState(() {
                                              MessageDetail msg =
                                                  initData.singleWhere(
                                                      (f) => f.id == v);
                                              has = !msg.isRead;
                                              msg.isRead = true;
                                            });
                                          });
                                        },
                                      );
                                    }).toList(),
                                  );
                                },
                              ),
                              onRefresh: () async {
                                await  Future.delayed(
                                    const Duration(seconds: 1), () {
                                  setState(() {
                                    pageIndex = 0;
                                    initData = [];
                                  });
                                  _controllers.resetLoadState();
                                  getData(condition);
                                });
                              },
                              onLoad: () async {
                                await  Future.delayed(
                                    const Duration(seconds: 1), () {
                                  if (hasNext) {
                                    setState(() {
                                      pageIndex = pageIndex + 1;
                                    });
                                    getData(condition);
                                  }
                                });
                              },
                            ),
                          ),
                        ),
                      ))
                    ],
                  ),
                  buildDropdownMenu(),
                ])),
          ],
        ));
  }

  void _onTapHead(int index) {
    RenderObject renderObject = globalKey2.currentContext.findRenderObject();
    DropdownMenuController controller =
        DefaultDropdownMenuController.of(globalKey2.currentContext);

    scrollController
        .animateTo(scrollController.offset + renderObject.semanticBounds.height,
            duration:  const Duration(milliseconds: 150), curve: Curves.ease)
        .whenComplete(() {
      controller.show(index);
    });
  }

  String titleRoot = '全部消息';

  DropdownHeader buildDropdownHeader({DropdownMenuHeadTapCallback onTap}) {
    return  DropdownHeader(
      onTap: onTap,
      fontSize: 13,
      titles: [titleRoot],
    );
  }

  static const int TYPE_INDEX = 0;

  DropdownMenu buildDropdownMenu() {
    return  DropdownMenu(
        maxMenuHeight: kDropdownMenuItemHeight * 10,
        blur: 0.0,
        menus: [
           DropdownMenuBuilder(
              builder: (BuildContext context) {
                return  DropdownListMenu(
                  selectedIndex: TYPE_INDEX,
                  data: types,
                  itemBuilder:
                      (BuildContext context, dynamic data, bool selected) {
                    return  Padding(
                        padding:  EdgeInsets.all(10.0),
                        child:  Row(
                          children: <Widget>[
                             Text(
                              defaultGetItemLabel(data),
                              style: selected
                                  ?  TextStyle(
                                      fontSize: 14.0,
                                      color: GetConfig.getColor(theme),
                                      fontWeight: FontWeight.w400)
                                  :  TextStyle(fontSize: 14.0),
                            ),
                             Expanded(
                                child:  Align(
                              alignment: Alignment.centerRight,
                              child: selected
                                  ?  Icon(
                                      Icons.check,
                                      color: GetConfig.getColor(theme),
                                    )
                                  : null,
                            )),
                          ],
                        ));
                  },
                );
              },
              height: kDropdownMenuItemHeight * types.length),
        ]);
  }

  @override
  void initState() {
    super.initState();
    getMsgType();
    initConfig();
  }

  initConfig() async {
    SharedPreferences.getInstance().then((preferences) {
      setState(() {
        this.theme =
            preferences.getString("theme") ?? KColorConstant.DEFAULT_COLOR;
      });
    });
  }

  getMsgType() async {
    setState(() {
      isAnimating = true;
    });
    await getMessgaeType().then((data) {
      setState(() {
//        types.add(MessageType.fromParams("全部", "-1"));
//        data.keys.forEach((f){
//          MessageType d = MessageType.fromParams(data[f],f);
//          types.add(d);
//        });
        data.forEach((k, v) {
          Map<String, dynamic> _map = Map();
          _map["title"] = v;
          _map["id"] = k;
          types.add(_map);
        });
        Map<String, dynamic> _allMap = Map();
        _allMap["title"] = "全部";
        _allMap["id"] = -1;
        types.insert(0, _allMap);
      });
    }).then((data) {
      getData(null);
    });
  }

  getData(MessageType condition) async {
    setState(() {
      isAnimating = true;
    });
    await getMessageList(condition, pageIndex).then((data) {
      if (data != null && data.content != null && data.content.length > 0) {
        hasNext = !data.last;
        setState(() {
          for (var _data in data.content) {
            initData.add(MessageDetail.fromJson(_data));
          }
        });
      }
      _controllers.finishLoad(noMore: data.last);
      setState(() {
        isAnimating = false;
      });
    });
  }

  getTitle(String type) {
    var row;
    if (type == "check") {
      row = Row(
        children: <Widget>[
          Image.asset(
            "assets/images/message/check_" + theme + ".png",
            height: 20,
          ),
          Text("隐患排查")
        ],
      );
    } else if (type == "task") {
      row = Row(
        children: <Widget>[
          Image.asset(
            "assets/images/message/task_" + theme + ".png",
            height: 20,
          ),
          Text("隐患治理")
        ],
      );
    } else if (type == "planBegin") {
      row = Row(
        children: <Widget>[
          Image.asset(
            "assets/images/message/planBegin_" + theme + ".png",
            height: 20,
          ),
          Text("计划开始")
        ],
      );
    } else if (type == "planWarn") {
      row = Row(
        children: <Widget>[
          Image.asset(
            "assets/images/message/planWarn_" + theme + ".png",
            height: 20,
          ),
          Text("计划提醒")
        ],
      );
    } else if (type == "planEnd") {
      row = Row(
        children: <Widget>[
          Image.asset(
            "assets/images/message/planEnd_" + theme + ".png",
            height: 20,
          ),
          Text("漏检提醒")
        ],
      );
    } else if (type == "notify") {
      row = Row(
        children: <Widget>[
//          Image.asset("assert/images/message/漏检提醒.png"),
          Text("通知公告")
        ],
      );
    } else if (type == "latentDangerApp") {
      row = Row(
        children: <Widget>[
//          Image.asset("assert/images/message/漏检提醒.png"),
          Text("隐患治理")
        ],
      );
    }
    return row;
  }
}
