package com.lianxin.pubqq.extend;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
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.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lianxin.pubqq.activity.AddnewMemberActivity;
import com.lianxin.pubqq.chat.EMChatActivity;
import com.lianxin.panqq.edit.ModeTransGroupDialog;
import com.lianxin.panqq.edit.ModeTransUserDialog;
import com.lianxin.panqq.edit.MyAlertDialog;
//import com.lianxin.panqq.chat.entity.EMMessage;
import com.lianxin.panqq.client.EditClient;
import com.lianxin.panqq.client.MemberClient;
import com.lianxin.panqq.client.callback.askCallBack;
import com.lianxin.panqq.client.callback.updataCallBack;
import com.lianxin.panqq.list.bean.Member;
import com.lianxin.panqq.list.utils.FriendUtils;
import com.lianxin.panqq.main.EMGroupManager;
import com.lianxin.panqq.common.DefineChat;
import com.lianxin.panqq.common.DefineUser;
//import com.lianxin.panqq.common.Constants;
import com.lianxin.panqq.common.GloableParams;
import com.lianxin.pubqq.R;
import com.lianxin.panqq.widget.ExpandGridView;
import com.lianxin.panqq.common.Utils;
import com.lianxin.panqq.chat.BaseActivity;
import com.lianxin.panqq.common.bean.GroupInfo;
import com.lianxin.panqq.common.bean.UserInfo;
import com.lianxin.panqq.utils.ImagesUtils;

//群设置
public class GroupSettingActivity extends BaseActivity implements
		OnClickListener {
	private ImageView img_back;
	private TextView tv_groupname;
	private TextView txt_title;// 标题，成员总数
	int m_total = 0;// 成员总数
	private ExpandGridView gridview;// 成员列表
	// 修改群名称、置顶、、、、
	private RelativeLayout re_change_groupname;
	private RelativeLayout rl_switch_chattotop;
	private RelativeLayout rl_switch_block_groupmsg;
	private RelativeLayout re_clear;

	// 状态变化
	private CheckBox check_top, check_closetip;
	// 删除并退出

	private Button exitBtn;
	private Button deleteBtn;
	private Button setupBtn;	
	private String hxid;
	boolean is_admin = true;// 是否是管理员	
	private List<Member> members;	
	String longClickUsername = null;

	private int groupId;
	private int groupType;
	private String groupName;// 群名称	
//	private EMGroup group;
	private GridAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);	
		setContentView(R.layout.activity_groupsetting);	
		
		initControl();
		initView();
		initData();
		setListener();
	}

	//@Override
	protected void initControl() {
		txt_title = (TextView) findViewById(R.id.txt_title);
		txt_title.setText("聊天成员");
		img_back = (ImageView) findViewById(R.id.img_back);
		img_back.setVisibility(View.VISIBLE);
		tv_groupname = (TextView) findViewById(R.id.txt_groupname);
		gridview = (ExpandGridView) findViewById(R.id.gridview);

		re_change_groupname = (RelativeLayout) findViewById(R.id.re_change_groupname);
		rl_switch_chattotop = (RelativeLayout) findViewById(R.id.rl_switch_chattotop);
		rl_switch_block_groupmsg = (RelativeLayout) findViewById(R.id.rl_switch_block_groupmsg);
		re_clear = (RelativeLayout) findViewById(R.id.re_clear);
		check_top = (CheckBox)findViewById(R.id.check_top);
		check_closetip = (CheckBox)findViewById(R.id.check_closetip);
		
		exitBtn = (Button) findViewById(R.id.btn_exit_grp);
		deleteBtn = (Button) findViewById(R.id.btn_exitdel_grp);
		setupBtn = (Button) findViewById(R.id.btn_mode_trans);		
	}

	//@Override
	protected void initView() {
		//hxid = Utils.getValue(GroupSettingActivity.this, Constants.User_ID);
	}

	//@Override
	protected void initData() {
		// 获取传过来的groupid
		//groupId = getIntent().getStringExtra(Constants.GROUP_ID);
		groupId = getIntent().getIntExtra("Chat_ID",10002);
		groupType = getIntent().getIntExtra("Chat_Type", 1);
		groupName = getIntent().getStringExtra("Chat_Name");		
		// 获取本地该群数据
	//	group = EMGroupManager.getInstance().getGroup(groupId,groupType);
	//	members = group.getMembers();
		members = EMGroupManager.getInstance().getGroupMembers(groupId,groupType);		
		
		// 获取群成员信息
		tv_groupname.setText(groupName);

		// 显示群组成员头像和昵称
		if (members != null)
		showMembers(members);

		// 保证每次进详情看到的都是最新的group
		//updateGroup();		
	}

	// 显示群成员头像昵称的gridview
	private void showMembers(List<Member> members) {
		adapter = new GridAdapter(this, members);
		gridview.setAdapter(adapter);

		// 设置OnTouchListener,为了让群主方便地推出删除模》
		gridview.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					if (adapter.isInDeleteMode) {
						adapter.isInDeleteMode = false;
						adapter.notifyDataSetChanged();
						return true;
					}
					break;
				default:
					break;
				}
				return false;
			}
		});
	}

	//@Override
	protected void setListener() {
		re_change_groupname.setOnClickListener(this);
		check_top.setOnClickListener(this);
		check_closetip.setOnClickListener(this);
		re_clear.setOnClickListener(this);
		exitBtn.setOnClickListener(this);
		setupBtn.setOnClickListener(this);		
		deleteBtn.setOnClickListener(this);		
		img_back.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.img_back) {
			Utils.finish(GroupSettingActivity.this);
		} else if (id == R.id.btn_exit_grp) {// deleteMembersFromGroup(hxid);
			exitFromGroup();
		} else if (id == R.id.check_top) {
			boolean checked1 = ((CheckBox) v).isChecked();
		} else if (id == R.id.check_closetip) {
			boolean checked2 = ((CheckBox) v).isChecked();
		} else if (id == R.id.btn_mode_trans) {
			int mode = DefineChat.ModeType_MYFRIEND;
			mode = groupType;
			new ModeTransGroupDialog(GroupSettingActivity.this, groupId, groupType,
					new ModeTransGroupDialog.OnSetListener() {
						@Override
						public void onSelect(int option) {
							//	 setSight( option );
							//txt_power.setText(""+admin);
						}
					}).show();
		}
	}

	// 群组成员gridadapter
	private class GridAdapter extends BaseAdapter {

		public boolean isInDeleteMode;
		private List<Member> Members;		
		Context context;

		public GridAdapter(Context context, List<Member> objects) {

			this.Members = objects;
			this.context = context;
			isInDeleteMode = false;
		}
		@Override
		public View getView(final int position, View convertView,
				final ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(context).inflate(
						R.layout.item_chatsetting_gridview, null);
			}
			ImageView iv_avatar = (ImageView) convertView
					.findViewById(R.id.iv_avatar);
			TextView tv_username = (TextView) convertView
					.findViewById(R.id.tv_username);
			ImageView badge_delete = (ImageView) convertView
					.findViewById(R.id.badge_delete);

			// 最后一个item，减人按钮
			if (position == getCount() - 1 && is_admin) {
				tv_username.setText("");
				badge_delete.setVisibility(View.GONE);
				iv_avatar.setImageResource(R.drawable.icon_btn_deleteperson);

				if (isInDeleteMode) {
					// 正处于删除模式下，隐藏删除按钮
					convertView.setVisibility(View.GONE);
				} else {

					convertView.setVisibility(View.VISIBLE);
				}

				iv_avatar.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						isInDeleteMode = true;
						notifyDataSetChanged();
					}
				});

			} else if ((is_admin && position == getCount() - 2)
					|| (!is_admin && position == getCount() - 1)) { // 添加群组成员按钮
				tv_username.setText("");
				badge_delete.setVisibility(View.GONE);
				iv_avatar.setImageResource(R.drawable.jy_drltsz_btn_addperson);
				// 正处于删除模式下,隐藏添加按钮
				if (isInDeleteMode) {
					convertView.setVisibility(View.GONE);
				} else {
					convertView.setVisibility(View.VISIBLE);
				}
				iv_avatar.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// 进入选人页面
					//	startActivity((new Intent(GroupSettingActivity.this,
					//			AddGroupChatActivity.class).putExtra(
					//			Constants.GROUP_ID, groupId)));
					//	startActivity((new Intent(GroupSettingActivity.this,
					//			AddnewMemberActivity.class).putExtra(
					//			Constants.GROUP_ID, groupId)));	
						Intent intent = new Intent(GroupSettingActivity.this, AddnewMemberActivity.class);
						intent.putExtra("Chat_ID",groupId);
						intent.putExtra("Chat_Type",groupType);
						intent.putExtra("Chat_Name",groupName);			
						startActivity(intent);	
						//Utils.start_Activity(context,intent); 						
					}
				});
			}

			else { // 普通item，显示群组成员

				final Member user = Members.get(position);
				final String usernick = user.getName();
				final int userid = user.getUserId();
				int imageid = user.getHeadImg();
				if(imageid<0||imageid>80)
					imageid = imageid%80;
				final String useravatar = user.getHeadUrl();
				tv_username.setText(usernick);
	
				iv_avatar.setImageResource(ImagesUtils.images[imageid]);							
				if (isInDeleteMode) {
					// 如果是删除模式下，显示减人图标
					convertView.findViewById(R.id.badge_delete).setVisibility(
							View.VISIBLE);
				} else {
					convertView.findViewById(R.id.badge_delete).setVisibility(
							View.INVISIBLE);
				}
				iv_avatar.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if (isInDeleteMode) {
							// 如果是删除自己，return						
							if (GloableParams.m_szUserId == userid) {
								Utils.showLongToast(GroupSettingActivity.this,
										"不能删除自己");
								return;
							}
							 deleteMembersFromGroup(user);//TODO
						} else {
							// 正常情况下点击user，可以进入用户详情或者聊天页面等等
							Intent intent = new Intent(
									GroupSettingActivity.this,
									EMChatActivity.class);

							intent.putExtra("Chat_ID",user.getUserId());
							intent.putExtra("Chat_Type",DefineChat.ChatType_USER);
							intent.putExtra("Chat_Name",user.getName());							
							startActivity(intent);
							overridePendingTransition(R.anim.push_left_in,
									R.anim.push_left_out);
						}
					}
				});
			}
			return convertView;
		}

		@Override
		public int getCount() {
			if (is_admin) {
				return Members.size() + 2;
			} else {

				return Members.size() + 1;
			}
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return Members.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}
	}
	
	protected void updateGroup() {
		MemberClient.updataJoinClass(groupId,  new updataCallBack() {// 回调		
					@Override
				//	public void onSuccess(int code, Object contex) {
					public void onSuccess(int code, byte[] data) {						

						runOnUiThread(new Runnable() {
							public void run() {
	
								adapter.notifyDataSetChanged();
								//if (EMChatManager.getInstance().getCurrentUser().equals(group.getOwner())) {								
								if (2>1) {
									//显示解散按钮
									exitBtn.setVisibility(View.GONE);
									deleteBtn.setVisibility(View.VISIBLE);
								}else{
									//显示退出按钮
									exitBtn.setVisibility(View.VISIBLE);
									deleteBtn.setVisibility(View.GONE);
									
								}							
							}
						});						
					}

					@Override
					public void onFailure(final int errorCode, final String message) {
						runOnUiThread(new Runnable() {
							public void run() {
							//	getLoadingDialog("正在登录...").dismiss();
								Utils.showLongToast(GroupSettingActivity.this, message);								
							}
						});							
					}
				});		

	}	

	public void deleteMembersFromGroup(Member user){
		final int nDestid = user.getUserId();
		new MyAlertDialog(GroupSettingActivity.this,"删除成员？",
				"你确定要从此群中删除该成员吗？",
				new MyAlertDialog.OnSetListener() {
					@Override
					public void onSelect(int comm) {
						UserInfo uinfo = new UserInfo(nDestid,groupId,"",5,1,50);
						deleteMember(uinfo);							
					}
				}).show();
	}
	
	public void deleteMember(UserInfo uinfo){
		int nDestid = uinfo.destid;
		if(nDestid == GloableParams.m_szUserId){//判断是否是自己
		//	startActivity(new Intent(this, AlertDialog.class).putExtra("msg", "不能添加自己"));
		//	return;
		}	
		if(FriendUtils.getFriendList(nDestid)>0){//判断是否已经是好友
		//	startActivity(new Intent(this, AlertDialog.class).putExtra("msg", "此用户已是你的好友"));
		//	return;
		}	
		if(TextUtils.isEmpty(GloableParams.m_szServerIp)){//判断是否已经登录服务器
			Utils.showLongToast(GroupSettingActivity.this, "你还没有登录服务器!");
			return;
		}		
	//	getLoadingDialog("正在发送请求...").show();		
		EditClient.DeleteMember(groupType,uinfo,new askCallBack(){	
			@Override
			public void onSuccess(int statusCode, String message) {
	//			getLoadingDialog("正在发送请求...").dismiss();	
				final String str = message;
				runOnUiThread(new Runnable() {
					public void run() {
						Utils.showLongToast(GroupSettingActivity.this, str);
					}
				});				
			}
			@Override
			public void onFailure(int statusCode,  String message) {
	//			getLoadingDialog("正在发送请求...").dismiss();
				final String str = message;
				runOnUiThread(new Runnable() {
					public void run() {
						Utils.showLongToast(GroupSettingActivity.this, str);
					}
				});	
			}
		});	 
	}	

	public void exitFromGroup(){
	//	final int nDestid = user.getUserId();
		String title = "";
		String message = "";			
		switch (groupType) {		
		case DefineUser.TYPE_FRIEND:		
			break;
		case DefineUser.TYPE_CROWD:
			title = "退出该群？";
			message = "你确定要退出该群吗？"; 			
			break;			
		case DefineUser.TYPE_MYCLASS:
			title = "退出该班？";
			message = "你确定要退出该班吗？"; 			
			break;
		case DefineUser.TYPE_DEPART:
			title = "退出该部门？";
			message = "你确定要退出该部门吗？"; 			
			break;			
		case DefineUser.TYPE_PARTY:
			title = "退出该会议室？";
			message = "你确定要退出该会议室吗？"; 			
			break;
		case DefineUser.TYPE_GROUP:
			title = "退出该俱乐部？";
			message = "你确定要退出该俱乐部？"; 			
			break;
		case DefineUser.TYPE_CITY:
			title = "退出该地区？";
			message = "你确定要退出该地区吗？"; 			
			break;				
		default:			
			break;
		}			
		new MyAlertDialog(GroupSettingActivity.this,title,message,
				new MyAlertDialog.OnSetListener() {
					@Override
					public void onSelect(int comm) {
						//addFriend(askInfo);
						GroupInfo uinfo = new GroupInfo(groupId,groupName,5,1,10);						
						exitGroup(uinfo);					
					}
				}).show();	
	}	
	
	public void exitGroup(GroupInfo uinfo){
		int nDestid = uinfo.groupid;
		if(nDestid == GloableParams.m_szUserId){//判断是否是自己
		//	startActivity(new Intent(this, AlertDialog.class).putExtra("msg", "不能添加自己"));
		//	return;
		}	
		if(FriendUtils.getFriendList(nDestid)>0){//判断是否已经是好友
		//	startActivity(new Intent(this, AlertDialog.class).putExtra("msg", "此用户已是你的好友"));
		//	return;
		}
		if(TextUtils.isEmpty(GloableParams.m_szServerIp)){//判断是否已经登录服务器
			Utils.showLongToast(GroupSettingActivity.this, "你还没有登录服务器!");
			return;
		}		
	//	getLoadingDialog("正在发送请求...").show();		
		EditClient.exitGroup(groupType,uinfo,new askCallBack(){	
			@Override
			public void onSuccess(int statusCode, String message) {
	//			getLoadingDialog("正在发送请求...").dismiss();	
				final String str = message;
				runOnUiThread(new Runnable() {
					public void run() {
						Utils.showLongToast(GroupSettingActivity.this, str);
					}
				});				
			}
			@Override
			public void onFailure(int statusCode,  String message) {
	//			getLoadingDialog("正在发送请求...").dismiss();
				final String str = message;
				runOnUiThread(new Runnable() {
					public void run() {
						Utils.showLongToast(GroupSettingActivity.this, str);
					}
				});	
			}
		});	 
	}	
}
