package com.efounder.chat.publicnumber;

import android.annotation.SuppressLint;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import androidx.fragment.app.FragmentTransaction;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.activity.BaseActivity;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.model.Group;
import com.efounder.chat.service.MessageService;
import com.efounder.chat.struct.MessageChildTypeConstant;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.widget.ChatListView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.Constants;
import com.efounder.message.manager.JFMessageListener;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.utils.ResStringUtil;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.efounder.frame.utils.NetStateBroadcastReceiver.isNetActive;

/**
 * 聊天Activity
 *
 * @author hudq
 */
@SuppressLint("ClickableViewAccessibility")
public class PublicChatActivity_old extends BaseActivity implements
        PublicChatSenderFragment.OnVoiceRecordListener, PublicChatSenderFragment
        .OnClickMessageEditTextListener,
        PublicChatSenderFragment.SendMessageCallback, PublicChatOfficialAccountsSenderFragment
		.OnOfficialAccountKyeboardClickListener, MessageService.MessageServiceNetStateListener,
		MessageService.MessageServiceLoginListener {
    public static final String TAG = "PublicChatActivity";

    public static final String COPY_IMAGE = "EASEMOBIMG";

    private PublicChatSenderFragment publicChatSenderFragment;
    private PublicChatOfficialAccountsSenderFragment chatOfficialAccountsSenderFragment;

    /**
     * 语音容器（语音时显示在中间的麦克风容器）
     **/
    private View recordingContainer;
    /**
     * 麦克风图片
     **/
    private ImageView micImage;
    /**
     * 语音时 “手指上滑，取消发送” 提示
     **/
    private TextView recordingHint;
    /**
     * 麦克风动画资源文件,用于录制语音时
     **/
    private Drawable[] micImages;
    /**
     * 聊天ListView
     **/
    private ChatListView chatListView;
    /**
     * 聊天ListView 的 adapter
     **/
    private PublicChatAdapter chatAdapter;
    // private List<MessageBean> messageBeans;
    //private List<IMStruct002> iMStructAdpters;
    /**
     * 剪切板
     **/
    private ClipboardManager clipboard;
    private InputMethodManager manager;
    /**
     * 聊天类型：判断单聊，还是群聊，还是公众号
     **/
    private byte chatType;
    public static PublicChatActivity_old activityInstance = null;
    /**
     * 给谁发送消息
     **/
    private String toChatUsername;
    /**
     * 聊天对象id
     **/
    private int id;
    private Group group;
    private User user;
    /**
     * 下拉加载更多（转圈圈）
     **/
    private ProgressBar loadmorePB;
    private boolean isloading;
    private boolean haveMoreData = true;
    public String playMsgId;

    String myUserNick = "";
    String myUserAvatar = "";
    String toUserNick = "";
    String toUserAvatar = "";
    // 分享的照片
    String iamge_path = null;
    // 设置按钮
    private ImageView iv_setting;
    private ImageView iv_setting_group;


    /**
     * 左上角显示的用户名称
     **/
    private TextView toChatUserNickTextView;

    private PowerManager.WakeLock wakeLock;
    /**
     * 消息管理器
     **/
    private JFMessageManager messageManager;
    /**
     * 消息监听
     **/
    private JFMessageListener messageListener;

    private Handler messageHandler = new MessageHandler(this);
    List<IMStruct002> messageList;//消息记录

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

        public MessageHandler(PublicChatActivity_old activity) {
            weakReference = new WeakReference<PublicChatActivity_old>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            PublicChatActivity_old activity = weakReference.get();
            switch (msg.what) {
                case 1:
                    if (activity != null) {

                        activity.chatAdapter.notifyDataSetChanged();
                        activity.chatListView.setSelection(activity.chatListView
                                .getCount() - 1);
                    }
                    break;
                case 2:
                    activity.chatAdapter.notifyDataSetChanged();
                    activity.chatListView.setSelection(activity.chatListView.getCount());
                    break;

                default:
                    break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.publicactivity_chat_old);
        user = new User();
        id = getIntent().getIntExtra("id", 1);
        user = WeChatDBManager.getInstance().getOneOfficialNumber(id);

        Log.i(TAG, "onCreate------getIntent()----id:" + id);
        chatType = StructFactory.TO_USER_TYPE_PERSONAL;

        initAttr();
        initView();
        setUpView();
        Log.i(TAG, "onCreate-------------");
        MessageService.addMessageServiceLoginListener(this);
        MessageService.addMessageServiceNetStateListener(this);

    }

    @Override
    protected void onResume() {
        super.onResume();

        //判断是否显示网络不可用
        if (!isNetActive() || !JFMessageManager.isChannelActived()) {
            toChatUserNickTextView.setText(getIntent().getStringExtra("nickName") + "(网络不可用)");
        }

        if (chatAdapter != null) {

            chatAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 初始化一些属性
     */
    private void initAttr() {
        messageManager = JFMessageManager.getInstance();
        messageListener = new ChatMessageListener();
        messageManager.addMessageListener(EnvironmentVariable.getProperty(CHAT_USER_ID),
                messageListener);
    }

    /**
     * initView
     */
    protected void initView() {
        publicChatSenderFragment = (PublicChatSenderFragment) getSupportFragmentManager()
                .findFragmentById(R.id.fragment_chat_sender);
        publicChatSenderFragment.setOnClickMessageEditTextListener(this);
        publicChatSenderFragment.setOnVoiceRecordListener(this);
        publicChatSenderFragment.setSendMessageCallback(this);

        recordingContainer = findViewById(R.id.recording_container);
        micImage = (ImageView) findViewById(R.id.mic_image);
        recordingHint = (TextView) findViewById(R.id.recording_hint);
        chatListView = (ChatListView) findViewById(R.id.list);
        loadmorePB = (ProgressBar) findViewById(R.id.pb_load_more);
        toChatUserNickTextView = ((TextView) findViewById(R.id.name));

        iv_setting = (ImageView) this.findViewById(R.id.iv_setting);
        iv_setting_group = (ImageView) this.findViewById(R.id.iv_setting_group);


        chatOfficialAccountsSenderFragment = new PublicChatOfficialAccountsSenderFragment();
        chatOfficialAccountsSenderFragment
                .setOnOfficialAccountKyeboardClickListener(this);
        publicChatSenderFragment.setOnOfficialAccountKyeboardClickListener(this);

        FragmentTransaction fragmentTransaction = getSupportFragmentManager()
                .beginTransaction().add(
                        R.id.fragment_container_chat_sender,
                        chatOfficialAccountsSenderFragment,
                        "PublicChatOfficialAccountsSenderFragment");
        fragmentTransaction.hide(publicChatSenderFragment);
        fragmentTransaction.commit();
        iv_setting.setVisibility(View.VISIBLE);
        iv_setting_group.setVisibility(View.GONE);
        iv_setting.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

//                Intent intent = new Intent();
//                intent.setClass(PublicChatActivity.this,
//                        PublicNumerInfoActivity.class);
//                intent.putExtra("id", group.getGroupId());
//                intent.putExtra("chattype", chatType);
//                //startActivity(intent);

            }

        });


    }

    @SuppressWarnings("deprecation")
    private void setUpView() {
        activityInstance = this;
        clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE))
                .newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "demo");

        toChatUserNickTextView.setText(getIntent().getStringExtra("nickName"));


        messageList = JFMessageManager.getInstance().getMessageList(id, StructFactory.TO_USER_TYPE_PERSONAL);


        // TODO 获取历史消息
        List<IMStruct002> historyImStruct002s = null;
        int fromUserId = Integer.parseInt(EnvironmentVariable
                .getProperty(Constants.CHAT_USER_ID));
        int toUserId = user.getId();
        if (messageList.size() == 0) {
            historyImStruct002s = messageManager.getPersonalHistoryMessage(
                    fromUserId, toUserId, null, 20, null);
        }

        int unReadCount = JFMessageManager.getInstance().getUnReadCount(id, chatType);
        int tempCount = 0;
//        for (int i = messageList.size() - 1; i >= 0; i--) {
//            if (messageList.get(i).getFromUserId() != Integer.valueOf(EnvironmentVariable
//					.getUserID())
//                    && messageList.get(i).getState() != IMStruct002.MESSAGE_STATE_READ
//                    && messageList.get(i).getToUserType() != StructFactory.TO_USER_TYPE_GROUP) {
//                JFMessageManager.getInstance().sendReadMessage(messageList.get(i));
//                tempCount += 1;
//            }
//            if (tempCount == unReadCount) {
//                tempCount = 0;
//                break;
//            }
//
//        }


        // IMStruct002 imStruct002_4 = new IMStruct002();
        //
        // String body =
        // "{\"content\":[{\"title\":\"公众号头标题\",\"image\":\"assets://00.png\",
		// \"url\":\"http://www.sina.com.cn/\"},{\"title\":\"公共号底部标题\",\"image\":\"assets://01
		// .png\",\"url\":\"http://www.163.com/\"},{\"title\":\"公共号底部标题\",\"image\":\"assets://02
		// .png\",\"url\":\"http://www.163.com/\"}]}";
        // imStruct002_4.setBody(body.getBytes());
        // long time4 = 25978000;
        // imStruct002_4.setTime(time4);
        // byte childType4 = (byte) 2;
        // imStruct002_4.setToUserType(childType4);
        // byte messagechildType4 = (byte) 2;
        // imStruct002_4.setMessageChildType(messagechildType4);
        // iMStructAdpters.add(imStruct002_4);
        //
        // IMStruct002 imStruct002_5 = new IMStruct002();
        //
        // // String body =
        // //
        // "{\"content\":[{\"title\":\"公众号头标题\",\"image\":\"assets://00.png\",
		// \"url\":\"http://www.sina.com.cn/\"},{\"title\":\"公共号底部标题\",\"image\":\"assets://01
		// .png\",\"url\":\"http://www.163.com/\"},{\"title\":\"公共号底部标题\",\"image\":\"assets://02
		// .png\",\"url\":\"http://www.163.com/\"}]}";
        // // imStruct002_4.setBody(body.getBytes());
        // long time5 = 25978000;
        // imStruct002_5.setTime(time5);
        // byte childType5 = (byte) 0;
        // imStruct002_5.setToUserType(childType5);
        // byte messagechildType5 = (byte) 3;
        // imStruct002_5.setMessageChildType(messagechildType5);
        // iMStructAdpters.add(imStruct002_5);
        //
        IMStruct002 imStruct002_6 = new IMStruct002();

        String body = "{\"content\":[{\"title\":\"公众号头标题\",\"image\":\"assets://00.png\"," +
				"\"url\":\"http://www.sina.com.cn/\"},{\"title\":\"公共号底部标题\"," +
				"\"image\":\"assets://01.png\",\"url\":\"http://www.163.com/\"}," +
				"{\"title\":\"公共号底部标题\",\"image\":\"assets://02.png\",\"url\":\"http://www.163" +
				".com/\"}]}";
        imStruct002_6.setTime(System.currentTimeMillis());
        imStruct002_6.setFromUserId(0);
        imStruct002_6.setToUserId(54);
        imStruct002_6.setBody(body.getBytes());
        imStruct002_6.setToUserType(StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT);
        byte messagechildType6 = (byte) MessageChildTypeConstant.subtype_officalAccount;
        imStruct002_6.setMessageChildType(messagechildType6);
        imStruct002_6.setState(0);
        // iMStructAdpters.add(imStruct002_6);
        //
        // IMStruct002 imStruct002_7 = new IMStruct002();
        // // String body =
        // //
        // "{\"content\":[{\"title\":\"公众号头标题\",\"image\":\"assets://00.png\",
		// \"url\":\"http://www.sina.com.cn/\"},{\"title\":\"公共号底部标题\",\"image\":\"assets://01
		// .png\",\"url\":\"http://www.163.com/\"},{\"title\":\"公共号底部标题\",\"image\":\"assets://02
		// .png\",\"url\":\"http://www.163.com/\"}]}";
        // // imStruct002_4.setBody(body.getBytes());
        // imStruct002_7.setTime(25978000);
        // imStruct002_7.setToUserType((byte) 1);
        // imStruct002_7.setMessageChildType((byte) 5);
        // iMStructAdpters.add(imStruct002_7);
        //
        // // 加载图片
        // IMStruct002 imStruct002_8 = new IMStruct002();
        // imStruct002_8.setBody("assets://00.png".getBytes());
        // long time8 = 25978000;
        // imStruct002_8.setTime(time8);
        // byte childType8 = (byte) 0;
        // imStruct002_8.setToUserType(childType8);
        // byte messagechildType8 = (byte) 6;
        // imStruct002_8.setMessageChildType(messagechildType8);
        // iMStructAdpters.add(imStruct002_8);
        // // //加载语音
        // // IMStruct002 imStruct002_9 = new IMStruct002();
        // // imStruct002_9.setBody("assets://00.png".getBytes());
        // // long time9 = 25978000;
        // // imStruct002_9.setTime(time9);
        // // byte childType9 = (byte)1;
        // // imStruct002_9.setToUserType(childType9);
        // // byte messagechildType9 = (byte)7;
        // // imStruct002_9.setMessageChildType(messagechildType9);
        // // iMStructAdpters.add(imStruct002_9);
        //	messageList.add(imStruct002_6);

        chatAdapter = new PublicChatAdapter(this, chatListView, messageList);
        chatListView.setAdapter(chatAdapter);
        chatListView.setSelection(chatListView.getCount() - 1);
        chatListView.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        hideKeyboard();
                        break;
                    case MotionEvent.ACTION_UP:
                        v.performClick();
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
    }

    /**
     * 获取表情资源
     *
     * @param getSum
     * @return
     */
    public List<String> getExpressionRes(int getSum) {
        List<String> emoticonReslist = new ArrayList<String>();
        for (int x = 1; x <= getSum; x++) {
            String filename = "ee_" + x;
            emoticonReslist.add(filename);
        }
        return emoticonReslist;
    }

    /**
     * 返回
     *
     * @param view
     */
    @Override
    public void back(View view) {
        finish();
    }

    /**
     * 隐藏软键盘
     */
    private void hideKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams
                .SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                manager.hideSoftInputFromWindow(getCurrentFocus()
                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 麦克风图片懒加载
     *
     * @return
     */
    private Drawable[] getMicImages() {
        if (micImages == null) {
            // 动画资源文件,用于录制语音时
            micImages = new Drawable[]{
                    getResources().getDrawable(R.drawable.record_animate_01),
                    getResources().getDrawable(R.drawable.record_animate_02),
                    getResources().getDrawable(R.drawable.record_animate_03),
                    getResources().getDrawable(R.drawable.record_animate_04),
                    getResources().getDrawable(R.drawable.record_animate_05),
                    getResources().getDrawable(R.drawable.record_animate_06),
                    getResources().getDrawable(R.drawable.record_animate_07),
                    getResources().getDrawable(R.drawable.record_animate_08),
                    getResources().getDrawable(R.drawable.record_animate_09),
                    getResources().getDrawable(R.drawable.record_animate_10),
                    getResources().getDrawable(R.drawable.record_animate_11),
                    getResources().getDrawable(R.drawable.record_animate_12),
                    getResources().getDrawable(R.drawable.record_animate_13),
                    getResources().getDrawable(R.drawable.record_animate_14),};
        }
        return micImages;
    }

    @Override
    public void sendMessage(IMStruct002 struct002) {
        try {
            if (struct002 != null) {
                // FIXME
                // if (struct002.getMessageChildType() != 2 &&
                // struct002.getMessageChildType() != 9 ) {//排除公众号和阅后即焚
                // struct002.setToUserType((byte) (iMStructAdpters.size()%2));
                // }
                //	iMStructAdpters.add(struct002);
                //iMStructAdpters.clear();
                //iMStructAdpters.addAll(messageList);


//				chatAdapter.notifyDataSetChanged();
//				chatListView.setSelection(chatListView.getCount() - 1);
                // 存储发送的消息
                if (user != null) {
                    // MessageMap.putMessage(chatListItem.getUserId() + "",
                    // struct002);
                }

                // FIXME 测试发送文本
                //		if (struct002.getMessageChildType() == 0) {
                struct002.setToUserId(id);
                struct002.setFromUserId(Integer.parseInt(EnvironmentVariable
                        .getProperty(Constants.CHAT_USER_ID)));
                messageHandler.sendEmptyMessage(1);
                new AsyncTask<IMStruct002, Integer, String>() {

                    @Override
                    protected String doInBackground(IMStruct002... params) {
                        try {
                            IMStruct002 struct002 = params[0];
                            struct002.setToUserType((byte) 0);
                            boolean b = messageManager.sendMessage(struct002);
                            Log.i(TAG, "发送 ------ sendMessage:" + struct002.toString());
                            //XXX 判断网络是否连接，如果没连接，直接加入未发送队列
                            //if (!JFMessageManager.isChannelActive) {
                            //	ChatMessageQueue.unsendMessageList.add(struct002);
                            //}
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        return null;
                    }
                }.execute(struct002);

            }

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

    @Override
    public void onRecording(int musicalScale) {
        micImage.setImageDrawable(getMicImages()[musicalScale]);
    }

    @Override
    public void onRecorderButtonTouchDown(View v) {
        recordingContainer.setVisibility(View.VISIBLE);
        recordingHint.setText(getString(R.string.move_up_to_cancel));
        recordingHint.setBackgroundColor(Color.TRANSPARENT);
    }

    @Override
    public void onRecorderButtonTouchMove(View v, boolean isCancleRecord) {
        if (isCancleRecord) {
            recordingHint.setText(getString(R.string.release_to_cancel));
            recordingHint
                    .setBackgroundResource(R.drawable.recording_text_hint_bg);
        } else {
            recordingHint.setText(getString(R.string.move_up_to_cancel));
            recordingHint.setBackgroundColor(Color.TRANSPARENT);
        }

    }

    @Override
    public void onRecorderButtonTouchUp(View v) {
        recordingContainer.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onRecorderButtonTouchCancle(View v) {
        recordingContainer.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onClickMessageEditText(View v) {
        chatListView.setSelection(chatListView.getCount() - 1);
    }

    @Override
    public void onOfficialAccountKyeboardClick(View v,
                                               boolean isClickFromOfficialAccountView) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager()
                .beginTransaction();
        if (publicChatSenderFragment.isVisible()) {
            fragmentTransaction.hide(publicChatSenderFragment);
            fragmentTransaction.show(chatOfficialAccountsSenderFragment);
        } else {
            fragmentTransaction.hide(chatOfficialAccountsSenderFragment);
            fragmentTransaction.show(publicChatSenderFragment);
        }
        fragmentTransaction.commit();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, TAG + "-----------requestCode:" + requestCode
                + ",resultCode" + resultCode);
    }

    /**
     * 回话界面各种消息状态的监听
     *
     * @author hudq
     */
    private class ChatMessageListener implements JFMessageListener {

        @Override
        public void onReceive(final IMStruct002 imstruct002) {
            // XXX
            // 判断 如果不是系统消息（100代表系统消息）
            if (imstruct002.getMessageChildType() < 100) {
                JFMessageManager.getInstance().sendReadMessage(imstruct002);
                switch (imstruct002.getToUserType()) {
                    case StructFactory.TO_USER_TYPE_PERSONAL:
                        if (id == imstruct002.getFromUserId()) {
                            //iMStructAdpters.add(imstruct002);
                            //iMStructAdpters.clear();
                            //iMStructAdpters.addAll(messageList);
                        }
                        break;
                    case StructFactory.TO_USER_TYPE_GROUP:
                        if (id == imstruct002.getToUserId()) {
                            int sendMessageUserId = imstruct002.getFromUserId();//表示给你发消息的那个人，如张三李四
                            User currentUser = null;
                            currentUser = WeChatDBManager.getInstance().getOneFriendById(sendMessageUserId);
                            if (currentUser == null) {
                                currentUser = WeChatDBManager.getInstance().getOneUserById(sendMessageUserId);
                            }
                            if (currentUser == null) {
                                GetHttpUtil.getUserInfo(sendMessageUserId, PublicChatActivity_old.this, null);
                            } else {
                                //iMStructAdpters.add(imstruct002);
                                //iMStructAdpters.clear();
                                //iMStructAdpters.addAll(messageList);
                            }


                        }
                        break;
                    case StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT:

                        break;

                    default:
                        break;
                }
                messageHandler.sendEmptyMessage(1);
                Log.i(TAG, "onReceive------消息状态：" + imstruct002.toString());
            }
        }

        @Override
        public void onUpdate(int i, IMStruct002 imstruct002) {
            Log.i(TAG, "onUpdate------消息状态：" + imstruct002.toString());
            //iMStructAdpters.clear();
            //iMStructAdpters.addAll(messageList);


            messageHandler.sendEmptyMessage(1);
        }

        @Override
        public void onFailure(int i, IMStruct002 imstruct002) {
            Log.i(TAG, "onFailure------消息状态：" + imstruct002.toString());
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        super.onNewIntent(intent);
        id = intent.getIntExtra("id", 1);
        chatType = intent.getByteExtra("chattype",
                StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT);
        if (chatType == StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT) {
            user = WeChatDBManager.getInstance().getOneFriendById(id);
            initView();
            setUpView();
        }


    }

    @Override
    protected void onDestroy() {
        if (messageListener != null) {
            messageManager.removeMessageListener(EnvironmentVariable.getProperty(CHAT_USER_ID),
                    messageListener);
        }
        MessageService.removeMessageServiceLoginListener(this);
        MessageService.removeMessageServiceNetStateListener(this);
        super.onDestroy();
    }


    @Override
    public void netStateChange(int net_state) {
        Log.i(TAG, "netStateChange--监听网络状态--" + net_state);
        if (net_state == 0) {
            // rl_error_item.setVisibility(View.VISIBLE);
            Message message = new Message();
            message.what = 0;

            this.netStateChangeHandler.sendMessage(message);
        } else {
            //rl_error_item.setVisibility(View.GONE);

            Message message = new Message();
            message.what = 1;

            this.netStateChangeHandler.sendMessage(message);
        }
    }

    //处理网络监听状态handle
    Handler netStateChangeHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    toChatUserNickTextView.setText(toChatUserNickTextView.getText() + ResStringUtil.getString(R.string.wrchatview_network_unavailable));
                    break;
                case 1:
                    toChatUserNickTextView.setText(getIntent().getStringExtra("nickName"));

                    break;
            }
            super.handleMessage(msg);
        }
    };

    //监听tcp是否可用事件
    @Override
    public void onLoginSuccess() {
        Message message = new Message();
        message.what = 1;

        this.netStateChangeHandler.sendMessage(message);
    }

    @Override
    public void onLoginFail(String errorMsg) {

    }

}
