import 'package:cached_network_image/cached_network_image.dart';
import 'package:chat/data/UserData.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/models/group_info_model.dart';
import 'package:chat/models/ref_name_provider.dart';
import 'package:chat/utils/MessageMgr.dart';
import 'package:chat/utils/group_member_model.dart';
import 'package:chat/utils/screen.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../data/constants.dart';
import '../utils/CustomUI.dart';
import '../utils/app_navigator.dart';
import 'create_group_view.dart';
import 'package:chat/utils/friend_list_mgr.dart';

class GroupAllMember extends StatefulWidget {
  final GroupInfoModel groupInfoModel;

  GroupAllMember({Key key, this.groupInfoModel}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return GroupAllMemberState();
  }
}

class GroupAllMemberState extends State<GroupAllMember> {
  static const Separate_Size = 15.0;
  bool isHost;

  ///是否是群主
  @override
  void initState() {
    super.initState();
    MessageMgr().on('Update Group Info', updateGroupInfo);
    isHost = widget.groupInfoModel.hosterId == UserData().basicInfo.userId;
  }

  updateGroupInfo(args) async {
    if (mounted) {
      print('群设置 - 更新群信息2222');
      setState(() {});
    }
  }

  @override
  void dispose() {
    super.dispose();
    MessageMgr().off('Update Group Info', updateGroupInfo);
  }

  @override
  Widget build(BuildContext context) {
    Widget appBar = new AppBar(
      backgroundColor: AppColors.NewAppbarBgColor,
      title: new Text(
        I18n.of(context).group_memeber,
        style: TextStyle(color: AppColors.NewAppbarTextColor),
        textScaleFactor: 1.0,
      ),
      leading: CustomUI.buildCustomLeading(context),
      centerTitle: true,
    );

    return Scaffold(
      appBar: appBar,
      body: SafeArea(
        child: ListView(
          children: <Widget>[
            SizedBox(
              height: 12,
            ),

            ///群成员
            buildMember(
              () {
                ///添加成员
                Navigator.of(context).push(
                  new MaterialPageRoute(
                    builder: (context) {
                      return CreateGroupPage(
                          GroupOperatingPageType.AddMember,
                          widget.groupInfoModel.getMembersInGroup(),
                          widget.groupInfoModel.sessionId);
                    },
                  ),
                );
              },
              () {
                ///删除成员
                Navigator.of(context).push(
                  new MaterialPageRoute(
                    builder: (context) {
                      return CreateGroupPage(
                          GroupOperatingPageType.DeleteMember,
                          widget.groupInfoModel.getMembersInGroup(),
                          widget.groupInfoModel.sessionId);
                    },
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget buildMember(Function addMember, Function deleteMember) {
//    List<GroupMemberModel> members = widget.groupInfoModel.members;

    List<GroupMemberModel> members = [];

    for (int k = 0; k < widget.groupInfoModel.members.length; k++) {
      //只加入存在群的
      GroupMemberModel mo = widget.groupInfoModel.members[k];
      if (mo.inGroup == 1) {
        print('id ${mo.memberId} name ${mo.refName}  avatar ${mo.avtar}');
        members.add(mo);
      }
    }

    members.sort((GroupMemberModel left, GroupMemberModel right) =>
        right.identity.compareTo(left.identity));

    double size = Screen.width / 5;

    List<Widget> list = [];
    for (int index = 0; index < members.length; index++) {
      var member = members[index];
      var refName = Provider.of<RefNameProvider>(context)
          .getGroupRefName(widget.groupInfoModel.sessionId, member.memberId);
      list.add(GestureDetector(
        child: Container(
          child: Column(
            children: <Widget>[
              ClipRRect(
                  borderRadius: BorderRadius.all(Radius.circular(8.0)),
                  child: CachedNetworkImage(
                    imageUrl: member.avtar,
                    placeholder: (context, url) => Image.asset(
                      Constants.DefaultHeadImgUrl,
                      width: size - 30,
                      height: size - 30,
                    ),
                    width: size - 30,
                    height: size - 30,
                  )),
              SizedBox(
                height: 5,
              ),
              Container(
                width: size - 30,
                alignment: Alignment.center,
                child: Text(
                  refName,
                  textScaleFactor: 1.0,
                  style: TextStyle(fontSize: 11, color: Color(0xff818181)),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          ),
          width: size,
          height: size,
        ),
        behavior: HitTestBehavior.translucent,
        onTap: () {
          if (member.memberId != UserData().basicInfo.userId) {
            AppNavigator.pushProfileInfoPage(context, member.memberId,
                fromWhere: 2,
                addMode: !FriendListMgr().isMyFriend(member.memberId) ? 1 : 0);
          }
        },
      ));
    }

    list.add(GestureDetector(
      onTap: addMember,
      child: Container(
        width: size,
        height: size,
        child: Column(
          children: <Widget>[
            Container(
              alignment: Alignment.center,
              width: size - 30,
              height: size - 30,
              child: Text(
                '+',
                textScaleFactor: 1.0,
                style: TextStyle(fontSize: 30, color: Color(0xffB1B1B1)),
              ),
              decoration: BoxDecoration(
//              color: Colors.black,
                  border: Border.all(color: Color(0xffC3C3C3), width: 1.0),
                  borderRadius: BorderRadius.all(Radius.circular(6))),
            )
          ],
        ),
      ),
    ));
    if (isHost) {
      list.add(Container(
        width: size,
        height: size,
        child: Column(
          children: <Widget>[
//                      SizedBox(height: 5,),
            GestureDetector(
              onTap: deleteMember,
              child: Container(
                alignment: Alignment.center,
                width: size - 30,
                height: size - 30,
                child: Container(
                  color: Color(0xffB1B1B1),
                  width: 20,
                  height: 2.6,
                ),
                decoration: BoxDecoration(
                    border: Border.all(color: Color(0xffC3C3C3), width: 1.0),
                    borderRadius: BorderRadius.all(Radius.circular(6))),
              ),
            )
          ],
        ),
      ));
    }

    return Container(
      color: Color(0xffFAFAFA),
      //height: Screen.height-100,
      child: Column(
        children: <Widget>[
          SizedBox(
            height: 10,
          ),
          Wrap(
            children: list,
            crossAxisAlignment: WrapCrossAlignment.start,
            alignment: WrapAlignment.start,
          ),
        ],
      ),
    );
  }
}
