import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:gmalpha_flutter/messageModel/home/message_notification_item.dart';
import 'package:gmalpha_flutter/messageModel/model/message/message.dart';
// import 'package:gmalpha_flutter/model/message/message.dart' as prefix0;
import 'message_item.dart';
import 'package:gmalpha_flutter/commonModel/net/DioUtil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:gmalpha_flutter/commonModel/list_item.dart';


class MessageHomePage extends StatefulWidget {
  final Map params;
  MessageHomePage(this.params);
  @override
  _MessageHomePageState createState() => _MessageHomePageState(params);
}

class _MessageHomePageState extends State<MessageHomePage> {
  final Map nativeCookie; 
  _MessageHomePageState(this.nativeCookie);



  List<ListItem> messageList = List<ListItem>();
  List<ListItem>  dataArr = List<ListItem>();
  int pageIndex = 1;

  @override
  void initState() {
    if (nativeCookie.keys.length  > 0) {
      BaseOptions options = DioUtil.getDefOptions();
      Map cookie = this.nativeCookie;
      print('----22222222222222-----');
      Map<String, dynamic> newCookie = {'Cookie': cookie['Cookie']};
      options.baseUrl = cookie['host'] + '/';
      print('----33333333333----');
      HttpConfig config = new HttpConfig(options: options, nativeCookie:newCookie);
      DioUtil().setConfig(config);
    }
    super.initState();
  }

  RefreshController _refreshController =
      RefreshController(initialRefresh: true);

  void _onRefresh() async{
    pageIndex = 1;
   List<ListItem> newdataArr = List<ListItem>();
   newdataArr = await  _fetchListData();
   if (mounted) setState(() {
     dataArr = newdataArr;
   });
   _refreshController.refreshCompleted();
  }

  void _onLoading() async{
    pageIndex ++;
    List<ListItem>  newData = List<ListItem>();
    newData = await _fetchMesssageList();
    if (mounted) setState(() {
      this.dataArr.addAll(newData);
    });
    _refreshController.loadComplete();
  }

  Future<List<ListItem>> _fetchMesssageList() async {
//    List<Message> messageList = List<Message>();
//    BaseResp<List> baseresp = await DioUtil().request<List>(Method.get, "api/v1/reply/my", queryParameters: {'page': pageIndex, 'count': 10});
//    if (baseresp.code != 0) {
//      return new Future.error(baseresp.msg);
//    }
//
//    if (baseresp.data != null) {
//      messageList = baseresp.data.map((value) {
//        return Message.fromJson(value);
//      }).toList();
//    }
     _refreshController.refreshCompleted();
    return messageList;
  }

   Future<List<ListItem>>  _fetchNewestInfo() async {
    List<ListItem>  notiData = List<ListItem>();
//    BaseRespR noteResp =  await DioUtil().requestR(Method.get, 'api/v1/push/newest/info');
//    Map noteData = noteResp.data;
//    String noteContent = noteData['content'];
//    NotificationItem noteItem = NotificationItem('images/message_noti.png', noteContent, 0, '通知');
//    notiData.add(noteItem);
//
//    BaseRespR likeResp = await DioUtil().requestR(Method.get, 'api/v1/message/unread',queryParameters: {'type': 0});
//    print(likeResp);
//    Map likeData = likeResp.data;
//    String likeContent = '';
//    NotificationItem likeItem = NotificationItem('images/message_like.png', likeContent, likeData['count'], 'Like');
//    if (likeItem.count > 0) {
//      likeItem.content = '有${likeItem.count}个人Like了你';
//    } else {
//      likeItem.content = '还没有人给你Like哦~';
//    }
//    notiData.add(likeItem);

//    BaseRespR attentionResp = await DioUtil().requestR(Method.get, 'api/v1/message/unread',queryParameters: {'type': 1});
//    Map attData = attentionResp.data;
//    String attContent = '';
//    NotificationItem attItem = NotificationItem('images/message_att.png', attContent, attData['count'], '关注');
//    if (attItem.count > 0) {
//      attItem.content = '有${attItem.count}个人关注了你';
//    } else {
//      attContent = '还没有人给你关注哦~';
//    }
//    notiData.add(attItem);
    // this.dataArr = dataArr;
    return notiData;
  }

   Future<List<ListItem>> _fetchListData() async {
     List<ListItem>  dataArr = List<ListItem>();
     dataArr = await _fetchNewestInfo();
     List<ListItem> messageData = await _fetchMesssageList();
     messageData.forEach((item) {
       dataArr.add(item);
     });
    return dataArr;
   }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: new Text('消息'),
      ),
      body: new Container(
        child: SmartRefresher(
          child: _createListView(),
          controller: _refreshController,
          enablePullDown:  true,
          enablePullUp: true,
          header: WaterDropHeader(),
          onRefresh: (){
            _onRefresh();
          },
          onLoading: () {
            _onLoading();
          }
      ),
      )
    );
  }
  

  Widget _createListView() {
    List<ListItem> dataArr = this.dataArr;
    return ListView.builder(
      shrinkWrap: true,
      key: new PageStorageKey('message-list'),
      itemCount: dataArr.length,
      itemBuilder: (context,index) {
        ListItem  item = dataArr[index];
        if (item is Message) {
          return new MessageItem(onPressed: (){}, message:item);
        } else if (item is NotificationItem){
          return new MessageNotificationItem(onPressed: (){}, notification: item);
        } else {
          return Text('类型错误');
        }
      },
    );
  }
}
