package com.efounder.chat.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.core.xml.StubObject;
import com.efounder.chat.R;
import com.efounder.chat.activity.AddPublicFriendInfoActivity;
import com.efounder.chat.activity.ChatLocalSearchActivity;
import com.efounder.chat.adapter.ChatListSwipeMenuAdapter;
import com.efounder.chat.adapter.ChatVoicePlayClickListener;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.event.SystemInitOverEvent;
import com.efounder.chat.manager.ChatListManager;
import com.efounder.chat.manager.ChatMessageSendManager;
import com.efounder.chat.model.ChatListItem;
import com.efounder.chat.model.MessageEvent;
import com.efounder.chat.model.RefreshChatItemEvent;
import com.efounder.chat.model.SessionOnlineEvent;
import com.efounder.chat.model.TabMenuClickEvent;
import com.efounder.chat.model.UpdateBadgeViewEvent;
import com.efounder.chat.service.SystemInfoService;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.ChatActivitySkipUtil;
import com.efounder.chat.utils.ChatListHelper;
import com.efounder.chat.utils.VoiceRecognitionSoundFileCacheUtil;
import com.efounder.chat.view.voicedictate.VoiceDictatePopManager;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.activity.EFAppAccountMainActivity;
import com.efounder.frame.activity.EFTransformFragmentActivity;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.frame.utils.Constants;
import com.efounder.frame.utils.EFFrameUtils;
import com.efounder.frame.utils.NetStateBroadcastReceiver;
import com.efounder.http.EFHttpRequest;
import com.efounder.interfaces.BadgeUtil;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilecomps.contacts.ClearEditText;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.pansoft.chat.listener.VoiceDictateSendListener;
import com.efounder.util.EnvSupportManager;
import com.efounder.util.ToastUtil;
import com.efounder.utils.EasyPermissionUtils;
import com.efounder.utils.JfResourceUtil;
import com.efounder.utils.ResStringUtil;
import com.pansoft.utils.ResStubObjectUtil;
import com.utilcode.util.ConvertUtils;
import com.utilcode.util.SizeUtils;
import com.utilcode.util.ThreadManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import pub.devrel.easypermissions.AfterPermissionGranted;

import static com.efounder.chat.service.SystemInfoService.CHATITEMLIST;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;


/**
 * 消息列表界面
 *
 * @author Administrator=lch 会话列表fragment
 */
public class ChatListSwipeMenuFragment extends BaseFragment implements
//        MessageService
//        .MessageServiceNetStateListener, MessageService.MessageServiceLoginListener,
        VoiceDictateSendListener {
    private final static String TAG = "ChListSwipeMenuFragment";
    private ChatListSwipeMenuAdapter chatListAdapter;

    // 临时写的实体类
    private volatile List<ChatListItem> chatListItems;
    private volatile Map<String, ChatListItem> chatListMap;
    private View view;
    private SwipeMenuListView listView;
    //多设备
    private LinearLayout llMultiLoginItem;
    //搜索
    private ClearEditText searchEditext;
    private TextView tvLoginHint;
    private SwipeMenuCreator creator;
    private SimpleDateFormat dateFormat = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault());

    private Handler messageHandler = new MessageHandler(this);

    private int currentChatUserId = -1;
    private Activity activity;
    //网络错误提示布局
    private RelativeLayout rl_error_item;
    //    空白页提示
    private LinearLayout emptyPage;
    private Button startTrip;
    /**
     * //搜索框
     */
    private LinearLayout ll_search;
    //    private  Integer topIndex = -1;//置顶计数
    public static boolean ISALIVE = false;//此fragment是否可用


    //结束初始化网络事件
    private InitprogressDismiss initprogressDismiss;
    //是否初始化网络结束
    private boolean isInitNetOver = false;
    private NetStateBroadcastReceiver mNetStateBroadcastReceiver;
    //监听网络状态
    private NetStateBroadcastReceiver.NetStateListener mNetStateListener;

    private static final int MSG_WHAT_REFRESH = 0;
    private static final int MSG_WHAT_LOGIN_STATE = 1;
    private static final int MSG_WHAT_INIT_STATE = 2;

    private VoiceDictatePopManager voiceDictatePopManager;
    private ChatMessageSendManager chatMessageSendManager = new ChatMessageSendManager(getActivity());
    private JFMessageManager messageManager = JFMessageManager.getInstance();

    private View topHintView;
    private View topMutilDeviceView;
    /**
     * 搜索高度
     */
    int searchHeight = 0;
    /**
     * 第一次进来时做滑动
     */
    private boolean isFirstScroll = true;
    private float downY;
    private float moveY;
    private boolean isUp = true;
    /**
     * 顶部布局滑动时长
     */
    private int scrollTime = 800;

    private static class MessageHandler extends Handler {
        private WeakReference<ChatListSwipeMenuFragment> weakReference;

        public MessageHandler(ChatListSwipeMenuFragment fragment) {
            weakReference = new WeakReference<ChatListSwipeMenuFragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ChatListSwipeMenuFragment fragment = weakReference.get();
            if (fragment == null) {
                return;
            }
            switch (msg.what) {
                case 0:
                    fragment.chatListAdapter.notifyDataSetChanged();
                    break;
                case 1:
                    String chatUserID = EnvironmentVariable.getProperty(CHAT_USER_ID);
                    if (null != chatUserID && chatUserID.equals("0")) {
                        TextView tv_connect_errormsg = (TextView) fragment.getActivity().findViewById(R.id.tv_connect_errormsg);
                        tv_connect_errormsg.setText(R.string.wechatview_no_login);
                    }
//                    rl_error_item.setVisibility(View.VISIBLE);
                    break;
                case 2:
//                    rl_error_item.setVisibility(View.GONE);
                    if (fragment.initprogressDismiss != null) {
                        fragment.initprogressDismiss.trigger(false);
                    }
                    fragment.isInitNetOver = true;
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.activity = (Activity) context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //注册监听网络广播
        mNetStateBroadcastReceiver = new NetStateBroadcastReceiver();
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        getActivity().registerReceiver(mNetStateBroadcastReceiver, mFilter);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.chat_list_swipemenu, container, false);
        voiceDictatePopManager = new VoiceDictatePopManager(getActivity());
        voiceDictatePopManager.setVoiceDictateSendListener(this);
        isFirstScroll = true;// fix 头布局显示不出的bug
        initView();
        //注册eventbus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
        initListener();
    }

    private void initListener() {
        searchEditext.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //进入搜索界面
                ChatLocalSearchActivity.start(getActivity());
            }
        });
    }

    private void initData() {
        chatListItems = CHATITEMLIST;
        chatListMap = SystemInfoService.CHATLISTMAP;
//        topIndex = TOPINDEX;
        ISALIVE = true;
        mNetStateBroadcastReceiver.setNetStateListener(mNetStateListener);

        chatListAdapter = new ChatListSwipeMenuAdapter(this, chatListItems);
        listView.setAdapter(chatListAdapter);


        if (ResStubObjectUtil.getHasBigMenu()) {
            View footerView = new View(getActivity());
            ListView.LayoutParams params = new ListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, SizeUtils.dp2px(20));
            footerView.setLayoutParams(params);
            footerView.setBackgroundColor(JfResourceUtil.getSkinColor(R.color.wechatview_content_bottom_padding));
            listView.addFooterView(footerView);
        }
        chatListAdapter.notifyDataSetChanged();
        //设置语音识别发送的点击回调
        chatListAdapter.setOnRecognitonVoiceRecordStart(new ChatListSwipeMenuAdapter.OnRecognitonVoiceRecordStart() {
            @Override
            public void onRecordStart(int position) {
                if (voiceDictatePopManager != null && !voiceDictatePopManager.isShowPop()) {
                    voicePotiosin = position;
                    checkPermissionOrshowVoicePop();
                } else {
                    voiceDictatePopManager.disMissPop();
                }
            }
        });
        judgeChatListEmpty(CHATITEMLIST);
        initLeftSlide();//初始化左滑组件
        initItemClickEvent();
        //listView.setCloseInterpolator(new BounceInterpolator());//动画会弹效果
        //listView.setCloseInterpolator(new OvershootInterpolator());
        // setListViewHeightBasedOnChildren(listView);
        // listView.setFocusable(false);

        //添加网络监听事件
//        MessageService.addMessageServiceNetStateListener(this);
//        MessageService.addMessageServiceLoginListener(this);


    }

    @AfterPermissionGranted(EasyPermissionUtils.PERMISSION_REQUEST_CODE_AUDIO)
    private void checkPermissionOrshowVoicePop() {
        if (EasyPermissionUtils.checkAudioPermission()) {
            showVoicePop();
        } else {
            EasyPermissionUtils.requestAudioPermission(this);
        }
    }

    //点击录音按钮的位置
    private int voicePotiosin = 0;

    private void showVoicePop() {
        int position = voicePotiosin;
        int firstVisiblePosition = listView.getFirstVisiblePosition();
        int lastVisiblePosition = listView.getLastVisiblePosition();
        //如果位置在item最后，角位置显示右下
        if (Math.abs(position + 2 - lastVisiblePosition) <= 1) {
            voiceDictatePopManager.setBubbleLegRightBottom(true);
        } else {
            voiceDictatePopManager.setBubbleLegRightBottom(false);
        }
        //设置气泡位置
        voiceDictatePopManager.setGravity(Gravity.LEFT);
        voiceDictatePopManager.showTopPopWindow(listView.getChildAt(position + 2 - firstVisiblePosition), 0, "  ", true);
        //组织聊天消息
        ChatListItem chatListItem = chatListItems.get(position);
        chatMessageSendManager.setChatType((byte) chatListItem.getChatType());
        chatMessageSendManager.setCurrentChatUserId(chatListItem.getUserId());
        chatMessageSendManager.setPreSendMessageCallback(getPreSendCallback(chatListItem.getUserId(), (byte) chatListItem.getChatType()));
    }

    //初始化 listviewitem 点击
    private void initItemClickEvent() {
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                //两个headerView不可触发list的点击事件
                if (position == 0 || position == 1) {
                    return;
                }
                position = position - 2;
                if (position == chatListItems.size()) {
                    //footview 不能点击
                    return;
                }
                if (position > chatListItems.size() - 1) {
                    return;
                }
                ChatListItem listItem = chatListItems.get(position);
                final User user = listItem.getUser();
                //TODO 感觉是给铁工配置的 yqs
                if (user != null && ((EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).contains("OSPMobileLiveAppTG")
                        && user.getId() == 6392)
                        || EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).contains("OSPMobileLiveAppTGTest")
                        && user.getId() == 709)) {
                    //判断是否关注
                    User officialUser = WeChatDBManager.getInstance().getOneOfficialNumber(user.getId());
                    if (officialUser == null) {
                        AlertDialog dialog = new AlertDialog.Builder(activity).setMessage(ResStringUtil.getString(R.string.wechatview_no_attention_public_number)).setTitle("提示").setNegativeButton(R.string.common_text_cancel, null)

                                .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        ChatListManager chatListManager = new ChatListManager();
                                        chatListManager.clearunReadCount(user.getId(), (byte) 0);
                                        EventBus.getDefault().post(new UpdateBadgeViewEvent(user.getId() + "", (byte) 2));
                                        Intent intent = new Intent(activity, AddPublicFriendInfoActivity.class);
                                        intent.putExtra("userID", user.getId() + "");
                                        //不跳转聊天
                                        intent.putExtra("type", "task");
                                        activity.startActivity(intent);
                                    }
                                }).create();
                        dialog.show();
                        return;
                    }

                    ChatListManager chatListManager = new ChatListManager();
                    chatListManager.clearunReadCount(user.getId(), (byte) 0);
                    EventBus.getDefault().post(new UpdateBadgeViewEvent(user.getId() + "", (byte) 2));

                }
                if (user != null && user.getType() == 1) {
                    //usertype =1 表示是应用号
                    Intent intent = new Intent(activity, EFAppAccountMainActivity.class);
                    intent.putExtra("id", user.getId());
                    intent.putExtra("nickName", user.getNickName());
                    //查询是否是好友
                    boolean isFriend = WeChatDBManager.getInstance().queryIsFriend(user.getId());
                    intent.putExtra("isFriend", isFriend);
                    intent.putExtra("type", "chat");

                    //todo yqs 20180523 屏蔽的代码看不懂处理什么的。。。
                    //int unReadCount = chatListItems.get(position).getBadgernum();//未读消息数量 chatListItem
//                    String PublicNumIntentWhenNoNewMessage = EnvironmentVariable.getProperty("PublicNumIntentWhenNoNewMessage");
//                    if (unReadCount > 0 || (null != PublicNumIntentWhenNoNewMessage && PublicNumIntentWhenNoNewMessage.equals("ChatListFragment"))) {
//                        intent.putExtra("type", "chat");
//                    } else {
//                        intent.putExtra("type", "");
//                    }

                    if ((EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).contains("OSPMobileLiveAppTG")
                            && user.getId() == 6392)
                            || EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).contains("OSPMobileLiveAppTGTest")
                            && user.getId() == 709) {
                        intent.putExtra("type", "");
                    }
                    startActivity(intent);

                } else {
                    Intent intent = new Intent();
                    intent.putExtra("id", listItem.getUserId());
                    intent.putExtra("chattype", (byte) listItem.getChatType());
                    currentChatUserId = listItem.getUserId();
                    EnvironmentVariable.setProperty("currentChatUserId", String.valueOf(currentChatUserId));
                    ChatActivitySkipUtil.startChatActivity(activity, intent);
                }
                judgeChatListEmpty(CHATITEMLIST);

            }
        });
    }

    private void initView() {
        listView = (SwipeMenuListView) view.findViewById(R.id.listView);
        listView.setIsNeedIntercept(true);
        addHeaderLayout();
        //多设备登录H
        llMultiLoginItem = topMutilDeviceView.findViewById(R.id.ll_multi_login);
        tvLoginHint = topMutilDeviceView.findViewById(R.id.tv_hint);
        llMultiLoginItem.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //我的设备
                try {
                    Bundle bundle = new Bundle();
                    bundle.putBoolean(EFTransformFragmentActivity.EXTRA_HIDE_TITLE_BAR, true);
                    EFFrameUtils.pushFragment((Class<? extends BaseFragment>) Class.forName("com.efounder.chat.fragment.MultiLoginListFragment"), bundle);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });
        emptyPage = (LinearLayout) view.findViewById(R.id.layout_empty_page);
        startTrip = (Button) view.findViewById(R.id.btn_start_trip);
        searchEditext = (ClearEditText) topHintView.findViewById(R.id.filter_edit);
        searchEditext.setFocusable(false);
        //网络异常
        rl_error_item = (RelativeLayout) topMutilDeviceView.findViewById(R.id.rl_error_item);
        mNetStateListener = new NetStateBroadcastReceiver.NetStateListener() {
            @Override
            public void onConnected(int netState) {
//                LogUtils.e("onConnected------》");
                rl_error_item.setVisibility(View.GONE);
                //ThreadManager.getThreadPool().execute(threadMultiLoginDevice);
                requestLoginDevice();
            }

            @Override
            public void onDisconnected(int netState) {
//                LogUtils.e("onDisconnected------》");
                rl_error_item.setVisibility(View.VISIBLE);
                llMultiLoginItem.setVisibility(View.GONE);
            }
        };

//        rl_error_item.setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                String chatUserID = EnvironmentVariable.getProperty(CHAT_USER_ID);
//                if (null != chatUserID && chatUserID.equals("0")) {
//                    return;
//                }
//                if (initprogressDismiss != null)
//                    initprogressDismiss.trigger(true);
//                Toast.makeText(getActivity(), "重新连接服务", Toast.LENGTH_LONG).show();
//                Intent intent = new Intent(getActivity(), MessageService.class);
//                intent.putExtra(MessageService.EXTRA_KEY_IS_LOGIN_IMMEDIATELY, true);
//                getActivity().startService(intent);
//
//            }
//        });

//        View headerView = this.activity.getLayoutInflater()
//                .inflate(R.layout.chat_list_headview, container, false);
//        headerView.setOnClickListener(new OnClickListener() {
//
//            @Override
//            public void onClick(View arg0) {
//                Toast.makeText(activity, "点击搜索", Toast.LENGTH_SHORT)
//                        .show();
//            }
//        });

    }


    //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()) {
                listView.smoothScrollToPosition(1);
            }
        }
    }


    //TODO 处理收发消息时刷新界面事件
    @Subscribe(threadMode = ThreadMode.POSTING)
    public synchronized void onSolveMessageEvent(RefreshChatItemEvent event) {
        messageHandler.sendEmptyMessage(event.getMessageWhat());
        judgeChatListEmpty(CHATITEMLIST);
    }

    //TODO 处理订阅事件
    @Subscribe(threadMode = ThreadMode.POSTING)
    public synchronized void onSolveMessageEvent(MessageEvent messageEvent) {
        Log.e(TAG, Thread.currentThread().getName());
        ChatListItem chatListItem = messageEvent.getChatListItem();
        if (null == chatListItem) {
            return;
        }
        String key = null;
        if (chatListItem.getChatType() == StructFactory.TO_USER_TYPE_PERSONAL
                || chatListItem.getChatType() == StructFactory
                .TO_USER_TYPE_OFFICIAL_ACCOUNT) {
            key = "0" + String.valueOf(chatListItem.getUserId());
        } else {
            key = "1" + String.valueOf(chatListItem.getUserId());
        }
        if (chatListMap.containsKey(key)) {
            ChatListItem tempChatListItem = chatListMap.get(key);
            if (messageEvent.getType() == MessageEvent.DELETE) {
                chatListItems.remove(chatListMap.get(key));
                chatListMap.remove(key);
                if (chatListItem.getIsTop() == true) {
//                    if (SystemInfoService.TOPINDEX != -1) {
//                        SystemInfoService.TOPINDEX--;
//                    }
                    if (ChatListHelper.getTopIndex().get() != -1) {
                        ChatListHelper.topIndexDecrement();
                    }
                }
                //处理角标
                UpdateBadgeViewEvent updateBadgeViewEvent = new UpdateBadgeViewEvent(chatListItem.getUserId() + "", (byte) chatListItem.getChatType());
                EventBus.getDefault().post(updateBadgeViewEvent);

            } else if (messageEvent.getType() == MessageEvent.UPDATE) {
                tempChatListItem.setAvatar(chatListItem.getAvatar());
                tempChatListItem.setBadgernum(chatListItem.getBadgernum());
                tempChatListItem.setName(chatListItem.getName());
                tempChatListItem.setUser(chatListItem.getUser());
                tempChatListItem.setGroup(chatListItem.getGroup());
                if (tempChatListItem.getUser() != null) {
                    tempChatListItem.setIsBother(chatListItem.getUser().getIsBother());
                    if (tempChatListItem.getIsTop().booleanValue()
                            != chatListItem.getUser().getIsTop().booleanValue()) {
                        //打印内存地址
//                        Log.e("内存地址fragment：", System.identityHashCode(ChatListHelper.getTopIndex()) + "");

                        if (chatListItem.getUser().getIsTop()) {
//                            SystemInfoService.TOPINDEX++;
                            ChatListHelper.topIndexIncrement();

                            tempChatListItem.setIsTop(chatListItem.getUser().getIsTop());
                            chatListItems.remove(tempChatListItem);
                            chatListItems.add(0, tempChatListItem);
                        } else {
//                            if (SystemInfoService.TOPINDEX != -1) {
//                                SystemInfoService.TOPINDEX--;
//                            }
                            if (ChatListHelper.getTopIndex().get() != -1) {
                                ChatListHelper.topIndexDecrement();
                            }
                            tempChatListItem.setIsTop(chatListItem.getUser().getIsTop());
                        }
                        sortConversationByLastChatTime(chatListItems);
                        sortConversationByIsTop(chatListItems);
                    }
                }
                if (tempChatListItem.getGroup() != null) {
                    tempChatListItem.setIsBother(chatListItem.getGroup().getIsBother());
                    if (tempChatListItem.getIsTop().booleanValue() != chatListItem.getGroup().getIsTop().booleanValue()) {
                        if (chatListItem.getGroup().getIsTop()) {
//                            SystemInfoService.TOPINDEX++;
                            ChatListHelper.topIndexIncrement();
                            tempChatListItem.setIsTop(chatListItem.getGroup().getIsTop());
                            chatListItems.remove(tempChatListItem);
                            chatListItems.add(0, tempChatListItem);
                        } else {
//                            if (SystemInfoService.TOPINDEX != -1) {
//                                SystemInfoService.TOPINDEX--;
//                            }
                            if (ChatListHelper.getTopIndex().get() != -1) {
                                ChatListHelper.topIndexDecrement();
                            }
                            tempChatListItem.setIsTop(chatListItem.getGroup().getIsTop());
                        }
                        sortConversationByLastChatTime(chatListItems);
                        sortConversationByIsTop(chatListItems);
                    }
                }

            }

        }
        //setUnreadCount();
        messageHandler.sendEmptyMessage(MSG_WHAT_REFRESH);
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onSolveMessageEvent(UpdateBadgeViewEvent event) {
//        byte chatType = event.getChatType();
//        for (ChatListItem item : chatListItems) {
//            String eventUserID = event.getUserID();
//            String chatID = item.getUserId() + "";
//            if (eventUserID.equals(chatID)) {
//                if (BadgeUtil.handleAppContact(getActivity()).contains(chatID)) {
//                    int unReadcount = 0;
//                    if (chatType == StructFactory.TO_USER_TYPE_PERSONAL || chatType == StructFactory
//                            .TO_USER_TYPE_OFFICIAL_ACCOUNT) {
//                        unReadcount = JFMessageManager.getInstance().getUnReadCount(Integer.parseInt(chatID), (byte) 0);
//                    } else {
//                        unReadcount = JFMessageManager.getInstance().getUnReadCount(Integer.parseInt(chatID), chatType);
//                    }
//                    if (unReadcount > 0) {
//                        item.setBadgernum(0);
//                    } else {
//                        item.setBadgernum(-1);
//                    }
//                    chatListAdapter.notifyDataSetChanged();
//                    judgeChatListEmpty(CHATITEMLIST);
//                    break;
//                }
//            }
//        }
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSolveMessageEvent(UpdateBadgeViewEvent event) {
        byte chatType = event.getChatType();
        ChatListItem chatListItem = chatListMap.get(chatType + event.getUserID());
        if (chatListItem != null) {
            if (BadgeUtil.handleAppContact(getActivity()).contains(chatListItem.getUserId())
                    && (chatListItem.getChatType() == 0 || chatListItem.getChatType() == 2)) {
                if (chatListItem.getBadgernum() >= 0) {
                    chatListItem.setBadgernum(0);
                } else {
                    chatListItem.setBadgernum(-1);
                }
                chatListAdapter.notifyDataSetChanged();
                judgeChatListEmpty(CHATITEMLIST);
            }
        }
    }

    public void resetCountNum() {
        //setUnreadCount();
        chatListAdapter.notifyDataSetChanged();
        judgeChatListEmpty(CHATITEMLIST);
    }

    @Override
    public void onResume() {
        super.onResume();
//        System.out.println("----onResume---");
//        ThreadManager.getThreadPool().execute(threadMultiLoginDevice);
        currentChatUserId = -1;
        EnvironmentVariable.setProperty("currentChatUserId", "-1");

        ThreadManager.getThreadPool().execute(runnable);
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(4000);
                isInitNetOver = true;
                if (!JFMessageManager.isChannelActived()) {
                    Message message = new Message();
                    message.what = MSG_WHAT_LOGIN_STATE;
                    messageHandler.sendMessage(message);
                }
                if (initprogressDismiss != null) {
                    initprogressDismiss.trigger(false);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            if (voiceDictatePopManager != null) {
                voiceDictatePopManager.disMissPop();
            }
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!isVisibleToUser) {
            if (voiceDictatePopManager != null) {
                voiceDictatePopManager.disMissPop();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
//        System.out.println("----onPause---");
        //取消语音识别弹窗
        voiceDictatePopManager.disMissPop();
        //回收语音播放
        if (ChatVoicePlayClickListener.currentPlayListener != null && ChatVoicePlayClickListener.isPlaying) {
            ChatVoicePlayClickListener.currentPlayListener.stopPlayVoice();
        }
        ChatVoicePlayClickListener.currentPlayListener = null;
    }

    @Override
    public void onStop() {
        super.onStop();
        System.out.println("----onStop---");

    }


    @SuppressWarnings("unused")
    private void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    /**
     * 根据最后一条消息的时间排序
     *
     * @param
     */
    private void sortConversationByLastChatTime(
            List<ChatListItem> messageItemsList) {

        Collections.sort(messageItemsList, new Comparator<ChatListItem>() {
            @Override
            public int compare(final ChatListItem msg1, final ChatListItem msg2) {
                if (msg1.getStruct002() == null) {
                    return -1;
                }
                if (msg2.getStruct002() == null) {
                    return 1;
                }
                String chatTime1 = dateFormat.format(msg1.getStruct002()
                        .getLocalTime());
                String chatTime2 = dateFormat.format(msg2.getStruct002()
                        .getLocalTime());

                if (chatTime1.compareTo(chatTime2) == 0) {
                    return 0;
                } else if (chatTime1.compareTo(chatTime2) > 0) {
                    return -1;
                } else {
                    return 1;
                }
            }

        });
    }

    /**
     * 根据是否置顶排序
     *
     * @param
     */
    private void sortConversationByIsTop(
            List<ChatListItem> messageItemsList) {

        Collections.sort(messageItemsList, new Comparator<ChatListItem>() {
            @Override
            public int compare(final ChatListItem msg1, final ChatListItem msg2) {

                if (msg1.getIsTop().compareTo(msg2.getIsTop()) == 0) {
                    return 0;
                } else if (msg1.getIsTop().compareTo(msg2.getIsTop()) > 0) {
                    return -1;
                } else {
                    return 1;
                }
            }

        });
    }

    /**
     * 删除item
     *
     * @param v
     * @param position
     */
    public synchronized void deleteListItem(View v, int position) {
        if (position >= chatListItems.size()) {
            return;
        }
        ChatListItem willDeleteBean = chatListItems.get(position);
        if (willDeleteBean.getBadgernum() != -1) {
            if (willDeleteBean.getUserId() != Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))) {
                if (willDeleteBean.getChatType() == StructFactory.TO_USER_TYPE_GROUP) {
                    JFMessageManager.getInstance().unreadZero(willDeleteBean.getUserId(), (byte) 1);
                } else {
                    JFMessageManager.getInstance().unreadZero(willDeleteBean.getUserId(), (byte) 0);
                }
            }

        }
        if (willDeleteBean.getIsTop() == true) {
//            SystemInfoService.TOPINDEX--;
            ChatListHelper.topIndexDecrement();
        }
        if (chatListItems.contains(willDeleteBean)) {
            chatListItems.remove(willDeleteBean);
        }
        String deleteKey = null;
        if (willDeleteBean.getChatType() == StructFactory.TO_USER_TYPE_PERSONAL
                || willDeleteBean.getChatType() == StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT) {
            deleteKey = "0" + String.valueOf(willDeleteBean.getUserId());
        } else {
            deleteKey = "1" + String.valueOf(willDeleteBean.getUserId());
        }
        chatListMap.remove(deleteKey);

        WeChatDBManager.getInstance().deleteChatListiItem(willDeleteBean);
        //setUnreadCount();
        messageHandler.sendEmptyMessage(MSG_WHAT_REFRESH);
        UpdateBadgeViewEvent updateBadgeViewEvent = new UpdateBadgeViewEvent(willDeleteBean.getUserId() + "", (byte) willDeleteBean.getChatType());
        EventBus.getDefault().post(updateBadgeViewEvent);


    }

//    /**
//     * 设置未读总数量
//     */
//    public synchronized void setUnreadCount() {
//        int countNum = 0;
//        for (ChatListItem item : chatListItems) {
//            if (item.getBadgernum() != -1) {
//                countNum += item.getBadgernum();
//            }
//        }
//        EventBus.getDefault().post(new UnReadCountEvent(countNum, "message"));
//    }


//    @Override
//    public void netStateChange(int net_state) {
//        Log.i(TAG, "netStateChange--监听网络状态--" + net_state);
//        if (net_state == 0) {
//            Message message = new Message();
//            message.what = MSG_WHAT_LOGIN_STATE;
//
//            if (isInitNetOver == true)
//                this.messageHandler.sendMessage(message);
//        } else {
//            Message message = new Message();
//            message.what = MSG_WHAT_INIT_STATE;
//
//            this.messageHandler.sendMessage(message);
//        }
//    }


//    //监听tcp是否可用事件
//    @Override
//    public void onLoginSuccess() {
//        Message message = new Message();
//        message.what = MSG_WHAT_INIT_STATE;
//
//        this.messageHandler.sendMessage(message);
//    }
//
//    @Override
//    public void onLoginFail(String errorMsg) {
//
//    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ISALIVE = false;
        EventBus.getDefault().unregister(this);
        VoiceRecognitionSoundFileCacheUtil.clearChatList();
//        MessageService.removeMessageServiceNetStateListener(this);
//        MessageService.removeMessageServiceLoginListener(this);
//        if(threadMultiLoginDevice!=null){
//            ThreadManager.getThreadPool().cancel(threadMultiLoginDevice);
//        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "----onDestroy----");
        if (mNetStateBroadcastReceiver != null) {
            getActivity().unregisterReceiver(mNetStateBroadcastReceiver);
        }
        //清空回调
        ChatVoicePlayClickListener.clearCallBacks();

        ThreadManager.getThreadPool().cancel(runnable);

    }

    public interface InitprogressDismiss {
        void trigger(boolean isShow);

    }

    public void setInitprogressDismiss(InitprogressDismiss _initprogressDismiss) {
        initprogressDismiss = _initprogressDismiss;
    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    /**
     * 左滑显示删除和标记未读
     */
    private void initLeftSlide() {
        creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                switch (menu.getViewType()) {
                    case 0://消息已读
                        // 删除按钮
                        SwipeMenuItem item2 = new SwipeMenuItem(activity);
                        item2.setBackground(R.color.red_delete);
                        item2.setWidth(dp2px(90));
                        item2.setTitle(R.string.delete);
                        item2.setTitleSize(18);
                        item2.setTitleColor(Color.WHITE);
                        menu.addMenuItem(item2);
                        break;
                    case 1://消息未读
                        // 标为已读
                        SwipeMenuItem item0 = new SwipeMenuItem(activity);
                        item0.setBackground(R.color.red_read);
                        item0.setWidth(dp2px(90));
                        item0.setTitle(R.string.wrchatview_mark_read);
                        item0.setTitleSize(18);
                        item0.setTitleColor(Color.WHITE);
                        menu.addMenuItem(item0);
                        // 删除按钮
                        SwipeMenuItem item1 = new SwipeMenuItem(activity);
                        item1.setBackground(R.color.red_delete);
                        item1.setWidth(dp2px(90));
                        item1.setTitle(R.string.delete);
                        item1.setTitleSize(18);
                        item1.setTitleColor(Color.WHITE);
                        menu.addMenuItem(item1);
                        break;

                }


            }
        };
        listView.setMenuCreator(creator);
        listView.setOnMenuItemClickListener(
                new SwipeMenuListView.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                        if (menu.getViewType() == 0) {
                            deleteListItem(null, position);
                        } else {
                            switch (index) {
                                case 0:
                                    ChatListItem chatListItem = chatListItems.get(position);
                                    int badgerNum = chatListItem.getBadgernum();
                                    if (badgerNum == -1) {
                                        chatListAdapter.notifyDataSetChanged();
                                        judgeChatListEmpty(CHATITEMLIST);
                                    } else {
                                        if (chatListItem.getUserId() != Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))) {
                                            if (chatListItem.getChatType() == StructFactory.TO_USER_TYPE_GROUP) {
                                                JFMessageManager.getInstance().unreadZero(chatListItem.getUserId(), (byte) 1);
                                            } else {
                                                JFMessageManager.getInstance().unreadZero(chatListItem.getUserId(), (byte) 0);
                                            }
                                            chatListItem.setBadgernum(-1);
                                            resetCountNum();
                                            UpdateBadgeViewEvent updateBadgeViewEvent = new UpdateBadgeViewEvent(chatListItem.getUserId() + "", (byte) chatListItem.getChatType());
                                            EventBus.getDefault().post(updateBadgeViewEvent);
                                            ToastUtil.showToast(activity, R.string.wechatview_mark_read_success);
                                        }
                                    }

                                    break;
                                case 1:
                                    deleteListItem(null, position);

                                    break;
                            }
                        }
                        return true;

                    }
                }

        );

    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 1, sticky = true)
    public void onSolveMessageEvent(SystemInitOverEvent event) {
        //等服务初始化完成后再判断聊天list是否为空
        judgeChatListEmpty(CHATITEMLIST);
    }

    /**
     * 判断是否显示空白提示页
     */
    private void judgeChatListEmpty(List emptyList) {
        if (emptyList.size() == 0) {
            Log.e(TAG, "judgeEmpty: id  shown");
            emptyPage.setVisibility(View.VISIBLE);
        } else {
            emptyPage.setVisibility(View.GONE);
            if (isFirstScroll) {
                isFirstScroll = false;
//                LogUtils.e(" listView.smoothScrollBy(120,100);");
                ll_search.setVisibility(View.VISIBLE);

                ll_search.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
                    @Override
                    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                        searchHeight = ll_search.getMeasuredHeight();
                        listView.smoothScrollBy(searchHeight, 100);
                        ll_search.removeOnLayoutChangeListener(this);
                    }
                });
            }

        }
    }

    @Override
    public void onViceDictateSendListener(String content, String voicePath) {
        chatMessageSendManager.sendVoiceRecognitionMessage(content, voicePath);
    }

    /**
     * 设置预发送回调
     *
     * @param chatUserId id
     * @param chatType   type
     * @return 回调
     */
    private ChatSenderFragment.PreSendMessageCallback getPreSendCallback(final int chatUserId
            , final byte chatType) {
        return new ChatSenderFragment.PreSendMessageCallback() {
            @Override
            public void preSendMessage(IMStruct002 struct002) {
                if (struct002 != null) {
                    struct002.setToUserId(chatUserId);
                    struct002.setFromUserId(Integer.parseInt(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID)));
                    struct002.setToUserType(chatType);
                    struct002.putExtra("progress", 0);
                    struct002.putExtra("startUploadTime", System.currentTimeMillis());
                    messageManager.preSendMessage(struct002);
                    messageHandler.sendEmptyMessage(2);
//                chatAdapter.notifyDataSetChanged();
//                chatListView.setSelection(chatListView.getCount() - 1);
                }
            }

            @Override
            public void updateProgress(IMStruct002 struct002, double percent) {
                if (percent == -1.0d) {
                    JFMessageManager.getInstance().updateMessage(struct002);
                }
                chatListAdapter.notifyDataSetChanged();
            }

            @Override
            public void sendPreMessage(final IMStruct002 struct002) {
                if (struct002 != null) {
                    messageManager.sendPreMessage(struct002);
                    Log.i(TAG, "发送 ------ sendPreMessage:" + struct002.toString());
                }
            }
        };
    }

    private List<MultiLoginListFragment.LoginDevice> mData = new ArrayList<>();

    /**
     * 当前登录设备请求
     */
    private void requestLoginDevice() {
        if (!EnvSupportManager.isSupportShowMutiDevice()) {
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("userId", EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
        params.put("passWord", EnvironmentVariable.getProperty(Constants.CHAT_PASSWORD));
        EFHttpRequest httpRequest = new EFHttpRequest(TAG);
        httpRequest.setHttpRequestListener(new EFHttpRequest.HttpRequestListener() {
            @Override
            public void onRequestSuccess(int requestCode, String response) {
                if (response != null) {
                    //   LogUtils.i(response);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject.optString("result").equals("success")) {
                            //返回成功
                            JSONArray deviceArray = jsonObject.optJSONArray("sessionContextList");
                            mData.clear();
                            if (deviceArray.length() > 0) {
                                for (int i = 0; i < deviceArray.length(); i++) {
                                    JSONObject deviceObj = deviceArray.optJSONObject(i);
                                    MultiLoginListFragment.LoginDevice loginDevice = new MultiLoginListFragment.LoginDevice();
                                    if (deviceObj.optString("deviceId").equals(EnvironmentVariable.getProperty("deviceId"))) {
                                        continue;
                                    }
                                    loginDevice.setName(URLDecoder.decode(deviceObj.optString("deviceModel"), "UTF-8"));
                                    loginDevice.setDeviceId(deviceObj.optString("deviceId"));
                                    loginDevice.setClientId(deviceObj.optString("clientId"));
                                    try {
                                        loginDevice.setTime(com.utilcode.util.TimeUtils
                                                .millis2String(Long.valueOf(deviceObj.optString("sessionTime"))));
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    loginDevice.setType(deviceObj.optString("deviceClass"));
                                    mData.add(loginDevice);
                                }
                            }
                            settingMultiLoginDeviceLayoutVisible(mData);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
//                        ToastUtils.showShort("请求失败");
                    }
                }
            }

            @Override
            public void onRequestFail(int requestCode, String message) {
//                ToastUtils.showShort("请求失败");
            }
        });
        httpRequest.httpPost(String.format("%s/%s", EnvironmentVariable.getProperty("IMBaseUrl"),
                "IMServer/user/getSessionContextList"), params);
    }

    /**
     * 设置多设备布局的显示
     *
     * @param loginDeviceList
     */
    private void settingMultiLoginDeviceLayoutVisible
    (List<MultiLoginListFragment.LoginDevice> loginDeviceList) {
        if (loginDeviceList.size() > 0) {
            llMultiLoginItem.setVisibility(View.VISIBLE);
            tvLoginHint.setText(getString(R.string.web_login_hint, mData.size() + ""));
        } else {
            llMultiLoginItem.setVisibility(View.GONE);
        }
    }

    /**
     * 通知多设备布局刷新
     *
     * @param sessionOnlineEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void multiLoginDeviceSessionOnline(SessionOnlineEvent sessionOnlineEvent) {
        if (sessionOnlineEvent != null && sessionOnlineEvent.getType() == SessionOnlineEvent.TYPE_SESSION_ONLINE) {
            //if(threadMultiLoginDevice!=null){
            //ThreadManager.getThreadPool().execute(threadMultiLoginDevice);
            requestLoginDevice();

            //}

        }
    }


    private boolean isFling;
    private int topMutilDeviceViewHeight;

    /**
     * 添加头部的搜索 设备登录网络提示布局
     */
    @SuppressLint("ClickableViewAccessibility")
    private void addHeaderLayout() {
        topHintView = LayoutInflater.from(_mActivity).inflate(R.layout.item_chat_list_swipemenu_top_layout, null);
        topMutilDeviceView = LayoutInflater.from(_mActivity).inflate(R.layout.item_chat_list_swipemenu_top_mutil_device_layout, null);
        listView.addHeaderView(topHintView);
        listView.addHeaderView(topMutilDeviceView);
        ll_search = topHintView.findViewById(R.id.ll_search);
        ll_search.setVisibility(View.GONE);
        topMutilDeviceView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                topMutilDeviceViewHeight = topMutilDeviceView.getMeasuredHeight();
                topMutilDeviceView.removeOnLayoutChangeListener(this);
            }
        });
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                //停止滑动
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    isFling = false;
//                    LogUtils.e("SCROLL_STATE_IDLE----》" + topHintView.getTop());
                    topScroll();
                }
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
                    isFling = true;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
        listView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    downY = event.getY();
                } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    moveY = event.getY();
                    //判断上下滑动
                    if (downY > moveY) {
                        isUp = true;
                    } else {
                        isUp = false;
                    }
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    topScroll();
                }
                return false;
            }
        });
    }


    /**
     * 顶部布局滚动处理
     */
    private int lastTopScroller = 0;
    private int tempTopScroller = 0;

    private void topScroll() {

//        LogUtils.e("topScroll----->" + topHintView.getTop());

        //topView距离顶部滚动的距离
        int topScrollerLength = Math.abs(topHintView.getTop());

        tempTopScroller = topScrollerLength;
        if (lastTopScroller == tempTopScroller) {
            topScrollerLength = 11111;
        }
        //距部滑动的临界点（滑动点）
        int topCriticalLength = ConvertUtils.dp2px(11);
        //底部的临界点（滑动点）
        int bottomCriticalLength = searchHeight - topCriticalLength;
        //判断下滑不到临界点
        boolean isDownCritical = (topScrollerLength >= bottomCriticalLength && topScrollerLength < searchHeight);
        if (isUp && (topScrollerLength > topCriticalLength && topScrollerLength < searchHeight)) {
            //如果是上滑，并且topView滑动距离高于20小于搜索框的高度，执行本次滑动
            listView.smoothScrollBy(searchHeight + topHintView.getTop(), scrollTime);
        } else if (!isUp && topScrollerLength < bottomCriticalLength && topScrollerLength > 0) {
            //如果是下滑，并且topView滑动距离小于搜索框的高度，执行本次滑动
            listView.smoothScrollBy(topHintView.getTop(), scrollTime);
        } else if (isUp && topScrollerLength <= topCriticalLength) {
            //如果是上滑，topView距离顶部的滑动距离不到20，让列表滑回去
            listView.smoothScrollBy(topHintView.getTop(), scrollTime);
        } else if (!isUp && isDownCritical) {
            //下滑不到临界点
            listView.smoothScrollBy(searchHeight + topHintView.getTop(), scrollTime);
        }
        lastTopScroller = tempTopScroller;

    }

}
