import 'dart:async';
import 'dart:math';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:liftmanager/internal/means/means_router.dart';
import 'package:liftmanager/internal/search/presenter/base_list_provider.dart';
import 'package:liftmanager/internal/wode/model/message_model.dart';
import 'package:liftmanager/internal/wode/presenter/notice_list_presenter.dart';
import 'package:liftmanager/mvp/base_page_state.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/res/iconfont.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/my_refresh_list.dart';
import 'package:liftmanager/widgets/popup_window.dart';
import 'package:provider/provider.dart';

class NoticeList extends StatefulWidget {
  @override
  NoticeListState createState() => NoticeListState();
}

class NoticeListState extends BasePageState<NoticeList, NoticeListPresenter> {
  BaseListProvider<Records> provider = BaseListProvider<Records>();

  int _page = 1;
  GlobalKey _addKey = GlobalKey();
  List<String> idList;

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

  Future changeNoticeState(List<String> ids) async {
    await NewApiService().markMessagesRead(ids, onSuccess: (res) {
      String initThisNotice = randomInt(1111, 9999).toString() +
          DateTime.now().millisecondsSinceEpoch.toString();
      FastNotification.push("initNotice", initThisNotice);
      showToast('标记已读成功');
      _onRefresh();
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  Future removeNotificationMessages(List<String> ids) async {
    await NewApiService().removeAllMessage(ids, 4, onSuccess: (res) {
      showToast('删除成功');
      _onRefresh();
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  randomInt(int min, int max) {
    return new Random().nextInt(max) % (max - min + 1) + min;
  }

  @override
  void initState() {
    super.initState();
    _onRefresh();
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;

    return ChangeNotifierProvider<BaseListProvider<Records>>(
        create: (_) => provider,
        child: Scaffold(
          // resizeToAvoidBottomPadding: true,
          appBar: MyAppBar(
            centerTitle: "通知消息",
            actions: [
              IconButton(
                  key: _addKey,
                  icon: Icon(Iconfont.gengduo22),
                  onPressed: () {
                    _showAddMenu(context);
                  })
            ],
          ),
          body: Container(
            color: Color(0xffF6F6F6),
            padding: EdgeInsets.all(10),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Expanded(
                    flex: 1,
                    child: Consumer<BaseListProvider<Records>>(
                        builder: (_, provider, __) {
                      idList = provider.list.map((e) => e.id).toList();

                      return MyListView(
                        key: Key('notice_list'),
                        itemCount: provider.list.length,
                        stateType: provider.stateType,
                        onRefresh: _onRefresh,
                        loadMore: _loadMore,
                        pageSize: 15,
                        hasMore: provider.hasMore,
                        itemBuilder: (_, index) {
                          return Container(
                            margin: EdgeInsets.only(bottom: 10),
                            child: Slidable(
                                key: UniqueKey(),
                                actionPane: SlidableDrawerActionPane(),
                                actionExtentRatio: 0.2,
                                secondaryActions: <Widget>[
                                  Container(
                                    color: Color(0xffF94F45),
                                    alignment: Alignment.center,
                                    child: GestureDetector(
                                      onTap: () {
                                        removeNotificationMessages(
                                            [provider.list[index].id]);
                                      },
                                      child: Text(
                                        '删除',
                                        style: TextStyle(
                                            fontSize: 14, color: Colors.white),
                                      ),
                                    ),
                                  )
                                ],
                                child: InkWell(
                                  child: Container(
                                    padding: EdgeInsets.symmetric(
                                        horizontal: 10, vertical: 15),
                                    decoration: BoxDecoration(
                                      color: Colors.white,
                                      border: Border(
                                        bottom: BorderSide(
                                            width: 0.5, color: Colours.line),
                                      ),
                                    ),
                                    child: Row(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: <Widget>[
                                          if (provider.list[index].viewFlag ==
                                              0)
                                            Container(
                                              margin: EdgeInsets.only(top: 5),
                                              child: ClipRRect(
                                                  borderRadius:
                                                      BorderRadius.circular(3),
                                                  child: Container(
                                                      width: 6,
                                                      height: 6,
                                                      color: Colors.red)),
                                            ),
                                          SizedBox(width: 10),
                                          Expanded(
                                              child: Column(children: <Widget>[
                                            Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment
                                                      .spaceBetween,
                                              children: <Widget>[
                                                Text(
                                                  "通知消息",
                                                  textAlign: TextAlign.left,
                                                  style: TextStyle(
                                                    fontSize: 14,
                                                    color: Color(0xff333333),
                                                  ),
                                                ),
                                                Text(
                                                  provider.list[index]
                                                          .createTime ??
                                                      "",
                                                  textAlign: TextAlign.left,
                                                  style: TextStyle(
                                                    fontSize: 12,
                                                    color: Color(0xffCCCCCC),
                                                  ),
                                                ),
                                              ],
                                            ),
                                            SizedBox(
                                              height: 5,
                                            ),
                                            Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment
                                                      .spaceBetween,
                                              children: <Widget>[
                                                Container(
                                                  width: width * 0.7,
                                                  child: Text(
                                                    provider.list[index]
                                                            .content ??
                                                        "",
                                                    textAlign: TextAlign.left,
                                                    style: TextStyle(
                                                      fontSize: 13,
                                                      color: Color(0xff999999),
                                                    ),
                                                    overflow:
                                                        TextOverflow.ellipsis,
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ])),
                                        ]),
                                  ),
                                  onTap: () {
                                    changeNoticeState([provider.list[index].id]);
                                  },
                                )),
                          );
                        },
                      );
                    }))
              ],
            ),
          ),
        ));
  }

  Future _onRefresh() async {
    _page = 1;
    await presenter.getWalletList(_page);
  }

  Future _loadMore() async {
    _page++;
    await presenter.getWalletList(_page);
  }

  @override
  NoticeListPresenter createPresenter() {
    return NoticeListPresenter();
  }

  _showAddMenu(BuildContext context) {
    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);
    showPopupWindow(
      context: context,
      fullWidth: false,
      isShowBg: true,
      position: position,
      elevation: 2,
      child: GestureDetector(
        onTap: () => NavigatorUtils.goBack(context),
        child: Container(
          width: 120,
          decoration: BoxDecoration(borderRadius: BorderRadius.circular(10)),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              // Container(
              //   height: 10,
              //   width: 10,
              //   margin: EdgeInsets.only(bottom: 5),
              //   child: Transform.rotate(
              //     angle: -45 * pi / 180,
              //     child: CustomPaint(
              //       painter: _ShapesPainter(Color(0xffE4ECFF)),
              //       size: Size(10, 10),
              //     ),
              //   ),
              // ),
              SizedBox(
                // width: 120.0,
                height: 40.0,
                child: FlatButton.icon(
                    textColor: Color(0xff333333),
                    onPressed: () {
                      Navigator.pop(context);
                      if (idList != null) {
                        changeNoticeState(idList);
                      }
                    },
                    color: backgroundColor,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(8.0),
                          topRight: Radius.circular(8.0)),
                    ),
                    icon: Icon(Iconfont.yidu),
                    label: const Text("一键已读")),
              ),
              Divider(),
              SizedBox(
                // width: 120.0,
                height: 40.0,
                child: FlatButton.icon(
                    textColor: Color(0xff333333),
                    color: backgroundColor,
                    onPressed: () {
                      Navigator.pop(context);
                      if (idList != null) {
                        removeNotificationMessages(idList);
                      }
                    },
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.only(
                          bottomLeft: Radius.circular(8.0),
                          bottomRight: Radius.circular(8.0)),
                    ),
                    icon: Icon(Iconfont.yijianqingkong),
                    label: const Text("一键清空")),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _ShapesPainter extends CustomPainter {
  final Color color;

  _ShapesPainter(this.color);

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint();
    paint.color = color;
    var path = Path();
    path.lineTo(size.width, 0);
    path.lineTo(size.height, size.width);
    path.close();
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}

class NoticeWidget extends StatelessWidget {
  NoticeWidget({Key key, this.list}) : super(key: key);
  List<dynamic> list;

  List<Widget> listWidget(context) => list.map((i) {
        return InkWell(
          child: Container(
            padding: EdgeInsets.only(
                left: ScreenUtil().setWidth(15),
                right: ScreenUtil().setWidth(15),
                top: ScreenUtil().setWidth(10),
                bottom: ScreenUtil().setWidth(10)),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(width: 0.5, color: Colours.line),
              ),
            ),
            child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.only(right: ScreenUtil().setWidth(10)),
                    child: ClipRRect(
                      borderRadius:
                          BorderRadius.circular(ScreenUtil().setWidth(18)),
                      child: Container(
                        width: ScreenUtil().setWidth(36),
                        height: ScreenUtil().setWidth(36),
                        decoration: BoxDecoration(
                          gradient: const LinearGradient(
                              colors: [Color(0xFF00D9FF), Color(0xFF0287FF)]),
                        ),
                        // padding: EdgeInsets.only(right:10),
                        child: Icon(
                          IconData(i.type == "system" ? 0xe609 : 0xe62f,
                              fontFamily: "Iconfont"),
                          size: 24.0,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ),
                  Expanded(
                      child: Column(children: <Widget>[
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text(
                          i.type != null ? "系统消息" : "客服消息",
                          textAlign: TextAlign.left,
                          style: TextStyle(
                            fontSize: ScreenUtil().setSp(16),
                            color: Color(0xff000000),
                          ),
                        ),
                        Text(
                          i.createTime,
                          textAlign: TextAlign.left,
                          style: TextStyle(
                            fontSize: ScreenUtil().setSp(14),
                            color: Color(0xff999999),
                          ),
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text(
                          i.content,
                          textAlign: TextAlign.left,
                          style: TextStyle(
                            fontSize: ScreenUtil().setSp(13),
                            color: Color(0xff999999),
                          ),
                        ),
                        i.viewFlag != 0
                            ? ClipRRect(
                                borderRadius: BorderRadius.circular(3),
                                child: Container(
                                    child: null,
                                    width: 6,
                                    height: 6,
                                    color: Colors.red))
                            : Container(child: null)
                      ],
                    ),
                  ])),
                ]),
          ),
          onTap: () {
            print(i);
            NavigatorUtils.push(context, MeansRouter.errorDetail);
          },
        );
      }).toList();

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Column(children: listWidget(context)),
    );
  }
}
