package com.lianxin.pubqq.chat;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.lianxin.pubqq.R;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

import com.lianxin.panqq.chat.chatrow.EMChatRow;
import com.lianxin.panqq.chat.chatrow.EMCustomChatRowProvider;
import com.lianxin.panqq.chat.emojicon.EMEmojicon;
import com.lianxin.panqq.chat.entity.BigExpressMessageBody;
import com.lianxin.panqq.main.EMChatManager;
import com.lianxin.panqq.main.EMSendManager;
import com.lianxin.panqq.chat.EMConversation;
import com.lianxin.panqq.chat.entity.CallMessageBody;
import com.lianxin.panqq.chat.entity.CustomMessageBody;
import com.lianxin.panqq.chat.entity.EMMessage;
import com.lianxin.panqq.chat.entity.ImageMessageBody;
import com.lianxin.panqq.chat.entity.LocationMessageBody;
import com.lianxin.panqq.chat.entity.NormalFileMessageBody;
import com.lianxin.panqq.chat.entity.TextMessageBody;
import com.lianxin.panqq.chat.entity.VideoMessageBody;
import com.lianxin.panqq.chat.entity.VoiceMessageBody;
import com.lianxin.panqq.chat.utils.CommonUtils;
import com.lianxin.panqq.chat.utils.MediaUtils;
import com.lianxin.panqq.chat.widget.EMChatInputMenu;
import com.lianxin.panqq.chat.widget.EMChatExtendMenu;
import com.lianxin.panqq.chat.widget.EMChatMessageList;
import com.lianxin.panqq.chat.widget.EMTitleBar;
import com.lianxin.panqq.chat.widget.EMVoiceRecorderView;
import com.lianxin.panqq.chat.widget.EMVoiceRecorderView.EMVoiceRecorderCallback;
import com.lianxin.panqq.client.callback.askCallBack;
import com.lianxin.panqq.common.DefineChat;
import com.lianxin.panqq.common.DefineMedia;
import com.lianxin.panqq.common.GloableParams;
import com.lianxin.panqq.common.PermissionChecker;
import com.lianxin.panqq.common.Utils;
import com.lianxin.panqq.common.bean.CustomMessage;
import com.lianxin.panqq.edit.MyAlertDialog;
import com.lianxin.pubqq.activity.FriendInfoActivity;
import com.lianxin.pubqq.activity.MemberInfoActivity;
import com.lianxin.pubqq.extend.file.FileManager;
import com.lianxin.pubqq.extend.UserDetailActivity;
import com.lianxin.pubqq.extend.GroupSettingActivity;
import com.lianxin.pubqq.main.MyApp;
import com.lianxin.pubqq.nearby.NearbyInfoActivity;
import com.lianxin.pubqq.ulive.GroupAudioActivity;
import com.lianxin.pubqq.ulive.GroupVideoActivity;
import com.lianxin.pubqq.ulive.MeetingAudioActivity;
import com.lianxin.pubqq.ulive.MeetingVideoActivity;
import com.lianxin.pubqq.ulive.VideoPhoneActivity;
import com.lianxin.pubqq.ulive.VoicePhoneActivity;
import com.lianxin.panqq.main.PathUtil;
import com.lianxin.panqq.main.bean.RecentItem;
import com.lianxin.panqq.picker.MenuDialog;
import com.lianxin.panqq.utils.FileUtils;

/*有两个聊天窗口，功能完全一样，都正常，都在调用（更新时注意同步）
 * EMChatFragment(EMChatActivity)
 * IMChatActivity
 */
//聊天页面1
public class EMChatFragment extends Fragment {
    protected static final String TAG = "EMChatFragment";
    protected static final int REQUEST_CODE_MAP = 1;
    protected static final int REQUEST_CODE_CAMERA = 2;
    protected static final int REQUEST_CODE_LOCAL = 3;

	public static final int CHATMODE_SINGLE = 1;
	public static final int CHATMODE_GROUP = 2;   
	
	public static final int RESULT_CODE_COPY = 1;
	public static final int RESULT_CODE_DELETE = 2;
	public static final int RESULT_CODE_CANCEL = 8;	
	public static final int RESULT_CODE_FORWARD = 3;
	public static final int RESULT_CODE_OPEN = 4;
	public static final int RESULT_CODE_DWONLOAD = 5;
	public static final int RESULT_CODE_TO_CLOUD = 6;
	public static final int RESULT_CODE_EXIT_GROUP = 7;
	public static final int RESULT_CODE_MARK = 9;	
	// 给谁发送消息
	private String toChatUsername;
	public int toChatDestid;
	public int chatType;
	private int chatMode;	//1:单聊  2:群聊 
	private int myPlayId;	//登录用户或者局域网用户
	protected EMConversation conversation;	
    protected Bundle fragmentArgs;

    protected EMTitleBar titleBar;  
    protected InputMethodManager inputMethodManager;    
    protected EMChatMessageList messageList;
    protected EMChatInputMenu inputMenu;
    
    protected InputMethodManager inputManager;
    protected ClipboardManager clipboard;

    protected Handler handler = new Handler();
    protected File cameraFile;
    protected EMVoiceRecorderView voiceRecorderView;
    protected ListView listView;

    protected boolean isloading;
    protected boolean haveMoreData = true;
    protected int pagesize = 20;
    protected EMMessage contextMenuMessage;
    
    static final int ITEM_TAKE_PICTURE = 1;
    static final int ITEM_PICTURE = 2;
    static final int ITEM_LOCATION = 3;
    static final int ITEM_VIDEO = 4;
    static final int ITEM_FILE = 5;
    static final int ITEM_OFFLINEFILE = 6;     
    static final int ITEM_CALLVIDEO = 7;
    static final int ITEM_CALLVOICE = 8;
  
    private static final int REQUEST_CODE_SELECT_VIDEO = 11;
    private static final int REQUEST_CODE_SELECT_FILE = 12;
    private static final int REQUEST_CODE_SELECT_OFFLINEFILE = 16;    
    private static final int REQUEST_CODE_GROUP_DETAIL = 13;
    private static final int REQUEST_CODE_CONTEXT_MENU = 14;
    private static final int REQUEST_CODE_SELECT_AT_USER = 15;    
    
    protected int[] itemStrings = { R.string.attach_take_pic, R.string.attach_picture, R.string.attach_location, 
    		R.string.attach_video, R.string.attach_file, R.string.attach_offlinefile, R.string.attach_video_call, R.string.attach_voice_call };
    protected int[] itemdrawables = { R.drawable.chat_takepic_selector, R.drawable.chat_image_selector,
            R.drawable.chat_location_selector,R.drawable.chat_video_selector, R.drawable.chat_file_selector,
            R.drawable.chat_file_selector,R.drawable.chat_video_call_selector,R.drawable.chat_voice_call_selector };
    protected int[] itemIds = { ITEM_TAKE_PICTURE, ITEM_PICTURE, ITEM_LOCATION,ITEM_VIDEO,ITEM_FILE,ITEM_OFFLINEFILE,ITEM_CALLVIDEO,ITEM_CALLVOICE };
    private boolean isMessageListInited;
    protected MyItemClickListener extendMenuItemClickListener;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.em_fragment_chat, container, false);
    
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        fragmentArgs = getArguments();
  
        super.onActivityCreated(savedInstanceState);
        initView();
        setUpView();  
        
        updataUses();	//从服务器刷新谈话双方的最新设置       
    }

    /**
     * init view
     */
    protected void initView() {
        inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);   	
        titleBar = (EMTitleBar) getView().findViewById(R.id.title_bar);      
        voiceRecorderView = (EMVoiceRecorderView) getView().findViewById(R.id.voice_recorder);
        messageList = (EMChatMessageList) getView().findViewById(R.id.message_list);

        listView = messageList.getListView();   
        extendMenuItemClickListener = new MyItemClickListener();
        inputMenu = (EMChatInputMenu) getView().findViewById(R.id.input_menu);
		chatType = getActivity().getIntent().getIntExtra("Chat_Type", 1);  //为了下面的扩展菜单取出单聊还是群聊      
		//注册扩展菜单
        registerExtendMenuItem();
        //注册键盘输入窗口
        inputMenu.init(null);
        inputMenu.setChatInputMenuListener(new EMChatInputMenu.ChatInputMenuListener() {

            @Override
            public void onSendMessage(String content) {
                sendTextMessage(content);
            }

            @Override
            public boolean onPressToSpeakBtnTouch(View v, MotionEvent event) {

                return voiceRecorderView.onPressToSpeakBtnTouch(v, event, new EMVoiceRecorderCallback() {
                    
                    @Override
                    public void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {
                        sendVoiceMessage(voiceFilePath, voiceTimeLength);
						Toast.makeText(getActivity(), "发送成功1", Toast.LENGTH_SHORT).show();                        
                    }

					@Override
					public void onVoiceStartRecording(String voiceFilePath) {
		            	voiceRecorderView.setVoiceFileName(myPlayId,conversation.getUserTimeStamp());	
					}
                });
            }

            @Override
            public void onBigExpressionClicked(EMEmojicon emojicon) {

                sendBigExpressionMessage(emojicon);                   
            }
        });

        inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }

    protected void setUpView() {
    	//聊天对象ID和昵称
		toChatDestid = getActivity().getIntent().getIntExtra("Chat_ID",10002);
		toChatUsername = getActivity().getIntent().getStringExtra("Chat_Name");	
		// 判断单聊还是群聊		
		chatType = getActivity().getIntent().getIntExtra("Chat_Type", 1);		
		if(chatType<5)
		    chatMode =	CHATMODE_SINGLE;
		else
		    chatMode =	CHATMODE_GROUP;
		//自己的ID		
		myPlayId = GloableParams.m_szUserId; 
		if(chatType<5&&toChatDestid<=10000)
			myPlayId =	1000;	
		//初始化顶部工具栏		
		initTitleBar();	
		//初始化会话记录数据
        onConversationInit();
        //初始化消息列表       
        onMessageListInit();
        //页面刷新监听（没用到没实现）
        setRefreshLayoutListener();
        //注册新消息监听
        setReceiverMessageListener();
	
        String forward_msg_id = getArguments().getString("forward_msg_id");
        if (forward_msg_id != null) {
            forwardMessage(forward_msg_id);
        }
    }
 
	//刷新谈话双方的最新设置
	private void updataUses() {
		if(conversation==null)
			return;
		conversation.updataUsers(new askCallBack(){				
			@Override
			public void onSuccess(int statusCode, String message) {	
				final String str = message;				
				getActivity().runOnUiThread(new Runnable() {
					public void run() {											
						Utils.showLongToast(getActivity(), str);						
					}
				});				
			}
			@Override
			public void onFailure(int statusCode,  String message) {
				final String str = message;
				getActivity().runOnUiThread(new Runnable() {
					public void run() {						
						Utils.showLongToast(getActivity(), str);
					}
				});	
			}
		});		
	}   
    
    public void initTitleBar(){
		if (chatMode == CHATMODE_SINGLE) { // 单聊				
			titleBar.setTitle(toChatUsername);	
	        titleBar.setRightImageResource(R.drawable.icon_chat_user); 					
		}else if (chatMode == 0) { // 客服 
		}else {	
            titleBar.setTitle(toChatUsername);			
        	titleBar.setRightImageResource(R.drawable.icon_groupinfo);						
		}
    	titleBar.setLeftImageResource(R.drawable.icon_back);
        titleBar.setLeftLayoutClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
             //   getActivity().finish();
    			Utils.finish(getActivity());                
            }
        });
        titleBar.setRightLayoutClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
        		if (chatMode == CHATMODE_SINGLE) { // 单聊				
        			Intent Friendintent = new Intent(getActivity(), UserDetailActivity.class);
        			Friendintent.putExtra("USER_ID",toChatDestid);
        			Friendintent.putExtra("USER_Type",chatType);
        			Friendintent.putExtra("USER_Name",toChatUsername);			
        			startActivity(Friendintent);	

        		}else {// 群聊
        			//  打开群组详情页面
        			Intent Groupintent = new Intent(getActivity(), GroupSettingActivity.class);			
        			Groupintent.putExtra("Chat_ID",toChatDestid);
        			Groupintent.putExtra("Chat_Type",chatType);
        			Groupintent.putExtra("Chat_Name",toChatUsername);				
        			startActivity(Groupintent);	
 		
        		}
            }
        });  
    }
 
    public void showTitleBar(){
        if(titleBar != null){
            titleBar.setVisibility(View.VISIBLE);
        }
    }    
    
    public void hideTitleBar(){
        if(titleBar != null){
            titleBar.setVisibility(View.GONE);
        }
    }
    
    protected void hideSoftKeyboard() {
        if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getActivity().getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }   
    //注册扩展菜单
    protected void registerExtendMenuItem(){
    	if(chatType>=5)
    		itemStrings[5] = R.string.attach_sharefile;
        for(int i = 0; i < itemStrings.length; i++){
            inputMenu.registerExtendMenuItem(itemStrings[i], itemdrawables[i], itemIds[i], extendMenuItemClickListener);
        }
    }
    
    //初始化会话记录数据  
    protected void onConversationInit(){

		conversation = EMChatManager.getInstance().getornewConversation(toChatDestid,chatType);		
		if (chatMode == CHATMODE_SINGLE) { // 单聊				
			conversation.initUserInfo();					
		}else if (chatMode == 0) { // 客服 
		}else {// 群聊
			conversation.initGroupInfo(toChatDestid,chatType);			
		}	
		// 把此会话的未读数置为0
		conversation.resetUnsetMsgCount();      
    }
    //初始化消息列表窗口  
    protected void onMessageListInit(){
   
        EMCustomChatRowProvider customChatRowProvider = new CustomChatRowProvider(); 
        messageList.init(toChatDestid, chatType, customChatRowProvider);       
        setListItemClickListener();
        
        messageList.getListView().setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
              //  hideKeyboard();
                hideSoftKeyboard();               
                inputMenu.hideExtendMenuContainer();
                return false;
            }
        });
        
        isMessageListInited = true;
   
    }
    //点击事件监听    
    protected void setListItemClickListener() {
        messageList.setItemClickListener(new EMChatMessageList.MessageListItemClickListener() {
            
            @Override
            public void onUserAvatarClick(EMMessage message) {           	
            	onMyUserAvatarClick(message);
  
            }
            
            @Override
            public void onUserAvatarLongClick(EMMessage message) { 	          	
            	onMyUserAvatarLongClick(message);        	
            }
            
            @Override
            public void onResendClick(final EMMessage message) {
            	onMyResendClick(message);
            }
            
            @Override
            public void onBubbleLongClick(EMMessage message) {
            	onMyBubbleLongClick(message);
            }
            
            @Override
            public boolean onBubbleClick(EMMessage message) {
            	onMyBubbleClick(message);
 
                return false; 
            }

        });
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST_CODE_CONTEXT_MENU) {		
			switch (resultCode) {
			case RESULT_CODE_COPY: // 复制消息
				EMMessage copyMsg = contextMenuMessage;
				if (copyMsg.getMsgType() == EMMessage.MsgType.MSG_IMAGE) {
					ImageMessageBody imageBody = (ImageMessageBody) copyMsg.getBody();
					// 加上一个特定前缀，粘贴时知道这是要粘贴一个图片
					clipboard.setText("COPY_IMAGE" + imageBody.getLocalUrl());
				} else {
					// clipboard.setText(SmileUtils.getSmiledText(ChatActivity.this,
					// ((TextMessageBody) copyMsg.getBody()).getMessage()));
					clipboard.setText(((TextMessageBody) copyMsg.getBody()).getMessage());
				}
				break;
			case RESULT_CODE_DELETE: // 删除消息
				EMMessage deleteMsg = contextMenuMessage;
				conversation.removeMessage(deleteMsg.getMsgId());
	
				break;

			case RESULT_CODE_CANCEL: // 撤回消息
				EMMessage cancelMsg = contextMenuMessage;
				conversation.cancelMessage(cancelMsg.getMsgId());
				int position = data.getIntExtra("position", -1);				
				
				break;				
			case RESULT_CODE_MARK: // 点赞消息
  				EMMessage markMsg = contextMenuMessage;
  				conversation.markMessage(markMsg.getMsgId()); 			
  				break; 			
			case RESULT_CODE_FORWARD: // 转发消息
				EMMessage forwardMsg = contextMenuMessage;
				Intent intent = new Intent(getActivity(), ForwardMessageActivity.class);
				intent.putExtra("forward_msgid", forwardMsg.getMsgId());
				intent.putExtra("src_destid", toChatDestid);
				intent.putExtra("src_type", chatType);				
				startActivity(intent);
				break;
			default:
				break;
			}
		}      
        if (resultCode == Activity.RESULT_OK) { 
            if (requestCode == REQUEST_CODE_CAMERA) { // capture new image
                if (cameraFile != null && cameraFile.exists())
                    sendImageMessage(cameraFile.getAbsolutePath());
            } else if (requestCode == REQUEST_CODE_LOCAL) { // send local image
                if (data != null) {
                    Uri selectedImage = data.getData();
                    if (selectedImage != null) {
                        sendPicByUri(selectedImage);
                    }
                }
            } else if (requestCode == REQUEST_CODE_MAP) { // location
                double latitude = data.getDoubleExtra("latitude", 0);
                double longitude = data.getDoubleExtra("longitude", 0);
                String locationAddress = data.getStringExtra("address");
                if (locationAddress != null && !locationAddress.equals("")) {
                    sendLocationMessage(latitude, longitude, locationAddress);
                } else {
                    Toast.makeText(getActivity(), R.string.unable_to_get_loaction, 0).show();
                }
			} else if (requestCode == REQUEST_CODE_SELECT_FILE) { // 发送选择的文件
				String chooseFile = PathUtil.chooseFile;						
				if (chooseFile != null && !chooseFile.equals("")) {
			        sendFileMessage(chooseFile);					
				} else {
					Toast.makeText(getActivity(), "你没有选中文件！", 0).show();
				} 
 			} else if (requestCode == REQUEST_CODE_SELECT_OFFLINEFILE) { // 发送选择的文件
				 
                if (data != null) {
                    Uri uri = data.getData();
                    if (uri != null) {
             	
              		    Intent intent = new Intent(getActivity(), UploadFileActivity.class);
              		    intent.putExtra("uri", uri); 
             		    intent.putExtra("sendid", myPlayId);
            		    intent.putExtra("destid", toChatDestid); 
             		    intent.putExtra("chattype", chatType); 
             			if (myPlayId <= 10000) { // 局域网用户只能在线发送				
             				intent.putExtra("mode", UploadFileActivity.FILE_ONLINE);            		    
             			}else if (chatMode == CHATMODE_SINGLE) { // 单聊				
             				intent.putExtra("mode", UploadFileActivity.FILE_OFFLINE);					
             			}else {// 群聊
             				intent.putExtra("mode", UploadFileActivity.FILE_SHARE);			
             			}           		    
              		    getActivity().startActivity(intent);                    	
                    }
                } 				
			} else if (requestCode == REQUEST_CODE_SELECT_VIDEO) { // 发送本地选择的视频
                if (data != null) {
                    int duration = data.getIntExtra("dur", 0);
                    String videoPath = data.getStringExtra("path");
    				String fileName = "tv" + conversation.getUserTimeStamp() + ".jpg";				
    				File file = new File(PathUtil.getInstance().getVideoPath(), fileName);
                    try {
                        FileOutputStream fos = new FileOutputStream(file);
                        Bitmap ThumbBitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3);
                        ThumbBitmap.compress(CompressFormat.JPEG, 100, fos);
                        fos.close();
                        sendVideoMessage(videoPath, file.getAbsolutePath(), duration);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
			
            }
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        if(isMessageListInited)
            messageList.refresh();

    }
    
    @Override
    public void onStop() {
        super.onStop();
  
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
		// 注销广播
		try {
			getActivity().unregisterReceiver(newMessageReceiver);
			newMessageReceiver = null;
		} catch (Exception e) {
		}
		try {
			getActivity().unregisterReceiver(ackMessageReceiver);
			ackMessageReceiver = null;
			getActivity().unregisterReceiver(deliveryAckMessageReceiver);
			deliveryAckMessageReceiver = null;			
		} catch (Exception e) {
		}              
    }

    public void onBackPressed() {
        if (inputMenu.onBackPressed()) {
            Utils.finish(getActivity());
        }
    }
    
    
    protected void setRefreshLayoutListener() {

    }
    //注册新消息事件监听
	NewMessageBroadcastReceiver newMessageReceiver = new NewMessageBroadcastReceiver();   
    protected void setReceiverMessageListener() {
		// 注册接收消息广播
		IntentFilter intentFilter = new IntentFilter(MyApp.getInstance().getNewMessageBroadcastAction());
		// 设置广播的优先级别大于Mainacitivity,这样如果消息来的时候正好在chat页面，直接显示消息，而不是提示消息未读
		intentFilter.setPriority(5);
		getActivity().registerReceiver(newMessageReceiver, intentFilter);

		// 注册一个ack回执消息的BroadcastReceiver
		IntentFilter ackMessageIntentFilter = new IntentFilter(MyApp.getInstance().getAckMessageBroadcastAction());		
		ackMessageIntentFilter.setPriority(5);
		getActivity().registerReceiver(ackMessageReceiver, ackMessageIntentFilter);

		// 注册一个消息送达的BroadcastReceiver
		IntentFilter deliveryAckMessageIntentFilter = new IntentFilter(MyApp.getInstance()
						.getDeliveryAckMessageBroadcastAction());
		deliveryAckMessageIntentFilter.setPriority(5);
		getActivity().registerReceiver(deliveryAckMessageReceiver,deliveryAckMessageIntentFilter);
     }    
 
	/**
	 * 消息广播接收者
	 * 
	 */
	private class NewMessageBroadcastReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {

			int Destid = getActivity().getIntent().getIntExtra("Chat_ID",10002);
			int Type = getActivity().getIntent().getIntExtra("Chat_Type", 0);
			if (toChatDestid != Destid || chatType != Type) {
				// 消息不是发给当前会话，return
				return;
			}			
			// 通知adapter有新消息，更新ui

		    messageList.refresh();			
			// 记得把广播给终结掉
			abortBroadcast();
		}
	}

	/**
	 * 消息回执BroadcastReceiver
	 */
	private BroadcastReceiver ackMessageReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String msgid = intent.getStringExtra("msgid");
			String from = intent.getStringExtra("from");
			EMConversation conversation = EMChatManager.getInstance().getConversation(from);
			if (conversation != null) {
				// 把message设为已读
				EMMessage msg = conversation.getMessage(msgid);
				if (msg != null) {
					msg.isAcked = true;
				}
			}
			abortBroadcast();
		    messageList.refresh();			
		}
	};
	/**
	 * 消息送达BroadcastReceiver
	 */
	private BroadcastReceiver deliveryAckMessageReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			abortBroadcast();

		}
	};    
   
    /**
     * chat row provider 
     *自定义消息
     */
    private final class CustomChatRowProvider implements EMCustomChatRowProvider {
        @Override
        public int getCustomChatRowTypeCount() {
 
            return 8;
        }

        @Override
        public int getCustomChatRowType(EMMessage message) {
            if(message.getMsgType() == EMMessage.MsgType.MSG_CUSTOM){
                //voice call
               /* if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false)){
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VOICE_CALL : MESSAGE_TYPE_SENT_VOICE_CALL;
                }else if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VIDEO_CALL, false)){
                    //video call
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VIDEO_CALL : MESSAGE_TYPE_SENT_VIDEO_CALL;
                }else if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_MESSAGE, false)) {
                    //sent redpacket message
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_MONEY : MESSAGE_TYPE_SEND_MONEY;
                } else if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_ACK_MESSAGE, false)) {
                    //received redpacket message
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_LUCKY : MESSAGE_TYPE_SEND_LUCKY;
                }*/
            }
            return 0;
        }

        @Override
        public EMChatRow getCustomChatRow(EMMessage message, int position, BaseAdapter adapter) {
            if(message.getMsgType() == EMMessage.MsgType.MSG_CUSTOM){
                // voice call or video call
               /* if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false) ||
                    message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VIDEO_CALL, false)){
                    return new ChatRowVoiceCall(getActivity(), message, position, adapter);
                }else if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_MESSAGE, false)) {//send redpacket
                    return new ChatRowRedPacket(getActivity(), message, position, adapter);
                } else if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_ACK_MESSAGE, false)) {//open redpacket message
                    return new ChatRowRedPacketAck(getActivity(), message, position, adapter);
                }*/
            }
            return null;
        }

    }	
    /**
     * handle the click event for extend menu
     *
     */
    class MyItemClickListener implements EMChatExtendMenu.EMChatExtendMenuItemClickListener {

        @Override
        public void onClick(int itemId, View view) {

            switch (itemId) {
            case ITEM_TAKE_PICTURE:
                selectPicFromCamera();
                break;
            case ITEM_PICTURE:
                selectPicFromLocal();
                break;
            case ITEM_LOCATION:
            	//由于百度地图API_KEY总是过期导致调用崩溃，暂时屏蔽。用作自定义消息入口。
                //startActivityForResult(new Intent(getActivity(), BaiduMapActivity.class), REQUEST_CODE_MAP);
                sendCustomMessage( DefineChat.EM_SHAKEWINDOW, 10000 );             
                break;
            case ITEM_VIDEO:
    			Intent intent1 = new Intent(getActivity(), ImageGridActivity.class);
    			startActivityForResult(intent1, REQUEST_CODE_SELECT_VIDEO);
                break;
            case ITEM_FILE:
    			PathUtil.chooseFile = "";
    			Intent intent = new Intent(getActivity(), FileManager.class);
    			intent.putExtra("selectType",1);			
    			startActivityForResult(intent, REQUEST_CODE_SELECT_FILE);           	
                break;
            case ITEM_OFFLINEFILE:
            	selectFileFromLocal();
            	break;                 
            case ITEM_CALLVIDEO:
        		if (chatMode == CHATMODE_SINGLE) // 单聊            	
        			startVideoUser();       			
            	else    	
                	startVideoGroup();           	    
                break;
            case ITEM_CALLVOICE:

        		if (chatMode == CHATMODE_SINGLE) // 单聊            	
        			startVoiceUser();       			
            	else    	
                	startVoiceGroup();            	
                break;                
            default:
                break;
            }
        }

        @Override
        public void onLongClick(int itemId, View view) {
            switch (itemId) {
            case ITEM_TAKE_PICTURE:
                //selectPicFromCamera();
                break;
            case ITEM_PICTURE:
                //selectPicFromLocal();
                break;
            case ITEM_LOCATION:
                //startActivityForResult(new Intent(context, BaiduMapActivity.class), REQUEST_CODE_MAP);
                break;
            case ITEM_VIDEO:
    			//Intent intent1 = new Intent(context, ImageGridActivity.class);
    			//startActivityForResult(intent1, REQUEST_CODE_SELECT_VIDEO);
                break;
            case ITEM_FILE:
    			/*PathUtil.chooseFile = "";
    			Intent intent = new Intent(context, FileManager.class);
    			intent.putExtra("selectType",1);			
    			startActivityForResult(intent, REQUEST_CODE_SELECT_FILE); */            	
                break;
            case ITEM_OFFLINEFILE:
            	//selectFileFromLocal();
            	break; 
            case ITEM_CALLVIDEO:
        		if (chatMode == CHATMODE_SINGLE) // 单聊            	
        			startVideoUser();       			
            	else    	
                	startVideoGroup();         	    
                break;
            case ITEM_CALLVOICE:           	
        		if (chatMode == CHATMODE_SINGLE) // 单聊            	
        			startVoiceUser();       			
            	else    	
                	startVoiceGroup();            	
                break;                 
            default:
                break;
            }
        }         
    }
    //　文字、小表情   
    protected void sendTextMessage(String content) {
  
		if (content.length() > 0) {			
			EMMessage message = EMMessage.createSendMessage(myPlayId,EMMessage.MsgType.MSG_TEXT);
			TextMessageBody txtBody = new TextMessageBody(content);
			message.addBody(txtBody);
			sendMessage(message);
			saveToRecent(content);			
		}   	
    }
    //  大表情、斗图      
    protected void sendBigExpressionMessage(EMEmojicon emojicon){
   
 		EMMessage message = EMMessage.createSendMessage(myPlayId,EMMessage.MsgType.MSG_EMOTION);
 		BigExpressMessageBody txtBody = new BigExpressMessageBody(emojicon);
 		message.addBody(txtBody);
 		sendMessage(message);
 		saveToRecent(emojicon.getEmojiText());  		
     }
    // 语音       
    protected void sendVoiceMessage(String filePath, int length) {  	
		if (!(new File(filePath).exists())) {
			return;
		}  
		final EMMessage message = EMMessage.createSendMessage(myPlayId,EMMessage.MsgType.MSG_VOICE);		
		VoiceMessageBody body = new VoiceMessageBody(new File(filePath), length);		
		message.addBody(body);	
		sendMessage(message);	
		saveToRecent("[语音]");			
    }
    // 发送图片
    protected void sendImageMessage(String imagePath) {
 
		EMMessage message = EMMessage.createSendMessage(myPlayId,EMMessage.MsgType.MSG_IMAGE);	
		ImageMessageBody body = new ImageMessageBody(new File(imagePath),conversation);
		// 默认超过100k的图片会压缩后发给对方，可以设置成发送原图
		body.setSendOriginalImage(false);
		message.addBody(body); 
		sendMessage(message);	
		saveToRecent("[图片]");	
    }
    //发送位置
    protected void sendLocationMessage(double latitude, double longitude, String locationAddress) {
 
		EMMessage message = EMMessage.createSendMessage(myPlayId,EMMessage.MsgType.MSG_LOCATION);
		LocationMessageBody locBody = new LocationMessageBody(locationAddress, latitude, longitude);
		message.addBody(locBody);
		sendMessage(message);
		saveToRecent("[位置]"+locationAddress);		
    }
    //发送小视频
    protected void sendVideoMessage(String videoPath, String thumbPath, int videoLength) {
 
		final File videoFile = new File(videoPath);
		if (!videoFile.exists()) {
			return;
		} 
		EMMessage message = EMMessage.createSendMessage(myPlayId,EMMessage.MsgType.MSG_VIDEO);		
		VideoMessageBody body = new VideoMessageBody(videoFile, thumbPath, videoLength, videoFile.length());
		message.addBody(body);
		sendMessage(message);	
		saveToRecent("[视频]");		
    }
    //小文件像图片一样发送
    protected void sendFileMessage(String filePath) {

		File file = new File(filePath);
		if (file == null || !file.exists()) {
		//	Toast.makeText(getApplicationContext(), "文件不存在", 0).show();
			return;
		}
		if (file.length() > 100 * 1024 * 1024) {
			Toast.makeText(getActivity(), "文件不能大于100M", 0).show();
			return;
		}		
		if (file.length() > 100 * 1024-64) {
			sendBigFileMessage( filePath);
			return;
		}   	
		EMMessage message = EMMessage.createSendMessage(myPlayId,EMMessage.MsgType.MSG_FILE);	
		NormalFileMessageBody body = new NormalFileMessageBody(new File(filePath),conversation.getUserTimeStamp());
		message.addBody(body);
		sendMessage(message);
		String fileName = body.getFileName();		
		saveToRecent("[文件]"+fileName);
		Toast.makeText(getActivity(), "小文件像图片一样直接发送", 0).show();		
    }
    //大文件需要对方同意
    protected void sendBigFileMessage(String filePath) {

		File file = new File(filePath);
		if (file == null || !file.exists()) {
		//	Toast.makeText(getApplicationContext(), "文件不存在", 0).show();
			return;
		}
		if (file.length() > 100 * 1024 * 1024) {
		//	Toast.makeText(getApplicationContext(), "文件不能大于100M", 0).show();
			return;
		}   	
		EMMessage message = EMMessage.createSendMessage(myPlayId,EMMessage.MsgType.MSG_BIGFILE);	
		NormalFileMessageBody body = new NormalFileMessageBody(new File(filePath),conversation.getUserTimeStamp());
		message.addBody(body);
		sendMessage(message);
		String fileName = body.getFileName();		
		saveToRecent("[文件]"+fileName);			
    }
    //语音呼叫、视频呼叫等等
    protected void sendCallMessage( int type, int command ) {
  		EMMessage message = EMMessage.createSendMessage(myPlayId,EMMessage.MsgType.MSG_CALL );
  		CallMessageBody callBody = new CallMessageBody( type, command, toChatDestid );
		if(command==DefineMedia.EM_VIDEO_REQUESTCHAT)
	    	callBody.setTitle("[呼叫视频]");
		else if(command==DefineMedia.EM_AUDIO_REQUESTCHAT)
	    	callBody.setTitle("[呼叫语音]");    	
    	callBody.setState(command);   	
    	String str = MediaUtils.getSendMessage( type, command );	    	
    	callBody.setMessage(str);	
  		message.addBody(callBody);
  		sendMessage(message);
  		saveToRecent("[呼叫视频]");		
    }    
    //自定义消息入口
    protected void sendCustomMessage( int command, int targid ) {
    	//自定义消息处理模块：自己定义自己解释
    	CustomMessage msg = new CustomMessage( command,myPlayId,toChatDestid);  	
    	//用户定义各项数据
    	msg.DealwithCustom(chatType,toChatDestid);
    	//发送模块只需要得到buf
    	byte[] buf = msg.ToByteArray(); 
        int len = msg.getLength( );
  	    //拿到buf后，就可以像其他消息一样发送了
  		EMMessage message = EMMessage.createSendMessage(myPlayId,EMMessage.MsgType.MSG_CUSTOM );
  		CustomMessageBody customBody = new CustomMessageBody( buf, len );	
  		message.addBody(customBody);
  		sendMessage(message);
  		saveToRecent("[自定义]");		
    }    
    //上面的消息都要通过此入口开始发送  
    protected void sendMessage(EMMessage message){
        if (message == null) {
            return;
        }
		conversation.addSendMessage(message); 
        if(isMessageListInited) {
            messageList.refreshSelectLast();
        }
    
    }
    //重发消息         
    public void resendMessage1(EMMessage message){
        message.setStatus(EMMessage.Status.CREATE);
        messageList.refresh();
    }
	//将发送消息显示在最新消息窗口 
	public void saveToRecent(String message){
   		RecentItem thisItem = null;
		for (RecentItem entity : GloableParams.RecentList) {
			if(entity.userId == toChatDestid && entity.type == chatType)
				thisItem = entity;
		}
		if(thisItem != null )
		{ 
	  		
		}
		if(thisItem == null )
		{
	  		thisItem = new RecentItem();
			thisItem.setUserId(toChatDestid);
			thisItem.setChatType(chatType);			
			thisItem.setName(toChatUsername);
	  		
			GloableParams.RecentList.add(thisItem); 	  		
		}
		thisItem.setName(toChatUsername);		
		int len = message.length();
		if(len>30) len=30;
		message = message.substring(0,len);	
		int nowtime = (int) (new Date().getTime()/1000);
		thisItem.setMessage(message); 
		thisItem.setTime(nowtime);			

	       Intent intent = new Intent(MyApp.getInstance().getNewMessageBroadcastAction());  

			intent.putExtra("Chat_ID",toChatDestid);				
			intent.putExtra("Chat_Type",chatType);		        
	        MyApp.getInstance().sendBroadcast(intent); 		
	}   
    //===================================================================================
    /**
     * send image
     * 
     * @param selectedImage
     */
    protected void sendPicByUri(Uri selectedImage) {
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            cursor = null;

            if (picturePath == null || picturePath.equals("null")) {
                Toast toast = Toast.makeText(getActivity(), R.string.cant_find_pictures, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return;
            }
            sendImageMessage(picturePath);
        } else {
            File file = new File(selectedImage.getPath());
            if (!file.exists()) {
                Toast toast = Toast.makeText(getActivity(), R.string.cant_find_pictures, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return;

            }
            sendImageMessage(file.getAbsolutePath());
        }

    }
    
    /**
     * send file
     * @param uri
     */
    protected void sendFileByUri(Uri uri){
        String filePath = null;
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = null;

            try {
                cursor = getActivity().getContentResolver().query(uri, filePathColumn, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    filePath = cursor.getString(column_index);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            filePath = uri.getPath();
        }
        File file = new File(filePath);
        if (file == null || !file.exists()) {
            Toast.makeText(getActivity(), R.string.File_does_not_exist, 0).show();
            return;
        }
        //limit the size < 100M
        if (file.length() > 100 * 1024 * 1024) {
            Toast.makeText(getActivity(), R.string.The_file_is_not_greater_than_10_m, 0).show();
            return;
        }
        if (file.length() < 100 * 1024) {
        	sendFileMessage(filePath);
            Toast.makeText(getActivity(), "小文件像图片一样直接发送", 0).show();
            return;
        }        
        sendBigFileMessage(filePath);      
    }

    /**
     * capture new image
     */
    protected void selectPicFromCamera() {
        if (!CommonUtils.isExitsSdcard()) {
            Toast.makeText(getActivity(), R.string.sd_card_does_not_exist, 0).show();
            return;
        }
        //android 6.0及以上申请相机权限  
        String[] Permissions = {
        	  Manifest.permission.CAMERA,
              Manifest.permission.READ_PHONE_STATE
              };        
        PermissionChecker Checker = new PermissionChecker(getActivity());        
        Checker.checkPermissions(getActivity(),Permissions,new PermissionChecker.PermissionCheckCallback() { 
			@Override
			public void onRequest() {
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					//e.printStackTrace();
				}
			}

			@Override
			public void onGranted() {
					
			}

			@Override
			public void onGrantSuccess() {			
	
			}
			@Override
			public void onGrantFail() {
	            return;
			}

		});        
		cameraFile = new File(PathUtil.getInstance().getImagePath(), conversation.getUserTimeStamp() + ".jpg");	
	    if(cameraFile == null && !cameraFile.exists()){//如果文件存在就不在创建
    	    cameraFile.getParentFile().mkdirs();
        }
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 		
        //獲取系統版本  
        int currentapiVersion = android.os.Build.VERSION.SDK_INT; 
        if (currentapiVersion < 24) {  
            // 从文件中创建uri  
            Uri uri = Uri.fromFile(cameraFile);   
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);  
        } else {  
            //兼容android7.0 使用共享文件的形式  
            ContentValues contentValues = new ContentValues(1);  
            contentValues.put(MediaStore.Images.Media.DATA, cameraFile.getAbsolutePath());  
            Uri uri = MyApp.getInstance().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);  
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); 
        }  
        startActivityForResult(intent, REQUEST_CODE_CAMERA);      
    }

    /**
     * select local image
     */
    protected void selectPicFromLocal() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");

        } else {
            intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, REQUEST_CODE_LOCAL);
    }

    /**
     * select file
     */
    protected void selectFileFromLocal() {
        Intent intent = null;
        if (Build.VERSION.SDK_INT < 19) { //api 19 and later, we can't use this way, demo just select from images
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);

        } else {
			intent = new Intent(Intent.ACTION_GET_CONTENT);
			intent.setType("*/*");// 无类型限制
			intent.addCategory(Intent.CATEGORY_OPENABLE);             
        }
        startActivityForResult(intent, REQUEST_CODE_SELECT_OFFLINEFILE);
    }
    
 
    protected void startVideoGroup() {   
        //android 6.0及以上申请相机权限   
        String[] Permissions = {
        		Manifest.permission.CAMERA,
              Manifest.permission.READ_PHONE_STATE
              };        
        PermissionChecker Checker = new PermissionChecker(getActivity());        
        Checker.checkPermissions(getActivity(),Permissions,new PermissionChecker.PermissionCheckCallback() { 
			@Override
			public void onRequest() {
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					//e.printStackTrace();
				}
			}

			@Override
			public void onGranted() {
					
			}

			@Override
			public void onGrantSuccess() {			
	
			}
			@Override
			public void onGrantFail() {
	            return;
			}

		});   	
        String[] strarr = new String[]{"视频群聊","视频会议","视频教学"}; 
        MenuDialog.Builder builder = new MenuDialog.Builder(getActivity());             
		builder.setItems(strarr, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if (which == 1) { // 视频会议
					// 打开群组视频页面
					Intent Groupvideo = new Intent(getActivity(),
							MeetingVideoActivity.class);
					Groupvideo.putExtra("Chat_ID", toChatDestid);
					Groupvideo.putExtra("Chat_Type", chatType);
					Groupvideo.putExtra("Chat_Name", toChatUsername);
					startActivity(Groupvideo);				
				}else if (which == 2) { // 视频教学
					// 非阻塞呼叫
					//sendCallMessage(DefineChat.CommType_PCUSERMEDIA,
					//		DefineMedia.EM_VIDEO_REQUESTCHAT);
				} else {// 视频群聊
					// 打开群组视频页面
					Intent Groupvideo = new Intent(getActivity(),
							GroupVideoActivity.class);
					Groupvideo.putExtra("Chat_ID", toChatDestid);
					Groupvideo.putExtra("Chat_Type", chatType);
					Groupvideo.putExtra("Chat_Name", toChatUsername);
					startActivity(Groupvideo);
				}

			}
        }).show();
    }    
 
    protected void startVideoUser() {  
        //android 6.0及以上申请相机权限    
        String[] Permissions = {
        		Manifest.permission.CAMERA,
              Manifest.permission.READ_PHONE_STATE
              };        
        PermissionChecker Checker = new PermissionChecker(getActivity());        
        Checker.checkPermissions(getActivity(),Permissions,new PermissionChecker.PermissionCheckCallback() { 
			@Override
			public void onRequest() {
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					//e.printStackTrace();
				}
			}

			@Override
			public void onGranted() {
					
			}

			@Override
			public void onGrantSuccess() {			
	
			}
			@Override
			public void onGrantFail() {
	            return;
			}

		});
        String[] strarr = new String[]{"视频直拨","视频呼叫","视频电话"}; 
        MenuDialog.Builder builder = new MenuDialog.Builder(getActivity());             
		builder.setItems(strarr, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if (which == 1) { // 视频呼叫
					// 非阻塞呼叫
					sendCallMessage(DefineChat.CommType_PCUSERMEDIA,
							DefineMedia.EM_VIDEO_REQUESTCHAT);
				} else if (which == 0) {// 视频直拨
		        	//阻塞呼叫       	
					startActivity(new Intent(getActivity(), VideoTeleActivity.class)
					    .putExtra("userid", toChatDestid).putExtra("username", toChatUsername)
						.putExtra("isComingCall", false));
		            // videoCallBtn.setEnabled(false);
		            inputMenu.hideExtendMenuContainer();					
				} else {// 视频电话
		        	//阻塞呼叫       	
					startActivity(new Intent(getActivity(), VideoCallActivity.class)
					    .putExtra("userid", toChatDestid).putExtra("username", toChatUsername)
						.putExtra("isComingCall", false));
		            // videoCallBtn.setEnabled(false);
		            inputMenu.hideExtendMenuContainer();
				}
			}
        }).show();       

    }    
 
    protected void startVoiceGroup() {     	
        String[] strarr = new String[]{"语音群聊","语音会议"}; 
        MenuDialog.Builder builder = new MenuDialog.Builder(getActivity());             
		builder.setItems(strarr, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if (which == 1) { // 语音会议
					Intent Groupaudio = new Intent(getActivity(),
							MeetingAudioActivity.class);
					Groupaudio.putExtra("Chat_ID", toChatDestid);
					Groupaudio.putExtra("Chat_Type", chatType);
					Groupaudio.putExtra("Chat_Name", toChatUsername);
					startActivity(Groupaudio);					
				} else {// 语音群聊
					// 打开群组语音页面
					Intent Groupaudio = new Intent(getActivity(),
							GroupAudioActivity.class);
					Groupaudio.putExtra("Chat_ID", toChatDestid);
					Groupaudio.putExtra("Chat_Type", chatType);
					Groupaudio.putExtra("Chat_Name", toChatUsername);
					startActivity(Groupaudio);					
				}

			}
        }).show();
    }    

    protected void startVoiceUser() { 
        String[] strarr = new String[]{"语音直播","语音呼叫","语音电话"}; 
        MenuDialog.Builder builder = new MenuDialog.Builder(getActivity());             
		builder.setItems(strarr, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if (which == 1) { // 语音呼叫
					// 非阻塞呼叫
					sendCallMessage(DefineChat.CommType_PCUSERMEDIA,
							DefineMedia.EM_AUDIO_REQUESTCHAT);	
				} else if (which == 0){// 语音直拨(双方直接连接)
		        	//阻塞呼叫       	
					startActivity(new Intent(getActivity(), VoiceTeleActivity.class)
					    .putExtra("userid", toChatDestid).putExtra("username", toChatUsername)
						.putExtra("isComingCall", false));
		            // videoCallBtn.setEnabled(false);
		            inputMenu.hideExtendMenuContainer();					
				} else {// 语音电话(由服务器转接)
		        	//阻塞呼叫       	
					startActivity(new Intent(getActivity(), VoiceCallActivity.class)
					    .putExtra("userid", toChatDestid).putExtra("username", toChatUsername)
						.putExtra("isComingCall", false));
		            inputMenu.hideExtendMenuContainer();
				}

			}
        }).show();    	
 
    }    
  
    /**
     * forward message
     * 
     * @param forward_msg_id
     */
    protected void forwardMessage(String forward_msg_id) {
 
    }
   
    protected void onMyUserAvatarClick(EMMessage message) {
		if (message.getChatType() >= 5) {
			Intent intent = new Intent(getActivity(), MemberInfoActivity.class);
			intent.putExtra("Info_UserId", message.getSendId());
			intent.putExtra("Info_NickName", message.getFrom());
			intent.putExtra("TypeID", message.getRecvId());
			intent.putExtra("Info_GroupType", message.getChatType());
			Utils.start_Activity(getActivity(),intent);			
		}else if (toChatDestid > 10000) {
			Intent intent = new Intent(getActivity(), FriendInfoActivity.class);
			intent.putExtra("Info_UserId", message.getSendId());
			intent.putExtra("Info_NickName", message.getFrom());
			intent.putExtra("Info_Image", message.getImageId());	
			Utils.start_Activity(getActivity(),intent);	
		} else {
			Intent intent = new Intent(getActivity(), NearbyInfoActivity.class);
			intent.putExtra("Info_UserId", message.getSendId());			
			intent.putExtra("Info_Position", 0); 
			intent.putExtra("Info_NickName", message.getFrom());
			intent.putExtra("Info_Image", message.getImageId());			
			Utils.start_Activity(getActivity(),intent);			
		}  	

      }
      
      protected void onMyUserAvatarLongClick(EMMessage message) {
  		new MyAlertDialog(getActivity(),"移入到黑名单？",
  				"你确定要将该成员移入到黑名单吗？\n（此处没实现。可以到群组列表中去删除。）",
  				new MyAlertDialog.OnSetListener() {
  					@Override
  					public void onSelect(int comm) {
  					//	UserInfo uinfo = new UserInfo(nUserId,nTypeId,strNickName,image,iPower,iIndex);
  					//	deleteMember(uinfo);							
  					}
  				}).show();			

      }  
      
      protected void onMyResendClick(EMMessage message) {
      	 
      } 
      
      protected void onMyBubbleLongClick(EMMessage message) {
          contextMenuMessage = message;
	
  		int mode = 0;
  		if (message.direct == EMMessage.Direct.SEND)
  			mode = 2;
 
  		Intent intent = new Intent(getActivity(), ContextMenu.class);	
  		intent.putExtra("position", 5);
  		intent.putExtra("type",EMMessage.MsgType.MSG_TEXT);
  		intent.putExtra("mode", mode);	
		int sendtime = (int)message.getMsgTime();	
		intent.putExtra("sendtime", sendtime);
  		int requestCode = REQUEST_CODE_CONTEXT_MENU;	
  		startActivityForResult(intent, requestCode);          
      }  
      
      protected void onMyBubbleClick(EMMessage message) {   	
          switch (message.getMsgType()) {
          case EMMessage.MsgType.MSG_TEXT:
     
              break;
          case EMMessage.MsgType.MSG_LOCATION:

              break;
          case EMMessage.MsgType.MSG_FILE:
          	  onFileViewClick(message); 
              break;
  		  case EMMessage.MsgType.MSG_BIGFILE:
			  onFileViewClick(message);
			  break;            
          case EMMessage.MsgType.MSG_IMAGE:
          	  onImageViewClick(message);
              break;
          case EMMessage.MsgType.MSG_VOICE:

              break;
          case EMMessage.MsgType.MSG_VIDEO:
          	  onPlayViewClick(message);
              break;
          case EMMessage.MsgType.MSG_CALL:
        	  onMediaViewClick(message);
              break;           
          case EMMessage.MsgType.MSG_EMOTION:
   
              break;            
          default:
              break;
          } 
      } 
      
	protected void onImageViewClick(EMMessage message) {
		ImageMessageBody imgBody = (ImageMessageBody) message.getBody();

		Intent intent = new Intent(getActivity(), ShowBigImageActivity.class);
		File file = new File(imgBody.getLocalUrl());
		if (file.exists()) {
			Uri uri = Uri.fromFile(file);
			intent.putExtra("uri", uri);
		} else {

			intent.putExtra("remotepath", imgBody.getRemoteUrl());
			intent.putExtra("localUrl", imgBody.getLocalUrl());
			intent.putExtra("message", message.getMsgId());
			intent.putExtra("sendid", message.getDestId());
			intent.putExtra("chattype", message.getChatType());
		}
		Uri uri1 = Uri.fromFile(new File(imgBody.getThumbnailUrl()));
		intent.putExtra("uri1", uri1);
		if (message != null && message.direct == EMMessage.Direct.RECEIVE
				&& !message.isAcked
				&& message.getChatMode() != GloableParams.CHATMODE_GROUP) {
			try {
				EMSendManager.ackMessageRead(message);
				message.isAcked = true;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		getActivity().startActivity(intent);
	}

	protected void onPlayViewClick(EMMessage message) {
		PathUtil.curPlayId = myPlayId;		
		VideoMessageBody videoBody = (VideoMessageBody) message.getBody();
		Intent intent = new Intent(getActivity(), ShowVideoActivity.class);
		File file = new File(videoBody.getLocalUrl());
		if (file.exists()) {
			Uri uri = Uri.fromFile(file);
			intent.putExtra("uri", uri);
		} else {
			intent.putExtra("secret", videoBody.getSecret());
			intent.putExtra("remotepath", videoBody.getRemoteUrl());
			intent.putExtra("localpath", videoBody.getLocalUrl());
		}
		intent.putExtra("sendid", message.getDestId());
		intent.putExtra("chattype", message.getChatType());
		intent.putExtra("message", message.getMsgId());
		if (message != null && message.direct == EMMessage.Direct.RECEIVE
				&& !message.isAcked
				&& message.getChatMode() != GloableParams.CHATMODE_GROUP) {
			try {
				EMSendManager.ackMessageRead(message);
				message.isAcked = true;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		getActivity().startActivity(intent);
	}

	protected void onFileViewClick(EMMessage message) {
		NormalFileMessageBody fileBody = (NormalFileMessageBody) message
				.getBody();
		String filePath = fileBody.getLocalUrl();
		File file = new File(filePath);
		if (file != null && file.exists()) {
			// open files if it exist
			FileUtils.openFile(file, (Activity) getActivity());
		} else if(message.getMsgType()!=EMMessage.MsgType.MSG_BIGFILE){
			Intent intent = new Intent(getActivity(), ShowNormalFileActivity.class);
			intent.putExtra("sendid", message.getSendId());
			intent.putExtra("recvid", message.getRecvId());	
			intent.putExtra("chattype", message.getChatType());
			intent.putExtra("message", message.getMsgId());
			getActivity().startActivity(intent);
		} else if(message.direct == EMMessage.Direct.RECEIVE){
			Intent intent = new Intent(getActivity(), DownloadFileActivity.class);
			intent.putExtra("sendid", message.getSendId());
			intent.putExtra("recvid", message.getRecvId());	
			intent.putExtra("chattype", message.getChatType());
			intent.putExtra("message", message.getMsgId());
			getActivity().startActivity(intent);
		} else {
			Intent intent = new Intent(getActivity(), UploadFileActivity.class);
			intent.putExtra("sendid", message.getSendId());
			intent.putExtra("recvid", message.getRecvId());	
			intent.putExtra("chattype", message.getChatType());
			intent.putExtra("message", message.getMsgId());
			getActivity().startActivity(intent);			
		}

		if (message.direct == EMMessage.Direct.RECEIVE && !message.isAcked) {
			try {
				EMSendManager.getInstance().ackMessageRead(message);
				message.isAcked = true;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	protected void onMediaViewClick(EMMessage message) {
		CallMessageBody callBody = (CallMessageBody) message.getBody();
    	int type = callBody.getType();	
    	int command = callBody.getCommand();
    	int state = callBody.getState();  
		if(type==DefineChat.CommType_PCUSERMEDIA &&command==DefineMedia.EM_VIDEO_REQUESTCHAT){	
			Intent intent = new Intent(getActivity(), VideoPhoneActivity.class);
			intent.putExtra("sendid", message.getSendId());
			intent.putExtra("recvid", message.getRecvId());	
			intent.putExtra("destid", toChatDestid);
			intent.putExtra("message", message.getMsgId());
			getActivity().startActivity(intent);			
		}else if(type==DefineChat.CommType_PCUSERMEDIA&&command==DefineMedia.EM_AUDIO_REQUESTCHAT){	
			Intent intent = new Intent(getActivity(), VoicePhoneActivity.class);
			intent.putExtra("sendid", message.getSendId());
			intent.putExtra("recvid", message.getRecvId());	
			intent.putExtra("destid", toChatDestid);
			intent.putExtra("message", message.getMsgId());
			getActivity().startActivity(intent);			
		}		
	}	
}
