import 'package:cached_network_image/cached_network_image.dart';
import 'package:chat/data/UserData.dart';
import 'package:chat/data/chat_data_mgr.dart';
import 'package:chat/data/group_data_mgr.dart';
import 'package:chat/home/add_friend.dart';
import 'package:chat/home/group_announcement.dart';
import 'package:chat/home/group_manage_page.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/msgHandler.dart';
import 'package:chat/utils/screen.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';

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

class GroupSetting extends StatefulWidget {
  final GroupInfoModel groupInfoModel;

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

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

class GroupSettingState extends State<GroupSetting> {
  static const Separate_Size = 15.0;

  bool notice = true; //消息提示
  bool stickyChat = false; //置顶聊天
  bool showGroupFriendNickname = true; //显示群成员昵称

  bool isHost;

  ///是否是群主

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

    stickyChat = widget.groupInfoModel.topTag > 0;
    MessageMgr().on('Update Group Info', updateGroupInfo);
    notice = widget.groupInfoModel.messageFree == 1;
    showGroupFriendNickname = widget.groupInfoModel.isShowName > 0;

    print(
        '  widget.groupInfoModel.hosterId : ${widget.groupInfoModel.hosterId}');
  }

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

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

  quitGroup() {
    print('退出所有页面');
    GroupInfoMgr().deleteGroup(widget.groupInfoModel.sessionId);
    MessageMgr().emit('Quit Group', widget.groupInfoModel.sessionId);
    Navigator.of(context).popUntil(ModalRoute.withName('/main'));
  }

//清空聊天记录
  clearRecord() {
    //清楚最后一条数据
    widget.groupInfoModel.lastMsg = null;

    //清空聊天数据
    ChatDataMgr().deleteMsg(widget.groupInfoModel.sessionId, true);
  }

  @override
  Widget build(BuildContext context) {
    isHost = widget.groupInfoModel.hosterId == UserData().basicInfo.userId;
    print(widget.groupInfoModel.myName);
    Widget appBar = AppBar(
      backgroundColor: AppColors.NewAppbarBgColor,
      title: new Text(
        I18n.of(context).chat_news +
            '(${widget.groupInfoModel.getMembersInGroup().length})',
        textScaleFactor: 1.0,
        style: TextStyle(color: AppColors.NewAppbarTextColor),
      ),
      leading: CustomUI.buildCustomLeading(context),
      centerTitle: true,
    );

    var groupName =
        (widget.groupInfoModel.name == '' || widget.groupInfoModel.name == null)
            ? I18n.of(context).undefine_name
            : widget.groupInfoModel.name;

    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);
                    },
                  ),
                );
              },
              () {
                /// 查看更多成员
                AppNavigator.pushGroupAllMember(context, widget.groupInfoModel);
              },
            ),

            SizedBox(
              height: 12,
            ),

            ///群聊名称
            _buildSetting(I18n.of(context).group_chat_name, groupName, () {
              if (widget.groupInfoModel.canAlterGroupName()) {
                Navigator.of(context).push(
                  new MaterialPageRoute(
                    builder: (context) {
                      return AddFriendPage(
                        userId: widget.groupInfoModel.sessionId,
                        pageType: SendMessagePageType.ChangeGroupName,
                        originalName: groupName,
                      );
                    },
                  ),
                );
              } else {
                showToast('权限不足');
              }
            }),

            ///群二维码
            UserData().groupQRCode == 0
                ? Container()
                : _buildSetting(I18n.of(context).group_qr, '', () {
                    AppNavigator.pushGroupQrPage(
                        context, widget.groupInfoModel);
                  },
                    extendWidget: Icon(
                      IconData(0xe658, fontFamily: 'iconfont'),
                      size: 20.0,
                      color: Color(AppColors.TabIconNormal),
                    )),

            ///群公告
            groupAnnounce(),

            ///群管理
            widget.groupInfoModel.hosterId == UserData().basicInfo.userId
                ? _buildSetting(I18n.of(context).group_setting, '', () {
                    Navigator.of(context).push(
                      new MaterialPageRoute(
                        builder: (context) {
                          return GroupManagePage(
                            groupInfoModel: widget.groupInfoModel,
                          );
                        },
                      ),
                    );
                  }, showDivider: false)
                : Container(),
            SizedBox(
              height: 11,
            ),

            ///消息免打扰
            _buildSettingWithSwitch(notice, I18n.of(context).close_news_notice,
                (bool val) {
              setState(() {
                notice = val;
                MsgHandler.updateMemberMsgFreeReq(
                    widget.groupInfoModel.sessionId, notice);
              });
            }),
            Container(
              height: 0.5,
              color: Colors.white,
              child: Container(
                color: Color(0xffE5E5E5),
              ),
              padding: EdgeInsets.symmetric(horizontal: 20),
            ),

            ///置顶聊天
            _buildSettingWithSwitch(stickyChat, I18n.of(context).set_chat_top,
                (bool val) {
              setState(() {
                stickyChat = val;
                widget.groupInfoModel.updateTopTag(stickyChat);
                MessageMgr().emit('Update Group List');
              });
            }),
            SizedBox(
              height: 11,
            ),

            ///我在本群的昵称
            _buildSetting(
                I18n.of(context).my_group_nickname,
                widget.groupInfoModel.myName == null
                    ? UserData().basicInfo.nickName
                    : widget.groupInfoModel.myName, () {
              Navigator.of(context).push(
                new MaterialPageRoute(
                  builder: (context) {
                    return AddFriendPage(
                      userId: widget.groupInfoModel.sessionId,
                      pageType: SendMessagePageType.ChangeGroupNickName,
                      originalName: widget.groupInfoModel.myName,
                    );
                  },
                ),
              );
            }),

            ///显示群成员昵称
            _buildSettingWithSwitch(showGroupFriendNickname,
                I18n.of(context).show_group_member_name, (bool val) {
              setState(() {
                showGroupFriendNickname = val;
                widget.groupInfoModel.updateShowNameSwitch(val);
                MsgHandler.setGroupIsShowMenberNiceNameReq(widget.groupInfoModel.sessionId, val);
              });
            }),

            SizedBox(
              height: 11,
            ),

            ///清除聊天记录
            _buildSettingWithConfirm(I18n.of(context).group_clean_chat_record,
                I18n.of(context).group_clean_chat_record, () {
              clearRecord();
              Navigator.of(context).pop();
            }),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: Separate_Size),
              child: Divider(
                color: Color(0xffE5E5E5),
                height: 0.6,
              ),
            ),

            ///退出并删除按钮
            _buildSettingWithConfirm(I18n.of(context).quit_and_delete,
                I18n.of(context).quit_group_tips, () {
              print('退出群聊');
              quitGroup();
              MsgHandler.quitGroup(widget.groupInfoModel.sessionId);
            }),
          ],
        ),
      ),
    );
  }

  Widget _buildSetting(String title, String desc, Function func,
      {showRightIcon = true, showDivider = true, extendWidget}) {
    //版本

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10),
      child: FullWidthButton(
        showRightIcon: showRightIcon,
        title: title,
        description: desc,
        extendWidget: extendWidget,
        showDivider: showDivider,
        onPressed: func,
      ),
      decoration: BoxDecoration(
        color: Colors.white,
      ),
    );
  }

  Widget _buildSettingWithSwitch(
      bool switchValue, String title, Function onchang) {
    Widget left = new Text(
      title,
      textScaleFactor: 1.0,
      style: TextStyle(fontSize: 14, fontWeight: FontWeight.normal),
    );
    Widget right = new Expanded(
        child: new Container(
            alignment: Alignment.centerRight,
            padding: EdgeInsets.only(right: 8),
            child: new Switch(
              value: switchValue,
              activeTrackColor: Constants.ConfrimButtonColor.withOpacity(0.3),
              onChanged: onchang,
            )));
    return new Container(
      decoration: BoxDecoration(
        color: Colors.white,
      ),
      padding: EdgeInsets.only(left: 20),
      height: 53,
      child: new Row(
        children: <Widget>[left, right],
      ),
    );
  }

  Widget _buildSettingWithConfirm(
      String title, String dialogTips, Function function) {
    return Container(
        color: Colors.white,
        padding: EdgeInsets.only(top: 11, bottom: 11),
        child: InkWell(
          onTap: () {
            showModalBottomSheet(
              context: context,
              backgroundColor: Colors.transparent,
              builder: (BuildContext context) {
                return Container(
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(13),
                          topRight: Radius.circular(13))),
                  height: 225,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.fromLTRB(15, 15, 15, 13),
                        child: Text(
                          dialogTips,
                          textScaleFactor: 1.0,
                          style:
                              TextStyle(fontSize: 12, color: Color(0xff777777)),
                        ),
                      ),
                      Divider(
                        color: Color(0xffE5E5E5),
                      ),
                      InkWell(
                        onTap: function,
                        child: Container(
                          height: 60,
                          alignment: Alignment.center,
                          child: Text(I18n.of(context).determine,
                              textScaleFactor: 1.0,
                              style: TextStyle(
                                  fontSize: 18,
                                  color: Constants.ConfrimButtonColor)),
                        ),
                      ),
                      Container(
                        color: Color(0xffF2F2F2),
                        height: 4,
                      ),
                      InkWell(
                        onTap: () {
                          Navigator.of(context).pop();
                        },
                        child: Container(
                          height: 60,
                          alignment: Alignment.center,
                          child: Text(I18n.of(context).cancel,
                              textScaleFactor: 1.0,
                              style: TextStyle(
                                  fontSize: 18, color: Color(0xff4B4B4B))),
                        ),
                      )
                    ],
                  ),
                );
              },
            );
          },
          child: Container(
            height: 40,
            margin: EdgeInsets.symmetric(horizontal: 40),
            alignment: Alignment.center,
            child: Text(
              title,
              textScaleFactor: 1.0,
              style:
                  TextStyle(color: Constants.ConfrimButtonColor, fontSize: 15),
            ),
          ),
        ));
  }

  ///群公告
  Widget groupAnnounce() {
    return InkWell(
        onTap: () {
          if (widget.groupInfoModel.describe == '' && !isHost) {
            showToast(I18n.of(context).only_host);
            return;
          }
          Navigator.of(context).push(
            new MaterialPageRoute(
              builder: (context) {
                return GroupAnnouncementPage(
                  groupInfoModel: widget.groupInfoModel,
                );
              },
            ),
          );
        },
        child: Container(
            color: Colors.white,
            child: Column(
              children: <Widget>[
                Container(
                    padding: EdgeInsets.symmetric(
                        horizontal: Separate_Size, vertical: 12),
                    color: Colors.white,
                    child: Row(
                      children: <Widget>[
                        Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Padding(
                                padding: EdgeInsets.only(top: 0, left: 4),
                                child: Text(
                                  I18n.of(context).group_announcement,
                                  textScaleFactor: 1.0,
                                  style: TextStyle(
                                      color: Colors.black, fontSize: 14),
                                ),
                              ),
                              widget.groupInfoModel.describe == null ||
                                      widget.groupInfoModel.describe == ""
                                  ? Container()
                                  : Container(
                                      width: Screen.width - 55,
                                      padding: EdgeInsets.only(top: 3, left: 4),
                                      child: Text(
                                        widget.groupInfoModel.describe,
                                        textScaleFactor: 1.0,
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                            color: Color(0xff818181),
                                            fontSize: 11),
                                      ),
                                    ),
                            ]),
                        Expanded(
                          child: SizedBox(),
                        ),
                        Padding(
                            padding: EdgeInsets.only(bottom: 0),
                            child: Icon(
                              IconData(0xe63c, fontFamily: 'iconfont'),
                              size: 20.0,
                              color: Color(AppColors.TabIconNormal),
                            ))
                      ],
                    )),
                Container(
                  margin: EdgeInsets.symmetric(horizontal: 15),
                  decoration: BoxDecoration(
                    border: Border(
                      bottom: Constants.GreyBorderSide,
                    ),
                  ),
                )
              ],
            )));
  }

  ///群成员显示
  Widget buildMember(
      Function addMember, Function deleteMember, Function seeMoreMember) {
//    List<GroupMemberModel> members = widget.groupInfoModel.getMembersInGroup();

    List<GroupMemberModel> members = [];

    for (int k = 0; k < widget.groupInfoModel.members.length; k++) {
      //只加入存在群的
      GroupMemberModel mo = widget.groupInfoModel.members[k];
      if (mo.inGroup == 1) {
        members.add(mo);
      }
    }

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

    print('群成员数量- ${members.length}');
    int length = members.length;
    int dex = isHost ? 2 : 1;
    int shouldShow = length > (10 - dex) ? 10 - dex : length;

    double size = Screen.width / 5;

    List<Widget> list = [];
    for (int index = 0; index < shouldShow; 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,
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 11, color: Color(0xff818181)),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              )
            ],
          ),
          width: size,
          height: size,
        ),
        behavior: HitTestBehavior.translucent,
        onTap: () {
          if (members[index].memberId != UserData().basicInfo.userId) {
            AppNavigator.pushProfileInfoPage(context, members[index].memberId,
                fromWhere: 2, addMode:  !FriendListMgr().isMyFriend(members[index].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(
                  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>[
            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),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(
            height: 5,
          ),
          Wrap(
            children: list,
            crossAxisAlignment: WrapCrossAlignment.start,
            alignment: WrapAlignment.start,
          ),
          length > (10 - dex)
              ? GestureDetector(
                  onTap: seeMoreMember,
                  child: Container(
                    height: 35,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Text(
                          I18n.of(context).show_more_member,
                          textScaleFactor: 1.0,
                          style: TextStyle(color: Color(0xff818181)),
                        ),
                        Padding(
                            padding: EdgeInsets.only(bottom: 1.5),
                            child: Icon(
                              IconData(0xe63c, fontFamily: 'iconfont'),
                              size: 20.0,
                              color: Color(AppColors.TabIconNormal),
                            ))
                      ],
                    ),
                  ),
                )
              : Container(),
        ],
      ),
    );
  }
}
