import 'dart:convert';

import 'package:chat/data/UserData.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/data/group_data_mgr.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/models/last_message_model.dart';
import 'package:chat/models/ref_name_provider.dart';
import 'package:chat/proto/chat.pb.dart';
import 'package:chat/proto/transhousekeeper.pb.dart';
import 'package:chat/utils/HttpUtil.dart';
import 'package:chat/utils/MessageMgr.dart';
import 'package:chat/utils/msgHandler.dart';
import 'package:chat/utils/screen.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class LastMsgDescription extends StatefulWidget {
  final LastMessageModel lastMessageModel;
  LastMsgDescription(Key key, this.lastMessageModel) : super(key: key);
  @override
  _LastMsgDescriptionState createState() => _LastMsgDescriptionState();
}

class _LastMsgDescriptionState extends State<LastMsgDescription> {
  var desc = '';

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

    MessageMgr().on('Update LastMsg', updateList);
  }

  @override
  void dispose() {
    MessageMgr().off('Update LastMsg', updateList);
    super.dispose();
  }

  updateList(sessionId) {
    if (sessionId == widget.lastMessageModel.sessionId) {
      getLastMsgDesc();
    }
  }

  //获取用户的名字
  getFriendName() async {
    String fdName;

    if (widget.lastMessageModel.channelType == ChatChannelType.Group.value) {
      //群的最新消息
      fdName = Provider.of<RefNameProvider>(context).getGroupRefName(
          widget.lastMessageModel.sessionId, widget.lastMessageModel.fromId);
    } else {
      //私聊最新消息
      var friendInfo =
          await HttpUtil().getFriendInfo(widget.lastMessageModel.friendId);
      if (friendInfo != null) {
        fdName = Provider.of<RefNameProvider>(context)
            .getRefName(friendInfo.userId, friendInfo.nickName);
      }
    }
    return fdName;
  }

  getLastMsgDesc() async {
    MessageMgr().emit('Update Group List');
    if (widget.lastMessageModel == null) {
      return;
    }
    switch (widget.lastMessageModel.type) {
      case ChatType.TextChatType:
        desc = utf8.decode(widget.lastMessageModel.msgContent);
        print('desc: $desc');
        if (desc.contains('[ ')) {
          desc = desc.replaceAll('[ ', '[');
        }
        if (desc.contains(' ]')) {
          desc = desc.replaceAll(' ]', ']');
        }
        break;
      case ChatType.EmoticonType:
        desc = '[${I18n.of(Constants.getCurrentContext()).emoji}]';
        break;
      case ChatType.ImageChatType:
        desc = '[${I18n.of(Constants.getCurrentContext()).picture}]';
        break;
      case ChatType.ShortVideoChatType:
        desc = '[${I18n.of(Constants.getCurrentContext()).video}]';
        break;
      case ChatType.PlaceChatType:
        desc = '[${I18n.of(Constants.getCurrentContext()).locate}]';
        break;
      case ChatType.ShortVoiceChatType:
        desc = '[${I18n.of(Constants.getCurrentContext()).voice}]';
        break;

      case ChatType.GiftChatType:
        GiftChat giftChat =
            GiftChat.fromBuffer(widget.lastMessageModel.msgContent);

        if (giftChat.tuId == UserData().basicInfo.userId) {
          desc = I18n.of(Constants.getCurrentContext()).you_get;
        } else {
          desc = I18n.of(Constants.getCurrentContext()).you_give;
        }

        break;

      case ChatType.RedWalletChatType:
        if (widget.lastMessageModel.fromId == 0) {
          var fdName = await getFriendName();
          //服务器通知消息
          RedWallet wallet =
              RedWallet.fromBuffer(widget.lastMessageModel.msgContent);
          if (wallet.state == RedWalletState.Received) {
            var myId = UserData().basicInfo.userId;
            if (wallet.suId == myId) {
              desc = I18n.of(Constants.getCurrentContext())
                  .get_money
                  .replaceFirst('/s1', fdName);
            } else {
              desc = I18n.of(Constants.getCurrentContext())
                  .you_get_money
                  .replaceFirst('/s1', fdName);
            }
          } else if (wallet.state == RedWalletState.Expire) {
            desc = I18n.of(Constants.getCurrentContext()).money_over;
          } else {
            print('WWWWW${wallet.state}');
          }
        } else {
          desc = '[${I18n.of(Constants.getCurrentContext()).red_money}]';
        }
        break;

      case ChatType.GroupChatNoticeType:

        if(widget.lastMessageModel.channelType==ChatChannelType.Session.value){
          ///翻译管家的 通知消息
          desc = '翻译管家---';
          print('翻译管家的 通知消息-');
          TransHKChatNotice res = TransHKChatNotice.fromBuffer(widget.lastMessageModel.msgContent);
          if(res.noticeType==TransHKChatNoticeType.StartChat){
            return '[翻译管家服务开始]';
          }else  if(res.noticeType==TransHKChatNoticeType.EndChat){
            return '[翻译管家服务结束]';
          }else{
            return '';
          }


        }else{
          var notice =
          GroupChatNotice.fromBuffer(widget.lastMessageModel.msgContent);
          print('widget.lastMessageModel.type ${widget.lastMessageModel.type}');
          var groupInfo = await GroupInfoMgr()
              .getGroupInfo(widget.lastMessageModel.sessionId);

          desc = MsgHandler.getGroupNoticeMsg(notice, groupInfo);
          print('ggdesc $desc}');
          if (desc.contains('\$')) {
            desc = desc.substring(0, desc.indexOf('\$'));
          } else {}
        }



        break;

      case ChatType.FileChatType:
        desc = '[${I18n.of(context).file}]';
        break;
      default:
    }
    if (mounted) {
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    if (widget.lastMessageModel == null) {
      return Container();
    }

    if (widget.lastMessageModel.type == ChatType.TextChatType) {
      //处理表情
      return extendedText(desc,
          fontSize: 12,
          color: Constants.GreyTextColor,
          emojisize: 12.0,
          maxLines: 1);
    } else {
      return Text(desc,
          textScaleFactor: 1.0,
          textAlign: TextAlign.center,
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: AppStyles.DescStyle);
    }
  }
}
