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.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.lianxin.pubqq.activity.FriendInfoActivity;
import com.lianxin.pubqq.activity.FriendTypeInfoActivity;
import com.lianxin.pubqq.activity.InviteListActivity;
import com.lianxin.pubqq.activity.MemberAdminListActivity;
import com.lianxin.pubqq.activity.MemberListActivity;
import com.lianxin.pubqq.chat.IMChatActivity;
//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.pubqq.activity.UserSearchActivity;
import com.lianxin.panqq.list.ExFriendListView;
import com.lianxin.panqq.main.bean.ListUtil;
import com.lianxin.pubqq.main.adpter.FriendAdpter;
import com.lianxin.panqq.list.bean.FriendType;
import com.lianxin.panqq.list.bean.Friend;
import com.lianxin.panqq.list.utils.FriendUtils;
import com.lianxin.panqq.common.GloableParams;
import com.lianxin.panqq.common.utils.CaptionUtils;

public class Fragment_Friend extends Fragment implements OnClickListener {
	// 好友（服务器注册好友）
	private Activity ctx;
	private View layout, layout_head; 
    private ExFriendListView FriendView;    
	private FriendAdpter friendAdpter;     
      
    private ScrollView qqScroll=null;    
    private float curTouchPosx;
    private float curTouchPosy;    
    private List<FriendType> FriendTypes = GloableParams.FriendTypes;  
    private List<Friend> Friends = GloableParams.Friends; 
	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_friend,
					null);
			
			initData();	//先要初始化数据，否则下一步出错		
			initViews();
			initCaption();		
			setOnListener();
		} else {
			ViewGroup parent = (ViewGroup) layout.getParent();
			if (parent != null) {
				parent.removeView(layout);
			}
		}				
		return layout;
	}

	public void refresh1() {
    
		friendAdpter.notifyDataSetChanged();
    
	}	

	public void refreshNewUser() {
		
	    FriendTypes = GloableParams.FriendTypes;  
	    Friends = GloableParams.Friends; 
	    friendAdpter.setData(FriendTypes, Friends);	    
		friendAdpter.notifyDataSetChanged();	    
	}	

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

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

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

	protected void initCaption() {
		//加载服务器定制标题字符串
		//loadCustomCaption();
	    String sCaption = CaptionUtils.LoadCaption( "IDS_FRIEND_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 
		FriendView.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一样
		FriendView.setOnGroupClickListener(new OnGroupClickListener() {
            int ret = 0; 			
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {

                if(curTouchPosx<100)
                     return false;
        		float pxValue = curTouchPosx;		
        		int curDipx = DensityUtils.pxToDip(getActivity(), pxValue);	
                if(curDipx<100)
                    return false;        		
            	int nTypeId = GloableParams.FriendTypes.get(groupPosition).typeId; 
            	String nTypeName = GloableParams.FriendTypes.get(groupPosition).typename;             	
    			Intent intent = new Intent(getActivity(), FriendTypeInfoActivity.class);
    			intent.putExtra("TypeID", nTypeId);		
    			intent.putExtra("TypeName", nTypeName);
    			intent.putExtra("Info_Image",1);			
    			intent.putExtra("Info_Number", 10);
 			
    			//getActivity().startActivity(intent);  
    			Utils.start_Activity(getActivity(),intent); 		           			
   
    			return true;                
            }
        });	
		FriendView.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 onMyChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {

    	Friend child =	FriendUtils.getChild(groupPosition,  childPosition);	
		float pxValue = curTouchPosx;		
		int curDipx = DensityUtils.pxToDip(getActivity(), pxValue);		
        if(curDipx<200)
        {
        	
			Intent intent = new Intent(getActivity(), FriendInfoActivity.class);
	
			intent.putExtra("Info_UserId", child.userId);
			intent.putExtra("Info_NickName", child.getName());
			intent.putExtra("Info_Image", child.imageid);			 
			Utils.start_Activity(getActivity(),intent);			
  
		} else {			
			Intent intent = new Intent(getActivity(), IMChatActivity.class);
			intent.putExtra("Chat_ID", child.getUserId());
			intent.putExtra("Chat_Type", DefineChat.ChatType_USER);		
			intent.putExtra("Chat_Name", child.getName());
			//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);

			MenuDialog.Builder builder = new MenuDialog.Builder(getActivity());
			builder.setItems(new String[] { "刷新成员", "刷新分类", "修改组名" , "添加分类" , "删除分类"},
					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);

			MenuDialog.Builder builder = new MenuDialog.Builder(getActivity());
			builder.setItems(new String[] { "查看资料", "修改备注", "移至分组", "保密设置" , "接待设置"},
					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(), UserSearchActivity.class);
			intent.putExtra("REQUEST_FROM", 0);

			startActivityForResult(intent, 20);
		} else if (id == R.id.layout_addfriend) {
			intent.setClass(getActivity(), MemberListActivity.class);
			intent.putExtra("TypeID", 1);
			intent.putExtra("TypeType", DefineUser.TYPE_DESTFRIEND);
			//getActivity().startActivity(intent);
			Utils.start_Activity(getActivity(), intent);
		} else if (id == R.id.layout_group) {// 群聊
			intent.setClass(getActivity(), MemberAdminListActivity.class);
			intent.putExtra("TypeID", 1);
			intent.putExtra("TypeType", DefineUser.TYPE_MYFRIEND);
			//getActivity().startActivity(intent);
			Utils.start_Activity(getActivity(), intent);
		} else if (id == R.id.layout_public) {// 公众号

			intent.setClass(getActivity(), InviteListActivity.class);
			//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();
			FriendView.refreshData();
			friendAdpter.setData(FriendTypes, Friends);
			friendAdpter.notifyDataSetChanged();
		}

	}
	

}


