import 'package:cached_network_image/cached_network_image.dart';
import 'package:chat/data/chat_data_mgr.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/home/send_msg_state.dart';
import 'package:chat/models/UserInfo.dart';
import 'package:chat/models/last_message_model.dart';
import 'package:chat/models/last_msg_description.dart';
import 'package:chat/models/ref_name_provider.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:chat/utils/HttpUtil.dart';
import 'package:chat/utils/MessageMgr.dart';
import 'package:chat/utils/app_navigator.dart';
import 'package:chat/utils/msgHandler.dart';
import 'package:chat/utils/screen.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'last_unread_dot.dart';

class LastChatItem extends StatefulWidget {
  final LastMessageModel lastMessageModel;
  final int enterType; // 0默认  1图片
  final dynamic enterContent;
  LastChatItem(Key key, this.lastMessageModel,
      {this.enterType = 0, this.enterContent})
      : super(key: key);
  @override
  _LastChatItemState createState() => _LastChatItemState();
}

class _LastChatItemState extends State<LastChatItem> {
  LastMessageModel lastMessageModel;

  UserInfo userInfo;

  int retryCount=0;

  @override
  void initState() {
    super.initState();
    lastMessageModel = widget.lastMessageModel;

    initUserInfo();
    MessageMgr().on('UpdateUserInfo', msgUpdateUserInfo);
  }

  initUserInfo() async {
    print('## xxx ${widget.lastMessageModel.friendId}');
    userInfo = await HttpUtil().getFriendInfo(widget.lastMessageModel.friendId);
    setState(() {});
  }

  msgUpdateUserInfo(info) {
    if (info.userId == widget.lastMessageModel.friendId) {
      userInfo = info;
      setState(() {});
    }
  }

  @override
  void dispose() {
    super.dispose();
    MessageMgr().off('UpdateUserInfo', msgUpdateUserInfo);
  }

  @override
  Widget build(BuildContext context) {
    int unreadCount = ChatDataMgr()
        .unreadCountProvider
        .getUnreadCount(widget.lastMessageModel.sessionId);
    print('build lastchatimte 未读消息数$unreadCount');

    if (userInfo == null ) {
      print(('userinfo ==null'));


      return Container();
    }
    Widget avatar = ClipRRect(
            borderRadius: BorderRadius.all(Radius.circular(8.0)),
            child: CachedNetworkImage(
              imageUrl: userInfo.headimgurl,
              placeholder: CustomUI.buildImgLoding,
              width: Constants.ConversationAvatarSize,
              height: Constants.ConversationAvatarSize,
            ));

    List<Widget> _rightArea = [
      Align(
        alignment: Alignment.topCenter,
        child: Text(Constants.getShowTime(lastMessageModel.updateAt, context),
            textScaleFactor: 1.0, style: AppStyles.DescStyle),
      ),
      Expanded(
          child: Align(
        alignment: Alignment.bottomCenter,
        child: UnreadCountDot(
            sessionId: lastMessageModel.sessionId, unreadCount: unreadCount),
      ))
    ];

    return InkWell(
      child: Container(
        padding: const EdgeInsets.all(10.0),
        height: 68,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            color: Color(AppColors.ConversationItemBgColor),
            border: Border(bottom: Constants.GreyBorderSide)),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            avatar,
            Container(width: 10.0),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                      Provider.of<RefNameProvider>(context)
                          .getRefName(userInfo.userId, userInfo.nickName),
                      textScaleFactor: 1.0,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: 15,
                        color: Colors.black,
                      )),
                  Expanded(child: SizedBox()),
                  Row(
                    children: <Widget>[
                      SendMsgState(
                          sessionId: lastMessageModel.sessionId,
                          time: lastMessageModel.updateAt),
                      Container(
                          constraints:
                              BoxConstraints(maxWidth: Screen.width - 130),
                          child: LastMsgDescription(
                              Key("Item$lastMessageModel.sessionId"),
                              lastMessageModel))
                    ],
                  ),
                  SizedBox(height: 2)
                ],
              ),
            ),
            SizedBox(
              height: Constants.ConversationAvatarSize,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: _rightArea,
              ),
            )
          ],
        ),
      ),
      onTap: () {
        MsgHandler.updateActiveSesstion(lastMessageModel.sessionId);
        AppNavigator.pushChatPage(context, lastMessageModel.friendId,
            enterType: widget.enterType, enterContent: widget.enterContent);
      },
    );
  }
}
