package com.efounder.chat.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.SwitchCompat;

import android.text.InputType;
import android.text.TextUtils;
import android.text.method.DigitsKeyListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.chat.R;
import com.efounder.chat.adapter.GridUserAdapter;
import com.efounder.chat.db.GetDBHelper;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.chat.manager.PictureAndCropManager;
import com.efounder.chat.model.AppConstant;
import com.efounder.chat.model.ChatListItem;
import com.efounder.chat.model.Group;
import com.efounder.chat.model.GroupFunction;
import com.efounder.chat.model.GroupPositionsBean;
import com.efounder.chat.model.GroupRootBean;
import com.efounder.chat.model.MessageEvent;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.ChatActivitySkipUtil;
import com.efounder.chat.utils.GroupAvatarUtil;
import com.efounder.chat.utils.GroupLocationHttpRequest;
import com.efounder.chat.utils.GroupNameUtil;
import com.efounder.chat.utils.GroupOperationHelper;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.utils.PansoftCloudUtil;
import com.efounder.chat.utils.UshareHelper;
import com.efounder.chat.widget.ExpandGridView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.service.Registry;
import com.efounder.util.AbFragmentManager;
import com.efounder.util.EnvSupportManager;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.google.gson.Gson;
import com.pansoft.library.CloudDiskBasicOperation;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.utilcode.util.LogUtils;
import com.utilcode.util.ReflectUtils;
import com.utilcode.util.ToastUtils;
import com.utilcode.util.UriUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;

import static com.efounder.chat.R.id.btn_exit_grp;
import static com.efounder.chat.http.GetHttpUtil.ROOTURL;
import static com.efounder.chat.manager.PictureAndCropManager.PHOTO_REQUEST_CUT;
import static com.efounder.chat.manager.PictureAndCropManager.PHOTO_REQUEST_GALLERY;
import static com.efounder.chat.manager.PictureAndCropManager.PHOTO_REQUEST_TAKEPHOTO;
import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.efounder.frame.utils.NetStateBroadcastReceiver.isNetActive;


/**
 * 群设置界面
 *
 * @author YQS
 */
public class ChatGroupSettingActivity extends BaseActivity implements
        OnClickListener {
    private static final String TAG = "ChatGroupSettingActivit";
    private TextView tv_groupname;
    // 成员总数

    private TextView tv_m_total;
    // 成员总数
    int m_total = 0;
    // 功能列表
    private ExpandGridView gridview;
    // 人员列表
    private ExpandGridView userGridview;
    // 修改群名称、置顶、、、、
    private RelativeLayout re_change_groupname;
    private RelativeLayout rl_switch_chattotop;
    private RelativeLayout rl_switch_block_groupmsg;
    private RelativeLayout re_clear;//清空聊天记录
    private RelativeLayout re_myGroupName;
    private RelativeLayout reShareGroup;

    private TextView tv_myGroupName;
    private TextView tv_qunjieshao;//群介绍
    private TextView tv_titleView;//群名称左上方

    // 状态变化
    private SwitchCompat switchTop;// 置顶聊天
    private SwitchCompat switchNotification;// 免打扰
    // 删除并退出

    private Button exitBtn;

    // 群名称
    private String group_name;
    // 修改后群名称
    private String newName;
    // 是否是管理员
    boolean is_admin = false;
    String longClickUsername = null;

    private int groupId;
    private Group group;
    private GridAdapter adapter;
    private List<GroupFunction> functionList;
    public static ChatGroupSettingActivity instance;


    //仿qq 群聊
    private RelativeLayout rlTopLayout;
    private ImageView ivGroupAvatarView, ivErweimaView, ivBgView;
    private TextView tvGroupIdView;
    private TextView userCountView;
    private LinearLayout ll_groupUserLayout;//点击跳转群成员界面
    private PictureAndCropManager pictureAndCropManager;//拍照裁剪
    private LinearLayout ll_myGroupAddress;
    private RelativeLayout ll_show_address;
    private TextView tv_address_title;
    private TextView tv_address_details;
    private RelativeLayout rlFreeAddgroup;
    private SwitchCompat switchFreeAddgroup;
    private RelativeLayout rlAllNoSpeak;
    private SwitchCompat switchAllNoSpeak;
    private RelativeLayout reGroupEnglishname;
    private TextView tvGroupEnglishName;
    private RelativeLayout reGroupRecommend;
    private TextView tvGroupRecommend;
    private SmartRefreshLayout refreshLayout;


    private LinearLayout ll_groupsetting_address;//展示地址列表的容器
    private List<GroupPositionsBean.DataBean> data1;//办公地址列表
    private GroupLocationHttpRequest request;
    private String prl = "pln";
    private List<GroupRootBean> allMenuList;
    /**
     * 反射主工程的分享帮助类
     */
    private ReflectUtils reflectUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.social_groupsetting_activitynew);
        instance = this;
        groupId = getIntent().getIntExtra("id", 1);

        pictureAndCropManager = new PictureAndCropManager(this);
        initView();
        loadNetData();
        // updateGroup();
    }

    private void initView() {
        tv_groupname = (TextView) findViewById(R.id.tv_groupname);
        tv_m_total = (TextView) findViewById(R.id.tv_m_total);
        gridview = (ExpandGridView) findViewById(R.id.gridview);
        userGridview = (ExpandGridView) findViewById(R.id.gridview_groupuser);
        re_change_groupname = (RelativeLayout) findViewById(R.id.re_change_groupname);
        rl_switch_chattotop = (RelativeLayout) findViewById(R.id.rl_switch_chattotop);
        rl_switch_block_groupmsg = (RelativeLayout) findViewById(R.id.rl_switch_block_groupmsg);
        re_clear = (RelativeLayout) findViewById(R.id.re_clear);//清空聊天记录
        switchTop = (SwitchCompat) findViewById(R.id.switch_top);
        switchNotification = (SwitchCompat) findViewById(R.id.switch_notification);
        switchNotification.setOnClickListener(this);
        switchTop.setOnClickListener(this);
        re_myGroupName = (RelativeLayout) findViewById(R.id.re_mygroupremark);
        ll_myGroupAddress = (LinearLayout) findViewById(R.id.ll_add_address);
        ll_groupsetting_address = (LinearLayout) findViewById(R.id.ll_groupsetting_address);
        tv_myGroupName = (TextView) findViewById(R.id.tv_mygroupname);//我在本群中的昵称
        tv_titleView = (TextView) findViewById(R.id.tv_title);
        reShareGroup = (RelativeLayout) findViewById(R.id.re_share_group);
        exitBtn = (Button) findViewById(R.id.btn_exit_grp);
        re_change_groupname.setOnClickListener(this);
        rl_switch_chattotop.setOnClickListener(this);
        rl_switch_block_groupmsg.setOnClickListener(this);
        re_myGroupName.setOnClickListener(this);
        re_clear.setOnClickListener(this);
        exitBtn.setOnClickListener(this);
        ll_myGroupAddress.setOnClickListener(this);

        //这部分是仿qq群聊新增的
        rlTopLayout = (RelativeLayout) findViewById(R.id.rl_top);
        ivGroupAvatarView = (ImageView) findViewById(R.id.iv_group_avatar);
        ivErweimaView = (ImageView) findViewById(R.id.iv_grouperweima);
        tvGroupIdView = (TextView) findViewById(R.id.tv_groupid);
        ivBgView = (ImageView) findViewById(R.id.iv_bgView);
        userCountView = (TextView) findViewById(R.id.tv_usercount);
        ll_groupUserLayout = (LinearLayout) findViewById(R.id.ll_groupUserlayout);
        ll_groupUserLayout.setOnClickListener(this);
        tv_qunjieshao = (TextView) findViewById(R.id.tv_qunjieshao);
        rlFreeAddgroup = (RelativeLayout) findViewById(R.id.rl_free_addgroup);
        switchFreeAddgroup = (SwitchCompat) findViewById(R.id.switch_free_addgroup);
        rlAllNoSpeak = (RelativeLayout) findViewById(R.id.rl_all_no_speak);
        switchAllNoSpeak = (SwitchCompat) findViewById(R.id.switch_all_no_speak);
        switchAllNoSpeak.setOnClickListener(this);
        switchFreeAddgroup.setOnClickListener(this);
        reGroupEnglishname = (RelativeLayout) findViewById(R.id.re_group_englishname);
        tvGroupEnglishName = (TextView) findViewById(R.id.tv_group_english_name);
        reGroupRecommend = (RelativeLayout) findViewById(R.id.re_group_recommend);
        tvGroupRecommend = (TextView) findViewById(R.id.tv_group_recommend);

        tvGroupEnglishName.setOnClickListener(this);
        reGroupRecommend.setOnClickListener(this);
        refreshLayout = (SmartRefreshLayout) findViewById(R.id.refreshLayout);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getGroupInfo();
            }
        });
//        tv_address_title = (TextView) findViewById(R.id.tv_address_title);
//        tv_address_details = (TextView) findViewById(R.id.tv_address_details);
//        ll_show_address = (RelativeLayout) findViewById(R.id.ll_show_address);

    }

    /**
     * 为群组删除办公地点
     *
     * @param id 位置记录的id
     */
    private void delGroupPosition(int id) {
        if (null == request) {
            request = new GroupLocationHttpRequest();
        }

        request.delGroupPosition(id + "", new CloudDiskBasicOperation.ReturnBack() {
            @Override
            public void onReturnBack(String result) throws JSONException {
                JSONObject object = new JSONObject(result);
                String result1 = object.getString("result");
                if ("success".equals(result1)) {
                    ToastUtil.showToast(ChatGroupSettingActivity.this.getApplicationContext(), R.string.chat_delete_success);
                    loadNetData();
                }
            }
        });
    }

    private void initData() {
        initFunctionData();
        initGroupUsers(group, instance, tv_m_total, userCountView, userGridview, 1);
        setUpView();
        // 显示群组功能
        if (!EnvironmentVariable.getProperty("isShowGroupSettingMenu", "0").equals("-1")) {
            showFunction(functionList);
        } else {
            gridview.setVisibility(View.GONE);
        }

        // 判断是否是群主，是群主有删成员的权限，并显示减号按钮
        if (group.getCreateId() == Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))) {
            is_admin = true;
        }
        setTopView(group, tv_groupname, tvGroupIdView, tv_titleView, tv_qunjieshao);
        final String avatar = GroupAvatarUtil.getAvatar(group.getAvatar());
//        imageLoader.displayImage(avatar, ivGroupAvatarView, options);
        LXGlideImageLoader.getInstance().showRoundGrouAvatar(this, ivGroupAvatarView, avatar, LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_12);
        //todo 群头像设置点击事件
        ivGroupAvatarView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

                boolean isManager = isManager();
                if (group.getCreateId() == Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))
                        || isManager) {
                    showPhotoDialog();

                }
            }
        });
        ivErweimaView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ChatGroupSettingActivity.this, CreateUserQRCode.class);

                Bundle bundle = new Bundle();
                bundle.putString("type", "addGroup");
                bundle.putString("id", String.valueOf(groupId));
                bundle.putString("avatar", avatar);
                bundle.putString("nickname", group.getGroupName());
                bundle.putString("name", group.getGroupName());
                bundle.putString("sex", "");

                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        tvGroupEnglishName.setText("".equals(group.getEnglihName()) ? ResStringUtil.getString(R.string.chat_no_set) : group.getEnglihName());
        tvGroupRecommend.setText("".equals(group.getRecommond()) ? getString(R.string.wechatview_no_group_recommend) : group.getRecommond());
        switchNotification.setChecked(group.getIsBother());
        switchTop.setChecked(group.getIsTop());
        switchAllNoSpeak.setChecked(group.isBanSpeak());
        switchFreeAddgroup.setChecked(group.getGroupType() == 1);
        if (GroupNameUtil.getUserRoleInGroup(groupId, Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))) == User.GROUPCREATOR
                || GroupNameUtil.getUserRoleInGroup(groupId, Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)))
                == User.GROUPMANAGER) {
            rlAllNoSpeak.setVisibility(View.VISIBLE);
            rlFreeAddgroup.setVisibility(View.VISIBLE);
        } else {
            switchAllNoSpeak.setClickable(false);
            switchFreeAddgroup.setClickable(false);
            switchAllNoSpeak.setFocusable(false);
            switchFreeAddgroup.setFocusable(false);

        }

        if (!EnvSupportManager.isSupportBanSpeak()) {
            rlAllNoSpeak.setVisibility(View.GONE);
            rlFreeAddgroup.setVisibility(View.GONE);
        }
        if (EnvSupportManager.isSupportShareGroup()) {
            reShareGroup.setVisibility(View.VISIBLE);
            reShareGroup.setOnClickListener(this);
        }
        if (EnvSupportManager.isShowGroupWorkAddressMenu()) {
            ll_myGroupAddress.setVisibility(View.VISIBLE);
        } else {
            ll_myGroupAddress.setVisibility(View.GONE);
        }
    }

    /**
     * 判断当前登录用户是否是管理员
     *
     * @return
     */
    private boolean isManager() {
        boolean isManager = false;//当前登录的用户是否是管理员
        if (group.getUsers() != null) {
            for (User user : group.getUsers()) {
                if (user.getId() == Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))) {
                    int groupUserType = user.getGroupUserType();
                    if (groupUserType == 1) {
                        isManager = true;
                    }
                }
            }
        }
        return isManager;
    }

    private void showPhotoDialog() {
        final AlertDialog dlg = new AlertDialog.Builder(this).create();
        dlg.show();
        Window window = dlg.getWindow();
        // *** 主要就是在这里实现这种效果的.
        // 设置窗口的内容页面,shrew_exit_dialog.xml文件中定义view内容
        window.setContentView(R.layout.alertdialog);
        // 为确认按钮添加事件,执行退出应用操作
        LinearLayout ll_title = (LinearLayout) window
                .findViewById(R.id.ll_title);
        ll_title.setVisibility(View.VISIBLE);
        TextView tv_title = (TextView) window.findViewById(R.id.tv_title);
        tv_title.setText(getResources().getString(R.string.chatgroupsettingactivity_string9));
        TextView tv_paizhao = (TextView) window.findViewById(R.id.tv_content1);
        tv_paizhao.setText(R.string.common_text_take_picture);
        tv_paizhao.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                pictureAndCropManager.takePicture();
                dlg.cancel();
            }
        });
        TextView tv_xiangce = (TextView) window.findViewById(R.id.tv_content2);
        tv_xiangce.setText(R.string.common_text_photo_album);
        View lineView = window.findViewById(R.id.line1);
        lineView.setVisibility(View.VISIBLE);
        tv_xiangce.setVisibility(View.VISIBLE);
        tv_xiangce.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                pictureAndCropManager.selectPhoto();
                dlg.cancel();
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
//                获取位置
                case 0:
                    if (data != null) {
                        /*网络加载添加地点的记录*/
                        loadNetData();
                        /*本地添加一条数据*/
                       /* Bundle bundle = data.getExtras();
                        String title = bundle.getString("title");
                        String address = bundle.getString("address");
                        displayPositionList(title, address);*/

                    }
                    break;
                case PHOTO_REQUEST_TAKEPHOTO:
                    try {
                        pictureAndCropManager.startPhotoZoom(UriUtils.getUriForFile(
                                new File(pictureAndCropManager.getPicturePath())), 300);
                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastUtil.showToast(ChatGroupSettingActivity.this.getApplicationContext(), R.string.chat_photo_open_fail);
                    }

                    break;

                case PHOTO_REQUEST_GALLERY:
                    if (data != null) {
                        pictureAndCropManager.startPhotoZoom(data.getData(), 300);
                    }
                    break;

                case PHOTO_REQUEST_CUT:
                    //Bitmap bitmap = BitmapFactory.decodeFile(pictureAndCropManager.getPicturePath());

                    Log.i("剪裁后头像文件路径：", pictureAndCropManager.getPicturePath());
                    if (!isNetActive()) {
                        ToastUtil.showToast(ChatGroupSettingActivity.this.getApplicationContext(), R.string.common_text_network_error_please_again);
                        return;
                    }

                    showLoading(ResStringUtil.getString(R.string.chat_uploading));

                    try {
                        PansoftCloudUtil.getCloudRes(pictureAndCropManager.getPicturePath(), new PansoftCloudUtil.UpLoadListener() {
                            @Override
                            public void getHttpUrl(Boolean isSuccess, final String url) {
                                if (isSuccess) {
                                    Log.i("ChatGroupSettingAct", "---头像在云盘服务器上的路径:" + url);
                                    GetHttpUtil.updateGroupAvatar(ChatGroupSettingActivity.this, groupId, url, new GetHttpUtil.UpdateGroupAvatarCallBack() {
                                        @Override
                                        public void updateGroupAvatarSuccess(boolean isSuccess) {
                                            if (isSuccess) {
                                                group.setAvatar(url);
//                                                imageLoader.displayImage(url, ivGroupAvatarView, options);
                                                LXGlideImageLoader.getInstance().showRoundGrouAvatar(ChatGroupSettingActivity.this, ivGroupAvatarView, url, LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_12);

                                                saveGroupInfo(group);
                                                ToastUtil.showToast(ChatGroupSettingActivity.this.getApplicationContext(), R.string.chat_update_head_success);
                                            } else {
                                                ToastUtil.showToast(ChatGroupSettingActivity.this.getApplicationContext(), R.string.chat_update_head_fail);
                                            }
                                        }
                                    });

                                    dismissLoading();
                                } else {
                                    ToastUtil.showToast(ChatGroupSettingActivity.this.getApplicationContext(), R.string.chat_update_head_fail);
                                    dismissLoading();

                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    break;
            }
            super.onActivityResult(requestCode, resultCode, data);
            try {
                reflectUtils.method("onActivityResult", this, requestCode, resultCode, data);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    /*查询群组的办公地点*/
    private void loadNetData() {
        if (null == request) {
            request = new GroupLocationHttpRequest();
        }
        request.getGroupPositions("" + groupId, new CloudDiskBasicOperation.ReturnBack() {
            @Override
            public void onReturnBack(String result) throws JSONException {
                Log.e("getGroupPositions", result + ",currentThread=" + Thread.currentThread().getName());
                if (result.startsWith("{")) {
                    Gson gson = new Gson();
                    GroupPositionsBean bean = gson.fromJson(result, GroupPositionsBean.class);
                    String result2 = bean.getResult();
                    if ("success".equals(result2)) {
                        data1 = bean.getData();
                        ll_groupsetting_address.removeAllViews();
                        if (data1.size() > 0 && null != data1) {
                            for (int i = 0; i < data1.size(); i++) {
                                String title = data1.get(i).getShortpositionname();
                                String address = data1.get(i).getPositionname();
                                displayPositionList(title, address);
                            }
                            delPositionListener();
                        }
                    } else {
                        ToastUtil.showToast(ChatGroupSettingActivity.this.getApplicationContext(), R.string.chat_data_load_fail);
                    }
                }
            }
        });
    }

    private void displayPositionList(String title, String address) {
        if (TextUtils.isEmpty(title) && TextUtils.isEmpty(address)) {
//                            ll_show_address.setVisibility(View.GONE);
        } else {
//                            ll_show_address.setVisibility(View.VISIBLE);
//                            tv_address_title.setText(title);
//                            tv_address_details.setText(address);
//                            展示地点列表
            View view = getCustomView(title, address);
            ll_groupsetting_address.addView(view);
//                            分割线
           /* View line = new View(ChatGroupSettingActivity.this);
            line.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1));
            line.setBackgroundColor(Color.parseColor("#55504a"));
            ll_groupsetting_address.addView(line);*/
        }
    }

    @NonNull
    private View getCustomView(String title, String address) {
        View view = LayoutInflater.from(ChatGroupSettingActivity.this).inflate(R.layout.item_chat_group_poi, null);
        TextView tv_title = (TextView) view.findViewById(R.id.tv_chat_group_title);
        TextView tv_address = (TextView) view.findViewById(R.id.tv_chat_group_address);
        ImageView iv_del = (ImageView) view.findViewById(R.id.iv_chat_group_click);
        View line = view.findViewById(R.id.line_item_chat_group_address);
        line.setVisibility(View.VISIBLE);
        tv_title.setText(title);
        tv_address.setText(address);
        iv_del.setVisibility(View.VISIBLE);
        iv_del.setImageResource(R.drawable.icon_del);
        return view;
    }

    /**
     * 初始化群功能列表
     */
    private void initFunctionData() {
        functionList = new ArrayList<>();
//        functionList.add(new GroupFunction("drawable://" + R.drawable.group_function_1, "公告"));
//        functionList.add(new GroupFunction("drawable://" + R.drawable.group_function_2, "文件"));
//        functionList.add(new GroupFunction("drawable://" + R.drawable.group_function_3, "相册"));
//        functionList.add(new GroupFunction("drawable://" + R.drawable.group_function_4, "话题"));
//        functionList.add(new GroupFunction("drawable://" + R.drawable.group_function_5, "群日历"));
//        functionList.add(new GroupFunction("drawable://" + R.drawable.group_function_6, "群投票"));
//        functionList.add(new GroupFunction("drawable://" + R.drawable.group_function_7, "群链接"));
//        functionList.add(new GroupFunction("drawable://" + R.drawable.group_function_8, "更多"));
       /* Map<String, StubObject> registryNodeStore = Registry.registryNodeStore;
        LogUtils.e("registryNodeStore" + registryNodeStore.toString());
        for (String key : registryNodeStore.keySet()) {
            prl += "  key=" + key + ",value=" + registryNodeStore.get(key).toString() + "/n";
        }
        LogUtils.e(prl);
        String pln = "registryStore";
        Map<String, List<StubObject>> registryStore = Registry.registryStore;
        for (String key : registryStore.keySet()) {
            pln += "  key=" + key + ",value=" + registryStore.get(key).toString() + "/n";
        }
        LogUtils.e(pln);*/
        List<StubObject> officeRoot = Registry.getRegEntryList("GroupRoot");
        ArrayList<String> titleList = new ArrayList<>();
        ArrayList<String> iconList = new ArrayList<>();
        if (null != officeRoot && officeRoot.size() > 0) {
            //所有菜单容器
            allMenuList = new ArrayList<>();
            for (int i = 0; i < officeRoot.size(); i++) {
                StubObject stubObject = officeRoot.get(i);
                Hashtable stubTable = stubObject.getStubTable();
                //利用枚举获取key:value对儿
                Enumeration<String> e2 = stubTable.keys();
                GroupRootBean bean = new GroupRootBean();
                while (e2.hasMoreElements()) {
                    String key = e2.nextElement();
                    String value = (String) stubTable.get(key);
                    switch (key) {
                        case "caption":
                            titleList.add(value);
                            break;
                        case "icon":
                            iconList.add(value);
                            bean.setIcon(value);
                            break;
                        case "viewType":
                            bean.setViewType(value);
                            break;
                        case "AndroidShow":
                            bean.setShow(value);
                            break;

                        default:
                            break;
                    }
                    /*if ("caption".equals(key)) {
                        titleList.add(value);
                    }
                    if ("icon".equals(key)) {
                        iconList.add(value);
                    }*/

                }
                allMenuList.add(bean);
            }
        }
        if (null != titleList && titleList.size() > 0) {
            for (int i = 0; i < titleList.size(); i++) {
//                functionList.add(new GroupFunction("drawable://" +iconList.get(i), titleList.get(i)));
                String filepath = AppConstant.APP_ROOT + "/res" + "/" + "unzip_res" + "/" + "menuImage/" + iconList.get(i);
                functionList.add(new GroupFunction(filepath, titleList.get(i)));
            }
        }
    }

    /**
     * 初始化群组成员
     *
     * @param from 标示来自加群的简介，还是来自群设置显示详情。根据情况显示群成员后的添加图片或者是更多图片。
     *             0为来自加群，1为群设置
     */
    public static void initGroupUsers(Group group, Context context, TextView
            tv_m_total, TextView userCountView, ExpandGridView userGridview, int from) {
        List<User> usersList = group.getUsers();
        if (usersList == null) {
            ToastUtil.showToast(context.getApplicationContext(), R.string.chatgroupsettingactivity_string10);
        } else {
            GroupOperationHelper.sortGroupUser(usersList, group.getGroupId());
            tv_m_total.setText("(" + usersList.size() + ")");
            userCountView.setText(usersList.size() + ResStringUtil.getString(R.string.chat_people));
            if (usersList != null && usersList.size() > 5) {
                usersList = usersList.subList(0, 5);
            }
            GridUserAdapter usersAdapter = new GridUserAdapter(context, usersList, group, from);
            userGridview.setAdapter(usersAdapter);
        }
    }

    /**
     * 用群成员list来设置
     */
    public static void setGroupUsers(List<User> usersList, Context context, TextView
            tv_m_total, TextView userCountView, ExpandGridView userGridview, int from, int groupId) {
        if (usersList == null) {
            ToastUtil.showToast(context.getApplicationContext(), R.string.chatgroupsettingactivity_string10);
        } else {
            GroupOperationHelper.sortGroupUser(usersList, groupId);
            tv_m_total.setText("(" + usersList.size() + ")");
            userCountView.setText(usersList.size() + ResStringUtil.getString(R.string.chat_people));
            if (usersList != null && usersList.size() > 5) {
                usersList = usersList.subList(0, 5);
            }
            GridUserAdapter usersAdapter = new GridUserAdapter(context, usersList, groupId, from);
            userGridview.setAdapter(usersAdapter);
        }
    }

    /**
     * 设置群组名，昵称等view
     */
    private void setUpView() {
        User user = GroupNameUtil.getGroupUser(groupId, Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
        String myGroupNickName = GroupNameUtil.getGroupUserName(user);
        tv_myGroupName.setText(myGroupNickName);
    }

    //todo 设置上半部分的view信息
    public static void setTopView(Group group, TextView tv_groupname, TextView
            tvGroupIdView, TextView tv_titleView, TextView tv_qunjieshao) {
        tv_groupname.setText(group.getGroupName());//群组名
        tv_titleView.setText(group.getGroupName());

        tvGroupIdView.setText(tv_groupname.getContext().getResources().getString(R.string.chatgroupsettingactivity_qh) + group.getGroupId());//群号
        // Bitmap bitmap = FastBlurUtil.doBlur(imageLoader.loadImageSync(avatar), 40, false);
        //  ivBgView.setImageBitmap(bitmap);
        //ivBgView.setAlpha(70);
        // blur(imageLoader.loadImageSync(avatar), ivBgView);
        //设置群介绍
        try {
            long createTime = group.getCreateTime();
            Date date = new Date(createTime);
            SimpleDateFormat sdf = new SimpleDateFormat(tv_groupname.getContext().getResources().getString(R.string.chatgroupsettingactivity_string6));
            String text = sdf.format(date);
            tv_qunjieshao.setText(text);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

//    public static String getAvatar(Group group) {
//        String avatar = group.getAvatar();
//        if ("".equals(avatar)) {
//            avatar = "drawable://" + +R.drawable.default_groupavatar;
//        }else if (avatar.contains("http")) {
//
//        } else {
//            avatar = "file://" + avatar;
//        }
//        return avatar;
//    }


    @Override
    protected void onResume() {
        super.onResume();
        group = WeChatDBManager.getInstance().getGroupWithUsers(groupId);
        if (group.getUsers().size() == 0) {
            if (!isNetActive()) {
                initData();
                return;
            }
            getGroupUser();
        } else {
            initData();
        }
    }


    /* 为群组删除办公地点*/
    private void delPositionListener() {
        int count = ll_groupsetting_address.getChildCount();
        for (int i = 0; i < count; i++) {
            final View childAt = ll_groupsetting_address.getChildAt(i);
            if (null != childAt) {
                final ImageView iv_del = (ImageView) childAt.findViewById(R.id.iv_chat_group_click);
                final TextView tv_del = (TextView) childAt.findViewById(R.id.tv_chat_group_title);
                if (iv_del != null) {
                    final int finalI = i;
                    if (i > ll_groupsetting_address.getChildCount() - 1) {
                        return;
                    }
                    iv_del.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            iv_del.setClickable(false);
//                            删除前判断身份权限
                            User tempUser = null;
                            if (group.getUsers() != null) {
                                for (User user : group.getUsers()) {
//                    当前登录用户
                                    if (user.getId() == Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))) {
                                        tempUser = user;
                                    }
                                }
//                判断当前用户身份：是否是群主或管理员
                                if (group.getCreateId() != Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))
                                        && tempUser.getGroupUserType() != User.GROUPCREATOR
                                        && tempUser.getGroupUserType() != User.GROUPMANAGER) {
//                    ToastUtil.showToast(ChatGroupSettingActivity.this, "只有群主或者管理员才能进行此操作");
                                    AlertDialog.Builder builder = new AlertDialog.Builder(ChatGroupSettingActivity.this);
                                    builder.setTitle(R.string.common_text_hint);
                                    builder.setMessage(ResStringUtil.getString(R.string.chat_only_owner_admin_this_operation));
                                    builder.setCancelable(false);
                                    builder.setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            iv_del.setClickable(true);
                                            dialog.dismiss();
                                        }
                                    });
                                    builder.create().show();
                                } else {
//                                    if (finalI > ll_groupsetting_address.getChildCount() - 1) {
//                                        return;
//                                    }
                                    AlertDialog.Builder builder = new AlertDialog.Builder(ChatGroupSettingActivity.this);
//                                builder.setTitle(R.string.common_text_hint);
                                    builder.setMessage(ResStringUtil.getString(R.string.chat_sure_delete) + data1.get(finalI).getShortpositionname() + ResStringUtil.getString(R.string.chat_ma));
                                    builder.setCancelable(false);
                                    builder.setNegativeButton(R.string.common_text_cancel, null);
                                    builder.setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            int id = data1.get(finalI).getId();
                                            delGroupPosition(id);
                                        }
                                    });
                                    iv_del.setClickable(true);
                                    builder.create().show();
                                }


                            }
                        }
                    });
                }
            }

        }
    }

    // 显示群功能
    @SuppressLint("ClickableViewAccessibility")
    private void showFunction(final List<GroupFunction> functionList) {
        adapter = new GridAdapter(this, functionList);
        gridview.setAdapter(adapter);

        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String name = functionList.get(position).getName();
                String viewType = allMenuList.get(position).getViewType();
                if (null != viewType) {
                    if ("display".equals(viewType)) {
//                                                    跳转页面
                        String aName = allMenuList.get(position).getShow();
                        AbFragmentManager abFragmentManager = new AbFragmentManager(ChatGroupSettingActivity.this);
                        StubObject stubObject = new StubObject();
                        Hashtable<String, String> hashtable = new Hashtable<String, String>();
                        hashtable.put("groupId", group.getGroupId() + "");
                        hashtable.put("groupName", group.getGroupName());
                        hashtable.put("AndroidShow", aName);
                        stubObject.setStubTable(hashtable);
                        try {
                            abFragmentManager.startActivity(stubObject, 0, 0);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else if ("webView".equals(viewType)) {
//                                                    webview 展示

                    }
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        // 群组消息免打扰
        if (id == R.id.switch_notification) {
            updateGroupBother();
        } else if (id == R.id.re_clear) {
//            clearGroupHistory();
//            // 按照你们要求必须有个提示，防止记录太少，删得太快，不提示
//            new Handler().postDelayed(new Runnable() {
//
//                public void run() {
//                    dismissProgressDialog();
//                }
//
//            }, 2000);
        } else if (id == R.id.re_change_groupname) {

            boolean isManager = isManager();
            if (group.getCreateId() == Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))
                    || isManager) {
                showNameAlert();
            } else {
                ToastUtil.showToast(ChatGroupSettingActivity.this.getApplicationContext(), R.string.chat_only_owner_admin_update_group_name);

            }

        } else if (id == btn_exit_grp && exitBtn != null) {
            if (!isNetActive()) {
                ToastUtil.showToast(ChatGroupSettingActivity.this.getApplicationContext(), R.string.common_text_please_check_your_network);
                return;
            }
            if (group.getCreateId() == Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))) {
                //解散群组
                showDissolveAlert();
            } else {
                showLoading(R.string.chat_signing_out);
                try {
                    GetHttpUtil.userQuitGroup(ChatGroupSettingActivity.this, group.getGroupId(), new GetHttpUtil.ReqCallBack() {
                        @Override
                        public void onReqSuccess(Object result) {
                            //退出成功
                            onUserQuitGroupResult(true);
                        }

                        @Override
                        public void onReqFailed(String errorMsg) {
                            //退出失败
                            onUserQuitGroupResult(false);
                        }
                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        } else if (id == R.id.switch_top) {
            group.setIsTop(switchTop.isChecked());
            //  WeChatDBManager.getInstance().insertOrUpdateGroup(group);
            saveGroupInfo(group);

        } else if (id == R.id.re_mygroupremark) {
            showMyGroupRemarkAlert();
        } else if (id == R.id.ll_groupUserlayout) {
            Intent intent = new Intent(ChatGroupSettingActivity.this, ChatGroupUserActivity.class);
            intent.putExtra("id", groupId);
            startActivity(intent);
        } else if (id == R.id.ll_add_address) {
            User tempUser = null;
            if (group.getUsers() != null) {
                for (User user : group.getUsers()) {
//                    当前登录用户
                    if (user.getId() == Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))) {
                        tempUser = user;
                    }
                }
                if (tempUser == null) {
                    ToastUtil.showToast(ChatGroupSettingActivity.this, R.string.chat_return_retry);
                    return;
                }
//                判断当前用户身份：是否是群主或管理员
                if (group.getCreateId() != Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))
                        && tempUser.getGroupUserType() != User.GROUPCREATOR && tempUser.getGroupUserType() != User.GROUPMANAGER) {
//                    ToastUtil.showToast(ChatGroupSettingActivity.this, "只有群主或者管理员才能进行此操作");
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle(R.string.common_text_hint);
                    builder.setMessage(ResStringUtil.getString(R.string.chat_only_owner_admin_this_operation));
                    builder.setCancelable(false);
                    builder.setPositiveButton(R.string.common_text_confirm, null);
                    builder.show();
                } else {
//            添加办公地点
                    Intent intent = new Intent();
                    intent.putExtra("groupid", groupId);

                    ChatActivitySkipUtil.startSetGroupAddressActivity(ChatGroupSettingActivity.this,
                            intent, 0);
                }
            }

        } else if (id == R.id.switch_free_addgroup) {
            if (GroupNameUtil.getUserRoleInGroup(groupId, Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))) != User.GROUPCREATOR
                    && GroupNameUtil.getUserRoleInGroup(groupId, Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)))
                    != User.GROUPMANAGER) {
                switchFreeAddgroup.setChecked(!switchFreeAddgroup.isChecked());
                ToastUtil.showToast(getApplicationContext(), R.string.chat_you_not_have_authority);
                return;
            }
            setFreeAddGroup();
            //自由加群
        } else if (id == R.id.switch_all_no_speak) {
            //全员禁言
            if (GroupNameUtil.getUserRoleInGroup(groupId, Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))) != User.GROUPCREATOR
                    && GroupNameUtil.getUserRoleInGroup(groupId, Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)))
                    != User.GROUPMANAGER) {
                switchAllNoSpeak.setChecked(!switchAllNoSpeak.isChecked());
                ToastUtil.showToast(getApplicationContext(), R.string.chat_you_not_have_authority);
                return;
            }
            setAllNoSpeak();
        } else if (id == R.id.re_share_group) {
            //分享该群
//            if ("".equals(group.getEnglihName())) {
//                ToastUtil.showToast(getApplicationContext(), "管理员暂未设置群英文名称，不能分享");
//
//                return;
//            }
            shareGroup();
        } else if (id == R.id.tv_group_english_name) {
            //群英文名
            if (GroupNameUtil.userIsManager(groupId)) {
                updateGroupKey();
            } else {
                ToastUtil.showToast(ChatGroupSettingActivity.this.getApplicationContext(), R.string.chat_group_setting_string1);
            }

        } else if (id == R.id.re_group_recommend) {
            //群公告
            GroupRecommendActivity.start(ChatGroupSettingActivity.this, groupId, group.getRecommond());

        }

    }

    private void updateGroupBother() {
        // 消息置顶
        showLoading(R.string.configuring_friend_info);
        GetHttpUtil.updateGroupBother(this, group.getGroupId(), switchNotification.isChecked(),
                new JFCommonRequestManager.ReqCallBack<String>() {
                    @Override
                    public void onReqSuccess(String result) {
                        dismissLoading();
                        //更新数据库
                        group.setIsBother(switchNotification.isChecked());
                        WeChatDBManager.getInstance().insertOrUpdateGroup(group);
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
                        dismissLoading();
                        switchNotification.setChecked(!switchNotification.isChecked());
                        ToastUtils.showShort(R.string.alter_friend_config_fail_retry);
                    }
                });

    }

    private void updateGroupKey() {

        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        RelativeLayout layout = (RelativeLayout) inflater.inflate(
                R.layout.social_alertdialog, null);
        dialog.setView(layout);
        final EditText ed_name = (EditText) layout
                .findViewById(R.id.ed_name);
        ed_name.setText(tvGroupEnglishName.getText());
        ed_name.setSelection(tvGroupEnglishName.getText().length());
        final String regular = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        ed_name.setKeyListener(new DigitsKeyListener() {
            @Override
            public int getInputType() {
                return InputType.TYPE_CLASS_TEXT;
            }

            @Override
            protected char[] getAcceptedChars() {
                char[] ac = regular.toCharArray();
                return ac;
            }
        });

        dialog.setTitle(getResources().getString(R.string.wechatview_input_group_english_name));
        dialog.setPositiveButton(R.string.common_text_confirm,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        newName = ed_name.getText().toString().trim();
                        if (TextUtils.isEmpty(newName)) {
                            ToastUtils.showShort(R.string.common_text_input_not_null);
                        } else {
                            dialog.cancel();
                            HashMap<String, String> map = new HashMap<>();
                            map.put("userId", EnvironmentVariable.getProperty(CHAT_USER_ID));
                            map.put("passWord", EnvironmentVariable.getProperty(CHAT_PASSWORD));
                            map.put("groupId", groupId + "");
                            map.put("groupKey", newName);
                            showLoading(R.string.configuring_friend_info);
                            JFCommonRequestManager.getInstance(ChatGroupSettingActivity.this)
                                    .requestGetByAsyn(TAG, ROOTURL + "/IMServer/group/updateGroupKey"
                                            , map, new JFCommonRequestManager.ReqCallBack<String>() {
                                                @Override
                                                public void onReqSuccess(String result) {
                                                    dismissLoading();
                                                    try {
                                                        JSONObject jsonObject = new JSONObject(result);
                                                        if (jsonObject.optString("result", "").equals("success")) {
                                                            group.setEnglihName(newName);
                                                            saveGroupInfo(group);
                                                            tvGroupEnglishName.setText(newName);
                                                            ToastUtil.showToast(getApplicationContext(), R.string.chat_set_success);

                                                        } else {

                                                            ToastUtil.showToast(getApplicationContext(),
                                                                    jsonObject.optString("msg", ResStringUtil.getString(R.string.chat_set_fail)));
                                                        }
                                                    } catch (JSONException e) {
                                                        e.printStackTrace();
                                                    }
                                                }

                                                @Override
                                                public void onReqFailed(String errorMsg) {
                                                    dismissLoading();
                                                    ToastUtil.showToast(getApplicationContext(), R.string.chat_set_fail);
                                                }

                                                @Override
                                                public int hashCode() {
                                                    return super.hashCode();
                                                }
                                            });

                        }
                    }


                });
        dialog.setNegativeButton(R.string.common_text_cancel, null);
        dialog.show();

    }

    // TODO: 2018/10/17  
    private void shareGroup() {
        try {
            //UshareHelper OpenShareHelper
            String description = ResStringUtil.getString(R.string.chat_come_join) + group.getGroupName() + ResStringUtil.getString(R.string.chat_tribe);

            String url = EnvironmentVariable.getProperty("groupUrlScheme")
                    + (group.getEnglihName().equals("") ? groupId : group.getEnglihName());
            reflectUtils = ReflectUtils.reflect(EnvironmentVariable.getProperty("shareClass", "")).newInstance();
            reflectUtils.method("share", this, url,
                    group.getGroupName(), R.drawable.wechat_icon_launcher, description, groupId,
                    new UshareHelper.ShareListener() {
                        @Override
                        public void share(int type) {

                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setFreeAddGroup() {
        final int newGrouType = switchFreeAddgroup.isChecked() ? 1 : 0;
        showLoading(R.string.configuring_friend_info);
        GetHttpUtil.updateAddGroupFreedom(getApplicationContext(), groupId, newGrouType, new JFCommonRequestManager.ReqCallBack<String>() {
            @Override
            public void onReqSuccess(String result) {
                dismissLoading();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.optString("result", "fail").equals("success")) {
                        group.setGroupType(newGrouType);
                        saveGroupInfo(group);
                        ToastUtil.showToast(getApplicationContext(), R.string.chat_set_success);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    ToastUtil.showToast(getApplicationContext(), R.string.chat_set_fail);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                dismissLoading();
                ToastUtil.showToast(getApplicationContext(), R.string.chat_set_fail);
            }
        });
    }

    private void setAllNoSpeak() {
        final int newNoSpeak = switchAllNoSpeak.isChecked() ? 1 : 0;
        showLoading(R.string.configuring_friend_info);
        GetHttpUtil.updateGroupNoSpeak(getApplicationContext(), groupId, newNoSpeak, new JFCommonRequestManager.ReqCallBack<String>() {
            @Override
            public void onReqSuccess(String result) {
                dismissLoading();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.optString("result", "fail").equals("success")) {
                        group.setBanSpeak(newNoSpeak == 1);
                        saveGroupInfo(group);
                        ToastUtil.showToast(getApplicationContext(), R.string.chat_set_success);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    ToastUtil.showToast(getApplicationContext(), R.string.chat_set_fail);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                dismissLoading();
                ToastUtil.showToast(getApplicationContext(), R.string.chat_set_fail);
            }
        });
    }

    //解散群组
    private void showDissolveAlert() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.common_text_hint);
        builder.setMessage(R.string.chatgroupsettingactivity_string11);
        builder.setCancelable(false);
        builder.setNegativeButton(R.string.common_text_cancel, null);
        builder.setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                showLoading(ResStringUtil.getString(R.string.common_text_please_wait));
                GetHttpUtil.dissolveGroup(ChatGroupSettingActivity.this, groupId, new GetHttpUtil.ReqCallBack() {
                    @Override
                    public void onReqSuccess(Object result) {
                        deleteGroup();
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
                        ToastUtil.showToast(ChatGroupSettingActivity.this.getApplicationContext(), errorMsg);
                    }
                });
            }
        });
        builder.show();
    }

    /**
     * 保存群组信息
     *
     * @param group
     */
    private void saveGroupInfo(final Group group) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (this) {
                    WeChatDBManager.getInstance().insertOrUpdateGroup(group);
                }

            }
        }).start();
    }

    /**
     * 清空群聊天记录
     */
    public void clearGroupHistory() {
        showLoading(ResStringUtil.getString(R.string.chat_clearing_message));
        GetDBHelper.getInstance().getDBHelper().getWritableDatabase().execSQL("update message  set enable = 0 where toUserType = 1 and  (fromUserId =" + groupId + " or toUserId =" + groupId + ")");
        JFMessageManager.getInstance().getMessageList(groupId, StructFactory.TO_USER_TYPE_GROUP).clear();
        //TODO 删除列表数据
        ChatListItem chatListItem = new ChatListItem();
        chatListItem.setChatType(StructFactory.TO_USER_TYPE_GROUP);
        chatListItem.setUserId(groupId);
        WeChatDBManager.getInstance().deleteChatListiItem(chatListItem);


    }

    private void showNameAlert() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        RelativeLayout layout = (RelativeLayout) inflater.inflate(
                R.layout.social_alertdialog, null);
        dialog.setView(layout);
        final EditText ed_name = (EditText) layout
                .findViewById(R.id.ed_name);
        ed_name.setText(group.getGroupName());
        ed_name.setSelection(group.getGroupName().length());
        dialog.setTitle(getResources().getString(R.string.chatgroupsettingactivity_string8));
        dialog.setPositiveButton(R.string.common_text_confirm,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        newName = ed_name.getText().toString().trim();
                        if (TextUtils.isEmpty(newName)) {
                            return;
                        } else {
                            try {
                                showLoading(R.string.configuring_friend_info);
                                GetHttpUtil.updateGroupName(ChatGroupSettingActivity.this, groupId, newName, new GetHttpUtil.ReqCallBack() {
                                    @Override
                                    public void onReqSuccess(Object result) {
                                        dismissLoading();
                                        //修改成功
                                        onUpdateGroupNameResult(true);
                                    }

                                    @Override
                                    public void onReqFailed(String errorMsg) {
                                        dismissLoading();
                                        //修改失败
                                        onUpdateGroupNameResult(false);

                                    }
                                });
                            } catch (JSONException e) {
                                e.printStackTrace();
                                dismissLoading();
                            }
                        }
                        dialog.cancel();
                    }


                });

        dialog.setNegativeButton(R.string.common_text_cancel,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }

                });
        dialog.show();

    }

    private void showMyGroupRemarkAlert() {

        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LinearLayout layout = (LinearLayout) inflater.inflate(
                R.layout.chatroomset_alertdialog, null);
        dialog.setView(layout);
        final EditText ed_name = (EditText) layout
                .findViewById(R.id.ed_name);
        ed_name.setText(tv_myGroupName.getText());
        ed_name.setSelection(tv_myGroupName.getText().length());
        dialog.setTitle(getResources().getString(R.string.chatgroupsettingactivity_string1));

        dialog.setPositiveButton(R.string.common_text_confirm,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        final String myGroupRemark = ed_name.getText().toString().trim();

                        if (TextUtils.isEmpty(myGroupRemark)) {
                            return;
                        } else {
                            try {
                                showLoading(R.string.configuring_friend_info);
                                GetHttpUtil.updateOwnGroupUserRemark(ChatGroupSettingActivity.this, groupId, myGroupRemark,
                                        new GetHttpUtil.UpdateUserInfoCallBack() {
                                            @Override
                                            public void updateSuccess(boolean isSuccess) {
                                                dismissLoading();
                                                if (isSuccess) {
                                                    User tempUser = WeChatDBManager.getInstance().getGroupUserInfo(groupId,
                                                            Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
                                                    tempUser.setOtherGroupRemark(myGroupRemark);
                                                    tempUser.setOwnGroupRemark(myGroupRemark);
                                                    WeChatDBManager.getInstance().insertOrUpdateMyGroupUser(groupId, tempUser);
                                                    tv_myGroupName.setText(myGroupRemark);
                                                    ToastUtil.showToast(ChatGroupSettingActivity.this.getApplicationContext(), R.string.chat_update_success);
                                                } else {
                                                    ToastUtil.showToast(ChatGroupSettingActivity.this.getApplicationContext(), R.string.chat_update_fail);
                                                }
                                            }
                                        });
                            } catch (Exception e) {
                                dismissLoading();
                                e.printStackTrace();
                            }
                        }
                        dialog.cancel();
                    }


                });

        dialog.setNegativeButton(R.string.common_text_cancel,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }

                });
        dialog.show();


//        // 设置能弹出输入法
//        dlg.getWindow().clearFlags(
//                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

    }


    @Override
    public void back(View view) {
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_OK);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        instance = null;
        //释放分享，避免内存泄漏
        try {
            if (reflectUtils == null) {
                return;
            }
            reflectUtils.method("release", this);
        } catch (Exception e) {
            LogUtils.e("reflectUtils.method(\"release\") error");
        }
    }


    public void onGetGroupUserSuccess(List<User> groupUsers, int groupId) {
        group = WeChatDBManager.getInstance().getGroupWithUsers(groupId);
        initData();
    }

    /**
     * 群功能gridadapter
     *
     * @author yqs
     */
    private class GridAdapter extends BaseAdapter {

        public boolean isInDeleteMode;
        private List<GroupFunction> objects;
        Context context;

        public GridAdapter(Context context, List<GroupFunction> objects) {

            this.objects = objects;
            this.context = context;

        }

        @Override
        public View getView(final int position, View convertView,
                            final ViewGroup parent) {
            GroupFunction function = objects.get(position);
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(
                        R.layout.social_chatgroupfunctiongridview_item, null);
            }
            ImageView iv_avatar = (ImageView) convertView
                    .findViewById(R.id.iv_avatar);
            TextView tv_username = (TextView) convertView
                    .findViewById(R.id.tv_username);

            tv_username.setText(function.getName());

//            imageLoader.displayImage("file://" + function.getImage(), iv_avatar, options);
            LXGlideImageLoader.getInstance().displayImage(ChatGroupSettingActivity.this, iv_avatar, "file://" + function.getImage());

            return convertView;
        }

        @Override
        public int getCount() {
            return objects.size();

        }

        @Override
        public Object getItem(int position) {
            return objects.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

    }


    private void deleteGroup() {
        WeChatDBManager.getInstance().quitGroup(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)),
                group.getGroupId());

        //TODO 删除列表数据
        clearBadgem(group.getGroupId(), StructFactory.TO_USER_TYPE_GROUP);


        //跳转到首页
        try {
            String className = getResources().getString(R.string.from_group_backto_first);
            Class clazz = Class.forName(className);
            Intent myIntent = new Intent(this, clazz);
            startActivity(myIntent);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        ToastUtil.showToast(ChatGroupSettingActivity.this.getApplicationContext(), R.string.chat_sign_out_success);
        dismissLoading();
        finish();
    }

    private void clearBadgem(int id, byte chatType) {

        //清除当前聊天的角标
        ChatListItem chatListItem = WeChatDBManager.getInstance().getChatListItem(id, chatType);

        JFMessageManager.getInstance().unreadZero(id, chatType);
        int unReadCount = JFMessageManager.getInstance().getUnReadCount(id, chatType);
        if (unReadCount == 0) {
            unReadCount = -1;
        }
        if (chatListItem != null) {
            chatListItem.setBadgernum(unReadCount);
            WeChatDBManager.getInstance().deleteChatListiItem(chatListItem);
            //ChatListItemUtil.updateUnreadCount(unReadCount, 0);
            EventBus.getDefault().post(new MessageEvent(chatListItem, MessageEvent.DELETE));

        }


    }

    //退群结果
    public void onUserQuitGroupResult(boolean isSuccess) {
        dismissLoading();
        if (isSuccess) {
            deleteGroup();
        } else {
            if (Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)) == group.getCreateId()) {
                ToastUtil.showToast(ChatGroupSettingActivity.this.getApplicationContext(), R.string.chat_creators_not_retry);
                return;
            }
            ToastUtil.showToast(ChatGroupSettingActivity.this.getApplicationContext(), R.string.chat_sign_out_fail);
        }

    }

    //更改群名称结果
    public void onUpdateGroupNameResult(boolean isSuccess) {
        if (isSuccess) {
            tv_groupname.setText(newName);
            tv_titleView.setText(newName);
            group.setGroupName(newName);
            WeChatDBManager.getInstance().insertOrUpdateGroup(group);
            notifyChange(group);
            ToastUtil.showToast(ChatGroupSettingActivity.this, R.string.chat_update_success);
        } else {
            ToastUtil.showToast(ChatGroupSettingActivity.this, R.string.chat_update_fail);
        }
    }

    /**
     * 异步加载头像
     */
//    public void initImageLoader() {
//        // 初始化异步加载图片的类
//        imageLoader = ImageLoader.getInstance();
//        // 设置异步加载图片的配置信息
//        options = ImageUtil.getImageLoaderOptions(R.drawable.default_useravatar);
//
//    }
    @Override
    protected void onStop() {
        super.onStop();
        notifyChange(group);
    }

    private void notifyChange(Group group) {
        ChatListItem chatListItem = WeChatDBManager.getInstance().getChatListItem(group.getGroupId(), 2);
        if (chatListItem != null) {
            EventBus.getDefault().post(new MessageEvent(chatListItem, MessageEvent.UPDATE));
        }
    }


    //获取群组信息
    private void getGroupInfo() {
        GetHttpUtil.getGroupById(this, groupId, new GetHttpUtil.ReqCallBack<Group>() {
            @Override
            public void onReqSuccess(Group serverGroup) {
                if (!"".equals(serverGroup.getAvatar()) && serverGroup.getAvatar().startsWith("http")) {
                    group.setAvatar(serverGroup.getAvatar());
                }
                group.setBanSpeak(serverGroup.isBanSpeak());
                group.setRecommond(serverGroup.getRecommond());
                group.setGroupType(serverGroup.getGroupType());
                group.setGroupName(serverGroup.getGroupName());
                group.setEnglihName(serverGroup.getEnglihName());
                getGroupUser();
            }

            @Override
            public void onReqFailed(String errorMsg) {
                refreshLayout.finishRefresh(100);
            }
        }, false);
    }

    //获取群成员
    private void getGroupUser() {
        try {
            GetHttpUtil.getGroupUsers(ChatGroupSettingActivity.this, group.getGroupId(), new GetHttpUtil.ReqCallBack<List<User>>() {
                @Override
                public void onReqSuccess(List<User> users) {
                    if (isDestroyed()) {
                        return;
                    }
                    refreshLayout.finishRefresh(100);
                    onGetGroupUserSuccess(users, group.getGroupId());
                }

                @Override
                public void onReqFailed(String errorMsg) {
                    if (isDestroyed()) {
                        return;
                    }
                    refreshLayout.finishRefresh(100);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
