package com.efounder.chat.fragment;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.Nullable;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
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.activity.AddFriendsOneActivity;
import com.efounder.chat.activity.ChatLocalSearchActivity;
import com.efounder.chat.activity.ChatRoomActivity;
import com.efounder.chat.activity.GroupNotifacationActivity;
import com.efounder.chat.activity.NewFriendsActivity;
import com.efounder.chat.activity.TransformFragmentActivity;
import com.efounder.chat.adapter.ContactsSortAdapter;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.model.AppConstant;
import com.efounder.chat.model.ContactTopModel;
import com.efounder.chat.model.TabMenuClickEvent;
import com.efounder.chat.model.UpdateBadgeViewEvent;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.ChatActivitySkipUtil;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.view.CommonOtherPopWindow;
import com.efounder.chat.widget.BadgeView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.mobilecomps.contacts.ChineseCharacterUtils;
import com.efounder.mobilecomps.contacts.ClearEditText;
import com.efounder.mobilecomps.contacts.HanyuParser;
import com.efounder.mobilecomps.contacts.PinyinComparator;
import com.efounder.mobilecomps.contacts.SideBar;
import com.efounder.mobilecomps.contacts.SideBar.OnTouchingLetterChangedListener;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.service.Registry;
import com.efounder.thirdpartycomps.stickylistheaders.StickyListHeadersListView;
import com.efounder.util.AbFragmentManager;
import com.efounder.util.AppContext;
import com.efounder.util.EnvSupportManager;
import com.efounder.utils.ResStringUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import static com.efounder.frame.utils.Constants.KEY_F_ZGBH;
import static com.efounder.frame.utils.Constants.KEY_SETTING_APPID;

/**
 * 联系人列表(通讯录)
 *
 * @author hudq
 */
public class ContactsFragment extends BaseFragment implements
        AdapterView.OnItemClickListener,
        StickyListHeadersListView.OnHeaderClickListener,
        StickyListHeadersListView.OnStickyHeaderOffsetChangedListener,
        StickyListHeadersListView.OnStickyHeaderChangedListener {

    private final static String TAG = "ContactsFragment";

    private StickyListHeadersListView stickyList;
    private SideBar sideBar;
    private TextView dialog;
    private View rootView;
    private ContactsSortAdapter adapter;
    private ClearEditText mClearEditText;
    private TextView searchMore;
    private boolean fadeHeader = true;

    private int newFriendCount = 0;
    private int groupNotiveCount = 0;
    //// TODO: 2017/10/21  为了兼容之前的，如果本地没有配置菜单，按以前方式展示，如果配置了，按新的方式展示次啊单
    private boolean haveConfigMenu = false;//默认没有配置菜单

    //数据源
    private List<User> sourceDataList;

    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;

    private MyHandler myHandler;
    private LinearLayout topLayout;//顶部view
    private LinearLayout topContentLayout;

    List<StubObject> topMenuList = null;
    List<ContactTopModel> topModelList = null;
    LayoutInflater inflater = null;

    String name;//搜索框内容


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //注册eventbus
        EventBus.getDefault().register(this);
        myHandler = new MyHandler();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_contacts, container,
                false);
        this.inflater = inflater;
        initViews(rootView);
        initData();
        return rootView;
    }

    @Override
    public void onResume() {
        reloadData();
        mClearEditText.setText("");
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //初始化本地数据
    private void initData() {
        // 实例化汉字转拼音类
        pinyinComparator = new PinyinComparator();
        sourceDataList = new ArrayList<User>();
        newFriendCount = WeChatDBManager.getInstance().getNewFriendUnread();
        groupNotiveCount = WeChatDBManager.getInstance().getGroupNoticveUnreadCount();
        adapter = new ContactsSortAdapter(getActivity(), sourceDataList);
        stickyList.setAdapter(adapter);
    }


    private void initViews(View view) {
        initTitleBar();
        sideBar = (SideBar) view.findViewById(R.id.sidrbar);
        dialog = (TextView) view.findViewById(R.id.dialog);
        searchMore = (TextView) view.findViewById(R.id.tv_search_more);
        sideBar.setTextView(dialog);
        //跳转到添加好友搜索界面 kongmeng
        searchMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), AddFriendsOneActivity.class);
                intent.putExtra("name", name);
                getContext().startActivity(intent);
            }
        });
        // 设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    stickyList.setSelection(position);
                }
            }
        });

        stickyList = (StickyListHeadersListView) view.findViewById(R.id.country_lvcountry);
        stickyList.setOnItemClickListener(this);
        stickyList.setOnHeaderClickListener(this);
        stickyList.setOnStickyHeaderChangedListener(this);
        stickyList.setOnStickyHeaderOffsetChangedListener(this);
        // stickyList.addHeaderView(getLayoutInflater().inflate(R.layout.list_header,
        // null));
        // stickyList.addFooterView(getLayoutInflater().inflate(R.layout.list_footer,
        // null));
        // stickyList.setEmptyView(findViewById(R.id.empty));
        stickyList.setDrawingListUnderStickyHeader(true);
        stickyList.setAreHeadersSticky(true);
        stickyList.setStickyHeaderTopOffset(-10);
        stickyList.setFastScrollEnabled(true);
        stickyList.setFastScrollAlwaysVisible(true);
        //stickyList.addHeaderView(topLayout);

        mClearEditText = (ClearEditText) view.findViewById(R.id.filter_edit);
        mClearEditText.setFocusable(false);
        //这里我们直接跳转搜索
        mClearEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //进入搜索界面
                ChatLocalSearchActivity.start(getActivity());
            }
        });
        //去企业通讯录搜索更多
        // 根据输入框输入值的改变来过滤搜索
        mClearEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                // 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                if (topContentLayout != null) {
                    topContentLayout.setVisibility(View.GONE);
                    searchMore.setVisibility(View.GONE);
                }
                filterData(s.toString());
                name = s.toString();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().equals("")) {
                    searchMore.setVisibility(View.GONE);
                    if (topContentLayout != null) {
                        topContentLayout.setVisibility(View.VISIBLE);
                    }
                }
            }
        });
        //EditText获取焦点后隐藏掉提示文字
        mClearEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                ClearEditText editText = (ClearEditText) v;
                String hint = null;
                int id = v.getId();
                if (id == R.id.filter_edit) {
                    if (hasFocus) {
                        hint = editText.getHint().toString();
                        editText.setTag(hint);
                        editText.setHint("");
                    } else {
                        hint = editText.getTag().toString();
                        editText.setHint(hint);
                    }
                }
            }
        });
    }

    //初始化标题栏
    private void initTitleBar() {
        RelativeLayout titleBarLayout;
        ImageView ivBack;
        TextView tvTitle;
        tvTitle = (TextView) rootView.findViewById(R.id.tv_title);

        //导入粉丝
        final ImageView ivImport;
        titleBarLayout = (RelativeLayout) rootView.findViewById(R.id.title);
        ivBack = (ImageView) rootView.findViewById(R.id.iv_back);
        ivImport = (ImageView) rootView.findViewById(R.id.iv_detail);
        //FIXME 星际通讯才显示这些
        if (isAlone() && EnvironmentVariable.getProperty(KEY_SETTING_APPID, "").equals(AppContext.getInstance()
                .getString(R.string.special_appid))) {
            titleBarLayout.setVisibility(View.VISIBLE);
            StubObject stubObject = (StubObject) getArguments().getSerializable("stubObject");
            if (stubObject.getString("menuType", "").equals("import")) {
                ivImport.setVisibility(View.VISIBLE);
                ivImport.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final CommonOtherPopWindow commonOtherPopWindow = new CommonOtherPopWindow(getActivity());
                        commonOtherPopWindow.addMenuButton(ResStringUtil.getString(R.string.openplanet_title_import_fans), R.drawable.open_plant_import_fans, true)
                                .setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        //给星际星球使用
                                        try {
                                            String className = getResources().getString(R.string.pageslidetab_import_activity);
                                            Class class1 = Class.forName(className);
                                            Intent intent = new Intent(getActivity(), class1);
                                            //intent.putExtra("number", user.getName());
                                            intent.putExtra("number", EnvironmentVariable.getUserName());
                                            intent.putExtra("hasRightButton", "false");
                                            startActivity(intent);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                        commonOtherPopWindow.dismiss();
                                    }
                                });
                        commonOtherPopWindow.showPopupWindow(ivImport);
                    }
                });

            }

            if (stubObject != null) {
                tvTitle.setText(stubObject.getCaption());
            }

            ivBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getActivity().finish();
                }
            });
        }
    }


    //加载数据库的数据
    private void reloadData() {
        sourceDataList.clear();
        List<User> myList = new ArrayList<User>();
        myList.addAll(WeChatDBManager.getInstance().getallFriends());
        sourceDataList.addAll(filledData(myList));
        // 根据a-z进行排序源数据
        Collections.sort(sourceDataList, pinyinComparator);
        loadTopView();
        if (!haveConfigMenu) {
            //如果没有配置菜单，使用之前的方式 加入三个菜单
            for (int i = 0; i < 3; i++) {
                User user = new User();
                if (i == 0) {
                    user.setNickName(ResStringUtil.getString(R.string.wechatview_new_friend));
                    user.setReMark(ResStringUtil.getString(R.string.wechatview_new_friend));
                    user.setId(-100);
                    user.setSortLetters("↑");
                    user.setBadgenum(newFriendCount);
                } else if (i == 1) {
                    user.setNickName(ResStringUtil.getString(R.string.chat_room_name));
                    user.setReMark(ResStringUtil.getString(R.string.chat_room_name));
                    user.setId(-100);
                    user.setSortLetters("↑");
                } else if (i == 2) {
                    user.setNickName(ResStringUtil.getString(R.string.wechatview_group_notification));
                    user.setReMark(ResStringUtil.getString(R.string.wechatview_group_notification));
                    user.setId(-100);
                    user.setSortLetters("↑");
                    user.setBadgenum(groupNotiveCount);
                }
                sourceDataList.add(i, user);
            }
        }
        adapter.notifyDataSetChanged();


    }

    //初始化上面部分的view
    private void loadTopView() {
        topMenuList = Registry.getRegEntryList("Contacts");
        if (topMenuList == null) {
            return;
        }
        //不为null 配置了菜单
        haveConfigMenu = true;

        if (topLayout != null) {
            //移除view 重新初始化
            stickyList.removeHeaderView(topLayout);
            topLayout.removeAllViews();
        }
        topLayout = new LinearLayout(getActivity());
        topLayout.setGravity(Gravity.CENTER_VERTICAL);
        topLayout.setOrientation(LinearLayout.VERTICAL);
        AbsListView.LayoutParams tabcontentParams = new AbsListView.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        topLayout.setLayoutParams(tabcontentParams);

        topContentLayout = new LinearLayout(getActivity());
        topContentLayout.setGravity(Gravity.CENTER_VERTICAL);
        topContentLayout.setOrientation(LinearLayout.VERTICAL);
        LinearLayout.LayoutParams llParram = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        topContentLayout.setLayoutParams(llParram);
        topLayout.addView(topContentLayout);

        topModelList = new ArrayList<>();
//        topModelList.add(new ContactTopModel("新的朋友", "cicon_xdpy", new StubObject(), "xdpy", newFriendCount));
//        topModelList.add(new ContactTopModel("群聊", "cicon_groupchat", new StubObject(), "ql", 0));
//        topModelList.add(new ContactTopModel("群通知", "cicon_groupnotice", new StubObject(), "qtz", groupNotiveCount));

        handleGNQX(topMenuList);
        for (StubObject stubObject : topMenuList) {
            Hashtable<String, String> hashtable = stubObject.getStubTable();
            ContactTopModel model = new ContactTopModel();
            model.setcName(hashtable.get("caption"));
            model.setGnbh(hashtable.get("id"));
            model.setImage(hashtable.get("menuIcon"));
            model.setBadgeNum(0);
            model.setHashtable(hashtable);
            topModelList.add(model);
            if ("xdpy".equals(stubObject.getString("id", ""))) {
                //新的朋友
                model.setBadgeNum(newFriendCount);
            } else if ("qtz".equals(stubObject.getString("id", ""))) {
                //群通知
                model.setBadgeNum(groupNotiveCount);
            }
        }
        for (ContactTopModel model : topModelList) {
            addItemView(model, inflater);
        }

        stickyList.addHeaderView(topLayout);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            reloadData();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSolveMessageEvent(UpdateBadgeViewEvent event) {
        int fromUserId = Integer.parseInt(event.getUserID());
        if (fromUserId == -2) {
            newFriendCount = WeChatDBManager.getInstance().getNewFriendUnread();
            groupNotiveCount = WeChatDBManager.getInstance().getGroupNoticveUnreadCount();
            //如果数据大于等于三条，并且没有配置菜单，使用之前的方式
            if (sourceDataList != null && sourceDataList.size() >= 3 && !haveConfigMenu) {
                sourceDataList.get(0).setBadgenum(newFriendCount);//新的好友
                sourceDataList.get(2).setBadgenum(groupNotiveCount);//群通知
            }
            myHandler.sendEmptyMessage(1);
            loadTopView();
        }
    }

    //TODO 处理tabmenu 点击(滚动到顶部)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public synchronized void onSolveEvent(TabMenuClickEvent event) {
        if (getArguments() != null) {
            StubObject stubObject = (StubObject) getArguments().getSerializable("stubObject");
            if (event.isChildPage(stubObject) && !isHidden()) {
                stickyList.smoothScrollToPosition(0);
            }
        }
    }

    /**
     * 为ListView填充数据
     *
     * @param users
     * @return
     */
    private List<User> filledData(List<User> users) {
        List<User> usersList = new ArrayList<User>();
        for (User user : users) {
            // 汉字转换成拼音
            String userName = user.getReMark();

            // String pinyin = new HanyuParser().getStringPinYin(userName);
            String sortString = "";
            String pinyin = null;
            try {
                //获取名字的简拼
                pinyin = ChineseCharacterUtils.getJianPin(userName);
                sortString = pinyin.substring(0, 1).toUpperCase(
                        Locale.getDefault());
            } catch (Exception e) {
                e.printStackTrace();
                user.setSortLetters("#");
            }

            if (userName.equals("群聊") || userName.equals("新的朋友") || userName.equals("群通知")) {
                user.setSortLetters("↑");
            } else if (userName.equals("")) {
                user.setSortLetters("☆");
            } else if (sortString.matches("[A-Z]")) {// 正则表达式，判断首字母是否是英文字母
                //更改setSortLetters由首字母的大写变为简拼的大写，便于比较   cimu
                user.setSortLetters(pinyin.toUpperCase(Locale.getDefault()));
            } else {
                user.setSortLetters("#");
            }
            usersList.add(user);
        }

        return usersList;

    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<User> filterDateList = new ArrayList<User>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = sourceDataList;
        } else {
            filterDateList.clear();
            for (User user : sourceDataList) {
                String name = user.getReMark();
                if (containString(name, filterStr)) {
                    filterDateList.add(user);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        adapter.updateListView(filterDateList);
        if (EnvSupportManager.isSupportCWGXPage()) {
            searchMore.setVisibility(View.VISIBLE);
        }
    }

    private boolean containString(String name, String filterStr) {
        String namePinyin = new HanyuParser().getStringPinYin(name);
        for (int i = 0; i < filterStr.length(); i++) {
            String singleStr = filterStr.substring(i, i + 1);
            // 汉字
            if (name != null && name.contains(singleStr)) {
                if (i == filterStr.length() - 1) {
                    return true;
                }
                continue;
            }
            // 英文
            if (namePinyin.contains(singleStr)) {
                int currentIndex = namePinyin.indexOf(singleStr);
                namePinyin = namePinyin.substring(currentIndex + 1,
                        namePinyin.length());
            } else {// 不包含
                break;
            }
            if (i == filterStr.length() - 1) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void onStickyHeaderOffsetChanged(StickyListHeadersListView l,
                                            View header, int offset) {
        if (fadeHeader
                && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            header.setAlpha(1 - (offset / (float) header.getMeasuredHeight()));
        }
    }

    @Override
    public void onStickyHeaderChanged(StickyListHeadersListView l, View header,
                                      int itemPosition, long headerId) {
        header.setAlpha(1);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        if (haveConfigMenu) {
            //因为添加了headview  所以要-1
            position = position - 1;
        }
        if (position < 0) {
            return;
        }
        User user = (User) adapter.getItem(position);
        if ("↑".equals(user.getSortLetters())) {
            String remark = user.getReMark();
            if ("公众号".equals(remark)) {
                Intent intent = new Intent(getActivity(), TransformFragmentActivity.class);
                intent.putExtra(TransformFragmentActivity.EXTRA_FRAGMENT_NAME, PublicNumberListFragment.class.getName());
                startActivity(intent);
            } else if ("群聊".equals(remark)) {
                Intent intent = new Intent(getActivity(), ChatRoomActivity.class);
                startActivity(intent);
            } else if ("组织机构".equals(remark)) {
                Intent intent = new Intent(getActivity(), TransformFragmentActivity.class);
                intent.putExtra(TransformFragmentActivity.EXTRA_FRAGMENT_NAME, TreeFragment.class.getName());
                startActivity(intent);
            } else if ("新的朋友".equals(remark)) {
                Intent intent = new Intent(getActivity(), NewFriendsActivity.class);
                startActivity(intent);
            } else if ("群通知".equals(remark)) {
                Intent intent = new Intent(getActivity(), GroupNotifacationActivity.class);
                startActivity(intent);
            }
        } else {
            //跳转聊天界面
            Intent intent = new Intent();
            intent.putExtra("id", user.getId());
            intent.putExtra("chattype", StructFactory.TO_USER_TYPE_PERSONAL);
            ChatActivitySkipUtil.startUserInfoActivity(getActivity(), intent);
        }
    }

    @Override
    public void onHeaderClick(StickyListHeadersListView l, View header,
                              int itemPosition, long headerId, boolean currentlySticky) {
        // Toast.makeText(getActivity(),
        // "Header " + headerId + " currentlySticky ? " + currentlySticky,
        // Toast.LENGTH_SHORT).show();
    }

    public class MyHandler extends Handler {
        public MyHandler() {
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (sourceDataList != null && sourceDataList.size() >= 3) {
                        sourceDataList.get(2).setBadgenum(groupNotiveCount);
                        sourceDataList.get(0).setBadgenum(newFriendCount);
                    }
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }


    private void addItemView(final ContactTopModel model, LayoutInflater inflater) {
        ViewGroup oneLayout = (ViewGroup) inflater.inflate(
                R.layout.contacts_topview, null, false);
        TextView titleView = (TextView) oneLayout.findViewById(R.id.title);
        ImageView avatar = (ImageView) oneLayout.findViewById(R.id.avatar);
        titleView.setText(model.getcName());
        String filepath = AppConstant.APP_ROOT + "/res/unzip_res/menuImage/" + model.getImage();
        LXGlideImageLoader.getInstance().showRoundUserAvatar(getActivity(), avatar,
                "file://" + filepath, LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_10);
        //初始化角标
        BadgeView badgeView = new BadgeView(getActivity(), avatar);
        if (model.getBadgeNum() != 0) {
            badgeView.setVisibility(View.VISIBLE);
            badgeView.setBadgeMargin(3);
            badgeView.setTextSize(13);
            badgeView.setTag("badge");
            badgeView.setText(String.valueOf(model.getBadgeNum()));
            badgeView.setBadgeBackgroundColor(getActivity().getResources().getColor(
                    R.color.chat_badge_color));
            badgeView.show();
        } else {
            badgeView.setVisibility(View.GONE);
        }
        oneLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("xdpy".equals(model.getGnbh())) {//新的朋友
                    Intent intent = new Intent(getActivity(), NewFriendsActivity.class);
                    startActivity(intent);
                } else if ("ql".equals(model.getGnbh())) {//群聊
                    Intent intent = new Intent(getActivity(), ChatRoomActivity.class);
                    startActivity(intent);
                } else if ("qtz".equals(model.getGnbh())) {//群通知
                    Intent intent = new Intent(getActivity(), GroupNotifacationActivity.class);
                    startActivity(intent);
                } else {
                    Hashtable table = model.getHashtable();
                    String utype = (String) table.get("utype");
                    String androidShow = (String) table.get("AndroidShow");
                    String enterName = (String) table.get("enterName");

                    ClassLoader loader = Thread.currentThread().getContextClassLoader();
                    Class<?> clazz = null;
                    try {
                        // clazz = loader.loadClass("com.efounder.SDReactNativeContainerForTZ");
                        clazz = loader.loadClass(androidShow);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    if (clazz == null) {
                        return;
                    }
                    String zgbh = EnvironmentVariable.getProperty(KEY_F_ZGBH);
                    if (TextUtils.isEmpty(zgbh)) {
                        zgbh = EnvironmentVariable.getUserName();
                    }
                    StubObject stubObject = new StubObject();
                    stubObject.setStubTable(table);
                    try {
                        new AbFragmentManager(getActivity()).startActivity(stubObject, 0, 0);

                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    if (true) {
                        return;
                    }
//                    Bundle bundle = new Bundle();
//                    bundle.putSerializable("enterName", enterName);
//                    bundle.putSerializable("zgbh", zgbh);
//                    bundle.putSerializable("userid", EnvironmentVariable.getProperty(CHAT_USER_ID));
//                    bundle.putSerializable("password", EnvironmentVariable.getProperty(CHAT_PASSWORD));
//                    bundle.putSerializable("jsrq", EnvironmentVariable.getProperty(KEY_TANGZU_JSRQ));
//                    bundle.putSerializable("utype", utype);
//                    bundle.putSerializable("title", model.getcName());
//                    Intent intent = new Intent(getActivity(),
//                            clazz);
//                    intent.putExtra("data", bundle);
//                    startActivity(intent);
                }
            }
        });
        topContentLayout.addView(oneLayout);
    }

    /**
     * 处理功能权限
     *
     * @param mainMenus
     * @return
     */
    public static List<StubObject> handleGNQX(List<StubObject> mainMenus) {
        Iterator<StubObject> iterator = mainMenus.iterator();
        String gnqxString = EnvironmentVariable.getProperty("gnqx", "");
        if (gnqxString != null) {//==null表示没有开启权限
            while (iterator.hasNext()) {
                StubObject stubObject = iterator.next();
                String permission = stubObject.getString("permission", "");
                if (!permission.equals("")) {
                    String[] gnqxStrings = gnqxString.split(";");
                    for (int j = 0; j < gnqxStrings.length; j++) {
                        String gnqx = gnqxStrings[j];
                        if (gnqx.equals(permission)) {
                            break;
                        } else {
                            if (j == gnqxStrings.length - 1) {
                                iterator.remove();
                            }
                        }
                    }
                }
            }
        }
        return mainMenus;
    }
}

