
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:provider/provider.dart';
import 'package:twongCustomer/store/models/serverModel.dart';

import '../models/index.dart';
import '../routes/utils.dart';
import '../utils/events.dart';
import '../utils/socket.dart';
import '../pages/setting.dart';
import '../utils/size_fit.dart';
import '../utils/notification.dart';

class UserListPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _UserListPageState();
  }
}

class _UserListPageState extends State<UserListPage> {
  int unread = 99;
  bool disposed = false;
  List<UserInfo> userList = new List<UserInfo>();
  Map<String, int> unreadMap = new Map<String, int>();
  Map<String, String> msgMap = new Map<String, String>();

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

    disposed = false;
    initNetwork();
    initEventListener();
  }

  @override
  void dispose() {
    super.dispose();
    disposed = true;
    print("user list dispose");
  }

  void initNetwork() {
    // String server = Provider.of<ServerModel>(context,listen: false).wsServer;
    // print(server);
    Socket.connect();
  }

  void initEventListener() {
    Events.on<UserOnline>().listen((event) {
      if (!mounted) return;
      setState(() {
        userList.add(event.user);
      });
    });

    Events.on<UserList>().listen((event) {
      if (!mounted) return;
      setState(() {
        userList = event.users;
      });
    });

    Events.on<ClearUnread>().listen((event) {
      if (!mounted) return;
      setState(() {
        if (unreadMap.containsKey(event.uid)) {
          unreadMap[event.uid] = 0;
        }
      });
    });

    Events.on<NotifyMessage>().listen((event) {
      if (!mounted) return;
      var user = userList.singleWhere((element) => element.uid == event.payload, orElse: () => null);
      if (user != null) _itemClick(user);
    });

    Events.on<UserMessage>().listen((event) {
      print(event.message.toJson());
      Notifications.showNotify(event.message.visitor_name, event.message.content, payload: event.message.id);
      if (!mounted) return;
      setState(() {
        if(unreadMap[event.message.id] == null) {
          unreadMap[event.message.id] = 1;
        } else {
          unreadMap[event.message.id] ++;
        }

        msgMap[event.message.id] = event.message.content;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("美天旺客服"),
        automaticallyImplyLeading: false,
        actions: [
          IconButton(icon: Icon(Icons.settings), onPressed: (){
            Navigator.push(context,
                new MaterialPageRoute(builder: (context) => new SettingPage()));
          })
        ],
      ),
      body: userList.length > 0 ? _buildList() : _buildNoData(),
    );
  }

  Widget _buildNoData() {
    return Center(
      child: Text("暂时没有消息"),
    );
  }

  Widget _buildUser(BuildContext context, int index) {
    var user = userList[index];
    var unreadWidget = Container();
    if (int.parse(getMsgCount(user.uid)) > 0) {
      unreadWidget = Container(
        width: 20,
        height: 20,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: Colors.red,
          borderRadius: BorderRadius.all(Radius.circular(25.0)),
        ),
        child: Text(
          getMsgCount(user.uid), style: TextStyle(color: Colors.white),),
      );
    }
    return InkWell(
      onTap: () => _itemClick(user),
      child: Container(
        margin: EdgeInsets.all(10),
        child: Row(
          children: [
            ClipRRect(borderRadius: BorderRadius.circular(20),child: Image.network(user.avator,width: 40,height: 40)),
            Container(
              margin: EdgeInsets.all(10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Container(
                        height: 20,
                        // width: 550.rpx,
                        child: Text(user.username, style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                      ),
                      // Text("9:12", style: TextStyle(fontSize: 14, color: Colors.grey)),
                    ],
                  ),
                  Row(
                    children: [
                      Container(
                        height: 20,
                        width: 550.rpx,
                        margin: EdgeInsets.only(top: 4),
                        child: Text(getMsgContent(user.uid), style: TextStyle(fontSize: 14, color: Colors.grey)),
                      ),
                      unreadWidget
                    ],
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _buildList() {
    return SafeArea(child: ListView.builder(
        physics: new NeverScrollableScrollPhysics(),
        itemBuilder: _buildUser,
        itemCount: userList.length));
  }

  String getMsgCount(String uid) {
    var count = unreadMap[uid];
    if (count == null) return "0";
    else return count.toString();
  }

  String getMsgContent(String id) {
    if(msgMap[id] == null) return "暂无消息";
    return msgMap[id];
  }

  void _itemClick (UserInfo user) {
    RouterUtils.toChat(context, user);
  }
}