package com.lianxin.pubqq.main;

import java.util.List;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
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.widget.ExpandableListView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.AdapterView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.lianxin.pubqq.activity.GroupSearchActivity;
import com.lianxin.pubqq.activity.InviteListActivity;
import com.lianxin.pubqq.activity.MemberInfoActivity;
import com.lianxin.pubqq.activity.MytypeInfoActivity;
import com.lianxin.pubqq.activity.NewGroupActivity;
import com.lianxin.pubqq.chat.EMChatActivity;
//import com.lianxin.panqq.chat.entity.EMMessage;
import com.lianxin.panqq.picker.MenuDialog;
import com.lianxin.panqq.common.DefineChat;
import com.lianxin.panqq.common.DefineUser;
import com.lianxin.panqq.common.Utils;
import com.lianxin.panqq.utils.DensityUtils;
import com.lianxin.panqq.client.callback.listCallBack;
import com.lianxin.pubqq.R;
import com.lianxin.panqq.list.ExCrowdListView;
import com.lianxin.panqq.main.bean.ListUtil;
import com.lianxin.pubqq.main.adpter.GroupAdpter;
import com.lianxin.panqq.list.bean.EMGroup;
import com.lianxin.panqq.list.bean.Member;
import com.lianxin.panqq.common.GloableParams;
import com.lianxin.panqq.common.utils.CaptionUtils;
import com.lianxin.pubqq.extend.CrowdActivity;

public class Fragment_Crowd extends Fragment implements OnClickListener {
	// 用户自建群
	private Activity ctx;
	private View layout, layout_head;	
    private ExCrowdListView CrowdView; 
	private GroupAdpter crowdAdpter; 
  
    private ScrollView qqScroll=null;    
    private float curTouchPosx;
    private float curTouchPosy;      
    private List<EMGroup> MyCrowds = GloableParams.MyCrowds; 
	private String  strCaption = "群,搜索群,新建群,关键字,群申请,群通知,我加入的群,刷新我加入的群"; //服务器各自定制的标题字符串
	private String[]  arrCaption = null; //标题字符串数组  
	private String  strTip = "刷新我加入的群"; 	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (layout == null) {
			ctx = this.getActivity();
			layout = ctx.getLayoutInflater().inflate(R.layout.fragment_crowd,
					null);
			
			initData();	//先要初始化数据，否则下一步出错		
			initViews();
			initCaption();
			setOnListener();
		} else {
			ViewGroup parent = (ViewGroup) layout.getParent();
			if (parent != null) {
				parent.removeView(layout);
			}
		}				
		return layout;
	}

	public void refresh() {	    
		crowdAdpter.notifyDataSetChanged();	    
	}	

	public void refreshNewUser() {		
		MyCrowds = GloableParams.MyCrowds;  
		crowdAdpter.setData(MyCrowds);	    
		crowdAdpter.notifyDataSetChanged();	    
	}	

	private void initData() {
		CrowdView = (ExCrowdListView)layout.findViewById(R.id.exlistcrowd); //实例化expandableLIstView			
		CrowdView.setStatusListener(new listCallBack(){
			@Override
			public void onSuccess(int statusCode, byte[] recvBuf) {
				MyCrowds = GloableParams.MyCrowds;					
			}
			@Override
			public void onFailure(int errorCode, String errorMessage) {
				// TODO Auto-generated method stub			
			}
		});	
		CrowdView.initData();	
		crowdAdpter = new GroupAdpter(getActivity(), MyCrowds, DefineUser.TYPE_CROWD);
		CrowdView.setAdapter(crowdAdpter); //给他设置adapter，这里getActivity（），如果在Activity中用就是this
		
		CrowdView.setGroupIndicator(getResources().getDrawable(R.drawable.expander_ic_folder));
		ListUtil.setListViewHeightBasedOnChildren(CrowdView);
		CrowdView.setDataAdapter(crowdAdpter);		
	}	
	
	private void initViews() {

		CrowdView.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				//获取点击事件相对控件左边的x轴坐标，即点击事件距离控件左边的距离
				curTouchPosx = event.getX();//获得触摸x坐标
				curTouchPosy = event.getY();//获得触摸y坐标				
				return false;
			}
		});
		CrowdView.setOnGroupExpandListener(new OnGroupExpandListener() {
			@Override
			public void onGroupExpand(int arg0) {
				ListUtil.setListViewHeightBasedOnChildren(CrowdView);
			}
		});			
		CrowdView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
			@Override
			public void onGroupCollapse(int arg0) {
				ListUtil.setListViewHeightBasedOnChildren(CrowdView);
			}
		});		

		qqScroll = (ScrollView) layout.findViewById(R.id.qq_scroll);
		qqScroll.smoothScrollTo(0, 0);	
	}

	protected void initCaption() {
		//加载服务器定制标题字符串
		//loadCustomCaption();
	    String sCaption = CaptionUtils.LoadCaption( "IDS_CROWD_WELCOME" );
	    if(!TextUtils.isEmpty(sCaption)&&sCaption.length() > 20)
	        arrCaption = CaptionUtils.SplitCaption( sCaption );	
	    else if(!TextUtils.isEmpty(strCaption)&&strCaption.length() > 20)
	        arrCaption = CaptionUtils.SplitCaption( strCaption );	    
		//如果服务器有自定义字符串    
		if( arrCaption != null && arrCaption.length > 7 ){
			//txt_title.setText(arrCaption[0]);
			((TextView)layout.findViewById(R.id.txt_search)).setText(arrCaption[1]);			
			((TextView)layout.findViewById(R.id.cap_addfriend)).setText(arrCaption[2]);
			((TextView)layout.findViewById(R.id.cap_group)).setText(arrCaption[3]);			
			((TextView)layout.findViewById(R.id.cap_public)).setText(arrCaption[4]);			
			((TextView)layout.findViewById(R.id.cap_table)).setText(arrCaption[6]);	
			strTip = arrCaption[7];			
		}
	}	
	
	private void setOnListener() {
		// TODO Auto-generated method stub

		layout.findViewById(R.id.layout_addfriend).setOnClickListener(this);
		layout.findViewById(R.id.layout_search).setOnClickListener(this);
		layout.findViewById(R.id.layout_group).setOnClickListener(this);
		layout.findViewById(R.id.layout_public).setOnClickListener(this);	
		layout.findViewById(R.id.layout_refresh).setOnClickListener(this);
		
		//长按条目，包括group和child 
		CrowdView.setOnItemLongClickListener(new OnItemLongClickListener() { 

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
	         //   longClickListIteam(arg1);
				return onMyItemLongClick( arg0, arg1, arg2, arg3 );				
				//return false;
			} 
	    }); 
		//设置group 和 child item onclick监听器，跟ExpandableListView一样
		CrowdView.setOnGroupClickListener(new OnGroupClickListener() {
            int ret = 0; 			
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                if(curTouchPosx<100)
                     return false;
            	onMyGroupClick( parent, v, groupPosition,  id);       
                return true;                 
            }
        });	
		CrowdView.setOnChildClickListener(new OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
            //    Toast.makeText(DifferentMenuActivity.this,
            //            "group " + groupPosition + " child " + childPosition + " clicked", Toast.LENGTH_SHORT).show();
            	return onMyChildClick( parent, v, groupPosition, childPosition, id);
            	//return false;
            }
        });		
	}

    public boolean onMyGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
 
    	EMGroup person = MyCrowds.get(groupPosition);
		int nChatId = person.getId();
		String nChatName = person.getName();			
	//	int nChatType = 5;   	
		int nChatType = DefineChat.ChatType_CROWD;
		float pxValue = curTouchPosx;		
		int curDipx = DensityUtils.pxToDip(getActivity(), pxValue);		
        if(curDipx<240)
        {
			Intent intent = new Intent(getActivity(), MytypeInfoActivity.class);
			intent.putExtra("TypeID", nChatId);
			//intent.putExtra("TypeType", nChatType);			
			//intent.putExtra("TypeName", nChatName);
			//intent.putExtra("Info_UserId", person.getId());
			intent.putExtra("Info_NickName", person.getName());
			intent.putExtra("Info_GroupType", DefineUser.TYPE_CROWD);
			//intent.putExtra("Info_Image",1);			
			//intent.putExtra("Info_Power", person.mypower);
			//intent.putExtra("Info_Index", person.index);			
			//getActivity().startActivity(intent);
			Utils.start_Activity(getActivity(),intent);			
		} else {
			Intent intent = new Intent(getActivity(), EMChatActivity.class);
			intent.putExtra("Chat_ID", nChatId);
			intent.putExtra("Chat_Type", nChatType);
			intent.putExtra("Chat_Name", nChatName);
			//getActivity().startActivity(intent);
			Utils.start_Activity(getActivity(),intent);			
		}       
        return false;
    }	

    public boolean onMyChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
		Member person = MyCrowds.get(groupPosition).members.get(childPosition);;
		int nChatId = person.getUserId();
		String nChatName = person.getName();			
		int nChatType = DefineChat.ChatType_USER;
		float pxValue = curTouchPosx;		
		int curDipx = DensityUtils.pxToDip(getActivity(), pxValue);		
        if(curDipx<200)
        {
    		int nTypeId = MyCrowds.get(groupPosition).getId();
    		String nTypeName = MyCrowds.get(groupPosition).getGroupName();        	
        	nChatType = DefineChat.ChatType_CROWD;       	
			Intent intent = new Intent(getActivity(), MemberInfoActivity.class);
			intent.putExtra("TypeID", nTypeId);
			//intent.putExtra("TypeType", nChatType);			
			//intent.putExtra("TypeName", nTypeName);	
			intent.putExtra("Info_GroupType", DefineUser.TYPE_CROWD);			
			intent.putExtra("Info_UserId", person.userId);
			intent.putExtra("Info_NickName", person.getName());
			//intent.putExtra("Info_Image", person.imageid);			
			//intent.putExtra("Info_Power", person.power);
			//intent.putExtra("Info_Index", person.index);			
			//getActivity().startActivity(intent);
			Utils.start_Activity(getActivity(),intent);			
		} else {
			Intent intent = new Intent(getActivity(), EMChatActivity.class);
			intent.putExtra("Chat_ID", nChatId);
			intent.putExtra("Chat_Type", nChatType);
			intent.putExtra("Chat_Name", nChatName);
			//getActivity().startActivity(intent);
			Utils.start_Activity(getActivity(),intent);			
		}
        return false;
    }	    
    
	public boolean onMyItemLongClick( AdapterView<?> parent, View childView, int flatPos, long id )
    {
        if (ExpandableListView.getPackedPositionType(id) == ExpandableListView.PACKED_POSITION_TYPE_GROUP)
        {
            long position = ((ExpandableListView) parent).getExpandableListPosition(flatPos);
            int groupPosition = ExpandableListView.getPackedPositionGroup(position);
            int childPosition = ExpandableListView.getPackedPositionChild(position);
       //     builder.setItems(new String[]{"个人资料","加为好友","移至分组","权限设置"}, new DialogInterface.OnClickListener() {             
            int power = 1;
            String[] strarr; 
            if( power>1 )
            	strarr = new String[]{"个人资料","加为好友","赠送礼物","给Ta评价","修改昵称","聘撤群委","删除群友"};
            else
            	strarr = new String[]{"刷新成员","保密设置","接待设置","退出该群"}; 
            MenuDialog.Builder builder = new MenuDialog.Builder(getActivity());             
            builder.setItems(strarr, new DialogInterface.OnClickListener() { 
            public void onClick(DialogInterface dialog, int which) { 
  
 	               Toast.makeText(ctx, "I am "+ which, Toast.LENGTH_SHORT).show();                        	  
                } 
            }).show(); 
            return true;
        }
        else if (ExpandableListView.getPackedPositionType(id) == ExpandableListView.PACKED_POSITION_TYPE_CHILD)
        {
            long position = ((ExpandableListView) parent).getExpandableListPosition(flatPos);
            int groupPosition = ExpandableListView.getPackedPositionGroup(position);
            int childPosition = ExpandableListView.getPackedPositionChild(position);
 
            int power = 2;
            String[] strarr; 
            if( power>1 )
            	strarr = new String[]{"个人资料","加为好友","赠送礼物","给Ta评价","修改昵称","聘撤群委","删除群友"};
            else
            	strarr = new String[]{"个人资料","加为好友","赠送礼物","给Ta评价"}; 
            MenuDialog.Builder builder = new MenuDialog.Builder(getActivity());          
            builder.setItems(strarr, new DialogInterface.OnClickListener() { 
            public void onClick(DialogInterface dialog, int which) { 
  
 	               Toast.makeText(ctx, "I am "+ which, Toast.LENGTH_SHORT).show();                        	  
                } 
            }).show(); 
            
            return true;
        }
        return false;
    }

	@Override
	public void onClick(View v) {
		Intent intent = new Intent();		
		int id = v.getId();
		if (id == R.id.layout_search) {// 搜索好友及公众号
			intent.setClass(getActivity(), GroupSearchActivity.class);
			intent.putExtra("REQUEST_FROM", 0);
			intent.putExtra("SEARCH_TYPE", DefineUser.TYPE_CROWD);
			//startActivity(intent);
			startActivityForResult(intent, 20);
		} else if (id == R.id.layout_addfriend) {
			intent.setClass(getActivity(), NewGroupActivity.class);
			intent.putExtra("Info_GroupType", DefineUser.TYPE_CROWD);
			//getActivity().startActivity(intent);
			Utils.start_Activity(getActivity(), intent);
		} else if (id == R.id.layout_group) {
			intent.setClass(getActivity(), CrowdActivity.class);
			//startActivity(intent);
			Utils.start_Activity(getActivity(), intent);
		} else if (id == R.id.layout_public) {
			intent.setClass(getActivity(), InviteListActivity.class);
			intent.putExtra("mSendId", 0);
			intent.putExtra("mChatType", DefineUser.TYPE_CROWD);
			//startActivity(intent);
			Utils.start_Activity(getActivity(), intent);
		} else if (id == R.id.layout_refresh) {//Toast.makeText(ctx, "刷新我参加的群", Toast.LENGTH_SHORT).show();
			Toast.makeText(ctx, strTip, Toast.LENGTH_SHORT).show();
			CrowdView.refreshData();
        	/*crowdAdpter.setData(MyCrowds);
        	crowdAdpter.notifyDataSetChanged(); */
		}
	}

}


