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;

  Future<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 = 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 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.isNotEmpty ? tipList.length+1: 1,
                    itemBuilder: (BuildContext context, int index) {
                      if (tipList.isEmpty) {
                        return Text(
                          '数据正在火速加载中...',
                          style: TextStyle(color: Colors.white30, fontSize: 13, height: 2),
                          textAlign: TextAlign.center,
                        );
                      }
                      if(index==tipList.length){
                        return Container(
                          height: 30,
                        );
                      }
                      return TipItem(
                          tipInfo: tipList[index],
                          tapInfo: () async {
                            bool res = await Navigator.push(context, CupertinoPageRoute(builder: (context) => 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 = Function();

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,
      //   ),
      // ),
      color: Color(0xFF363759),
      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: Theme.of(context).primaryColor, fontSize: 13, fontWeight: FontWeight.w600))
                          : Text('已读', style: TextStyle(color: Color(0xFF000000), fontSize: 13, fontWeight: FontWeight.w600))
                    ],
                  ),
                ),
                Container(
                  height: 1,
                  color: Colors.black26,
                ),
                // _tipContent(tipInfo.content),
                Container(
                  padding: EdgeInsets.only(top: 10, bottom: 15),
                  width: double.infinity,
                  child:Text.rich( TextSpan(
                    style: TextStyle(color: Colors.white, fontSize: 14),
                    children:_tipContent(tipInfo.content,context)
                  )
                  // DefaultTextStyle(
                  //   //1.设置文本默认样式
                  //   style: TextStyle(color: Colors.white, fontSize: 14),
                  //   textAlign: TextAlign.start,
                  //   child: Row(
                  //     crossAxisAlignment: CrossAxisAlignment.start,
                  //     children:_tipContent(tipInfo.content),
                  //   ),
                  // ),
                  
                ))
              ],
            ),
          ),
          onTap: tapInfo,
        ),
      ),
    );
  }

  List<TextSpan> _tipContent(content,context) {
    // content = '很遗憾';
    List<String> contentlist1 = content.split('[');
    List<Map> totalContent = [];
    contentlist1.forEach((item) {
      List _list = item.split(']');
      if (_list.length > 1) {
        totalContent.add({
          "content": _list[0],
          "isImport": true,
        });
        totalContent.add({
          "content": _list[1],
          "isImport": false,
        });
      } else {
        totalContent.add({
          "content": _list[0],
          "isImport": false,
        });
      }
    });

  

    List<TextSpan> _widgetList=[];
    totalContent.forEach((item){
      if(item['isImport']){
        _widgetList.add(TextSpan(text:' '+item['content']+' ',style:TextStyle(
          color: Color(0xFFFFB726),
          fontWeight:FontWeight.w600
        )));
      }
      else{
        _widgetList.add(TextSpan(text:item['content']));
      }
    });

    return _widgetList;
  }
}
