import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import '../styles/colors.dart';
import 'dart:ui';
import '../styles/totast.dart';
import 'package:flutter_redux/flutter_redux.dart';
import '../redux/AppState.dart';
import '../model/SystemNotice.dart';
import '../net/HttpManager.dart';
import '../net/Result.dart';
import 'TipInfo.dart';

class TipList extends StatefulWidget {
  @override
  TipListState createState() => TipListState();
}

class TipListState extends State<TipList> {
  int currentPage = 1;
  List<SystemNotice> tipList = [];
  bool isMore = false;
  ScrollController _mControll;

  void getListPage() async {
    isMore = false;
    if (currentPage != 1) {
      Toast.show(context, '加载中', -1, 'loading');
    }
    Result res = await HttpManager.get("systemNotice/page",
        data: {"userId": StoreProvider.of<AppState>(context).state.userInfo.id, "currentPage": currentPage, "pageNumber": 20});
    Toast.hide();
    List<SystemNotice> list = tipList;
    if (currentPage == 1) {
      list = [];
    }
    if (res.success) {
      for (var item in res.data['pp']) {
        SystemNotice tip = SystemNotice.fromJson(item);
        list.add(tip);
      }
      if (res.data['page']['currentPage'] < res.data['page']['totalPage']) {
        isMore = true;
      }
    } else {}
    setState(() {
      tipList = list;
    });
  }

  @override
  void initState() {
    super.initState();
    _mControll = new ScrollController();
    Future.delayed(Duration.zero, () => getListPage());
    _mControll.addListener(() {
      if (_mControll.position.pixels == _mControll.position.maxScrollExtent) {
        if (isMore) {
          currentPage++;
          getListPage();
        }
      }
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return new WillPopScope(
        child: Scaffold(
            appBar: AppBar(
              backgroundColor: PRIMARY_COLOR,
              title: Text('通知列表'),
              centerTitle: true,
              elevation: 0,
            ),
            body: RefreshIndicator(
              color: PRIMARY_COLOR,
              backgroundColor: Colors.white,
              onRefresh: () async {
                currentPage = 1;
                getListPage();
              },
              child: Container(
                color: BG_COLOR,
                child: ListView.builder(
                    physics: AlwaysScrollableScrollPhysics(),
                    controller: _mControll,
                    itemCount: tipList.length != 0 ? tipList.length : 1,
                    itemBuilder: (BuildContext context, int index) {
                      if (tipList.length == 0) {
                        return Text(
                          '数据正在火速加载中...',
                          style: TextStyle(color: Colors.white30, fontSize: 13, height: 2),
                          textAlign: TextAlign.center,
                        );
                      }
                      return TipItem(
                          tipInfo: tipList[index],
                          tapInfo: () async {
                            bool res = await Navigator.push(context, new CupertinoPageRoute(builder: (context) => new TipInfo(tipId: tipList[index].id)));
                            if (res != null) {
                              setState(() {
                                tipList = [];
                              });
                              currentPage = 1;
                              getListPage();
                            }
                          });
                    }),
              ),
            )),
        onWillPop: () {
          Toast.hide();
          Navigator.of(context).pop(true);
          return Future.value(false);
        });
  }
}

typedef OnTapHomeMenu();

class TipItem extends StatelessWidget {
  TipItem({Key key, this.tipInfo, this.tapInfo}) : super(key: key);
  final SystemNotice tipInfo; // 用来储存传递过来的值
  final OnTapHomeMenu tapInfo;
  @override
  Widget build(BuildContext context) {
    return Container(
      // height: 108,
      margin: EdgeInsets.only(top: 10),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Color(0xFF464B6A), Color(0xFF35395E)],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
        ),
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 15),
            child: Column(
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.symmetric(vertical: 12),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text(readTimestamp(tipInfo.createTime, 'yyyy.MM.dd HH:mm:ss'), style: TextStyle(color: Color(0xFF9BA0AE), fontSize: 13)),
                      tipInfo.statusFlag == 0
                          ? Text('未读', style: TextStyle(color: Color(0xFFC2524D), fontSize: 13, fontWeight: FontWeight.w600))
                          : Text('已读', style: TextStyle(color: Color(0xFF000000), fontSize: 13, fontWeight: FontWeight.w600))
                    ],
                  ),
                ),
                Container(
                  height: 1,
                  color: Colors.black26,
                ),
                Padding(
                  padding: EdgeInsets.only(top: 10, bottom: 15),
                  child: Text(tipInfo.content, style: TextStyle(color: Colors.white, fontSize: 14)),
                )
              ],
            ),
          ),
          onTap: tapInfo,
        ),
      ),
    );
  }
}
