package com.smart.gtstrvl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import com.example.mountaintravel.adapter.Fragment5twoAdapter;
import com.example.mountaintravel.adapter.TeamListAdapter;
import com.example.mountaintravel.base.BaseActivity;
import com.example.mountaintravel.kind.TeamListInfo;
import com.example.mountaintravel.util.StringChangeUtils;
import com.example.mountaintravel.util.StringUtils;
import com.example.mountaintravel.util.ToastUtil;
import com.example.mountaintravel.variable.Variable;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.R.integer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class TeamManageActivity extends BaseActivity implements OnClickListener {
	private ListView teammanage_list;
	private TeamListAdapter adapter;
	private int positiontrue;
	String eventId = "";
	private SharedPreferences sp;
	String teamId = "";
	TextView teammanage_teamname;
	TextView teammanage_teamnumber;
	Button teammanage_teamfire;
	String teamName = "暂无信息";
	String teamsize = "暂无信息";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_team_manage);
		initTitleBar("我的团队");
		sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
		Intent intent = getIntent();
		eventId = intent.getStringExtra("eventId");
		teammanage_list = (ListView) findViewById(R.id.teammanage_list);
		teammanage_list.setOnItemClickListener(listener);
		teammanage_teamname = (TextView) findViewById(R.id.teammanage_teamname);
		teammanage_teamnumber = (TextView) findViewById(R.id.teammanage_teamnumber);
		teammanage_teamfire = (Button) findViewById(R.id.teammanage_teamfire);
		teammanage_teamfire.setOnClickListener(this);
		adapter = new TeamListAdapter(this);
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				getTeamPeople();
			}

		}).start();
		// for (int i = 0; i < 30; i++) {
		// TeamListInfo info = new TeamListInfo(i + "A","","", "踢出团队");
		// adapter.addData(info);
		// }
		// teammanage_list.setAdapter(adapter);
		// adapter.notifyDataSetChanged();
	}

	android.widget.AdapterView.OnItemClickListener listener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			positiontrue = position;
			if (!adapter.getItem(position).getUserId()
					.equals(sp.getString("userid", "-1"))) {
				AlertDialog isExit = new AlertDialog.Builder(
						TeamManageActivity.this).create();
				// 设置对话框消息
				isExit.setMessage("确定要将"
						+ adapter.getItem(position).getTeamName() + "踢出团队吗？");
				// 添加选择按钮并注册监听
				isExit.setButton("确定", listenerremove);
				isExit.setButton2("取消", listenerremove);
				// 显示对话框
				isExit.show();
			}

		}
	};
	DialogInterface.OnClickListener listenerremove = new DialogInterface.OnClickListener() {
		@SuppressLint("NewApi")
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
				new Thread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub

						fireTeam();
					}

				}).start();
				break;
			case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框

				break;
			}
		}
	};
	DialogInterface.OnClickListener listenerrefire = new DialogInterface.OnClickListener() {
		@SuppressLint("NewApi")
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
				new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						fire_team();
					}

				}).start();
				break;
			case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框

				break;
			}
		}
	};

	private void fireTeam() {
		// TODO Auto-generated method stub
		DefaultHttpClient client = new DefaultHttpClient();
		String strURL = "http://" + Variable.address
				+ "/terminal/event/fire_team_user";
		HttpPost httpPost = new HttpPost(strURL);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			parameters.add(new BasicNameValuePair("userId", adapter.getItem(
					positiontrue).getUserId()));
			parameters.add(new BasicNameValuePair("organizerId", sp.getString(
					"userid", "")));
			parameters.add(new BasicNameValuePair("teamId", teamId));
			parameters.add(new BasicNameValuePair("eventId", eventId));
			System.out.println(adapter.getItem(positiontrue).getUserId()
					+ "sad");
			System.out.println(eventId + "fs");
			System.out.println(teamId + "asfd");
			// 创建传递参数封装 实体对象
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
					"UTF-8");// 设置传递参数的编码
			// 把实体对象存入到httpPost对象中
			httpPost.setEntity(entity);
			// 3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
			HttpResponse response = client.execute(httpPost); // HttpUriRequest的后代对象
			if (response.getStatusLine().getStatusCode() == 200) {
				String is = EntityUtils.toString(response.getEntity(), "UTF-8");
				// String result = StreamTools.streamToString(is);
				byte[] outMsgBytes = is.getBytes("UTF-8");
				String result = new String(outMsgBytes, "UTF-8");

				System.out.println(result);
				JSONObject json = new JSONObject(result);
				String code = json.getString("code");
				if (code.equals("000")) {
					Message message = new Message();
					message.what = 0;
					handler.sendMessage(message);

				} else {
					Message message = new Message();
					message.what = 4;
					handler.sendMessage(message);

				}
			} else {
				Message message = new Message();
				message.what = 5;
				handler.sendMessage(message);
			}

		} catch (Exception e) {
			Message message = new Message();
			message.what = 5;
			handler.sendMessage(message);
			e.printStackTrace();
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}
	}

	private void getTeamPeople() {
		// TODO Auto-generated method stub
		DefaultHttpClient client = new DefaultHttpClient();
		String strURL = "http://" + Variable.address
				+ "/terminal/event/one_team_user_list";
		HttpPost httpPost = new HttpPost(strURL);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			parameters.add(new BasicNameValuePair("eventId", eventId));
			parameters.add(new BasicNameValuePair("userId", sp.getString(
					"userid", "")));
			// 创建传递参数封装 实体对象
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
					"UTF-8");// 设置传递参数的编码
			// 把实体对象存入到httpPost对象中
			httpPost.setEntity(entity);
			// 3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
			HttpResponse response = client.execute(httpPost); // HttpUriRequest的后代对象
			if (response.getStatusLine().getStatusCode() == 200) {
				String is = EntityUtils.toString(response.getEntity(), "UTF-8");
				// String result = StreamTools.streamToString(is);
				byte[] outMsgBytes = is.getBytes("UTF-8");
				String result = new String(outMsgBytes, "UTF-8");
				System.out.println(result);
				HashMap<String, Object> parameterMap = StringChangeUtils
						.toObject(result, HashMap.class);
				Object result_obj = parameterMap.get("teamUserList");
				List<String> AllUserInformation = (List<String>) result_obj;
				teamsize = AllUserInformation.size() + "";
				if (AllUserInformation.size() == 0) {
					Message message = new Message();
					message.what = 6;
					handler.sendMessage(message);
					return;
				}
				for (int i = 0; i < AllUserInformation.size(); i++) {
					HashMap<String, Object> userInfomation = StringChangeUtils
							.toObject(AllUserInformation.get(i), HashMap.class);
					String userName = StringUtils.toString(userInfomation
							.get("userName"));
					teamName = StringUtils.toString(userInfomation
							.get("teamName"));
					teamId = StringUtils.toString(userInfomation.get("teamId"));

					String userId = StringUtils.toString(userInfomation
							.get("userId"));
					if (userId.equals(sp.getString("userid", "-1"))) {
						TeamListInfo info = new TeamListInfo(userName, "", "",
								"队长", userId);
						adapter.addData(info);
					} else {
						TeamListInfo info = new TeamListInfo(userName, "", "",
								"踢出团队", userId);
						adapter.addData(info);
					}
					// String repeaterSort =
					// StringUtils.toString(userInfomation.get("repeaterSort"));
					// String userId =
					// StringUtils.toString(userInfomation.get("axisX"));
				}

				Message message = new Message();
				message.what = 1;
				handler.sendMessage(message);
			} else {
				Message message = new Message();
				message.what = 5;
				handler.sendMessage(message);
			}

		} catch (Exception e) {
			Message message = new Message();
			message.what = 5;
			handler.sendMessage(message);
			e.printStackTrace();
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}

	}

	final Handler handler = new Handler() { // handle
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				ToastUtil.show(TeamManageActivity.this, "踢出成功");
				adapter.clear();
				new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						getTeamPeople();
					}

				}).start();
				break;
			case 1:
				teammanage_teamname.setText(teamName);
				teammanage_teamnumber.setText(teamsize);
				teammanage_list.setAdapter(adapter);
				adapter.notifyDataSetChanged();
				break;
			case 4:
				ToastUtil.show(TeamManageActivity.this, "操作失败");
				break;
			case 5:
				ToastUtil.show(TeamManageActivity.this, "网络异常，请检查网络");
				break;
			case 6:
				Fragment5twoAdapter adapter6 = new Fragment5twoAdapter(
						TeamManageActivity.this);
				adapter6.addData("暂无团队信息");
				teammanage_list.setAdapter(adapter6);
				adapter6.notifyDataSetChanged();
				break;
			case 7:
				ToastUtil.show(TeamManageActivity.this, "解散成功");
				startActivity(EventInfoActivity.class);
				break;

			}

			super.handleMessage(msg);
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.team_manage, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		AlertDialog isExit = new AlertDialog.Builder(TeamManageActivity.this)
				.create();
		// 设置对话框消息
		isExit.setMessage("确定要解散团队吗？");
		// 添加选择按钮并注册监听
		isExit.setButton("确定", listenerrefire);
		isExit.setButton2("取消", listenerrefire);
		// 显示对话框
		isExit.show();

	}

	private void fire_team() {
		DefaultHttpClient client = new DefaultHttpClient();
		String strURL = "http://" + Variable.address
				+ "/terminal/event/fire_team";
		HttpPost httpPost = new HttpPost(strURL);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			parameters.add(new BasicNameValuePair("teamId", teamId));
			parameters.add(new BasicNameValuePair("organizerId", sp.getString(
					"userid", "")));
			// 创建传递参数封装 实体对象
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
					"UTF-8");// 设置传递参数的编码
			// 把实体对象存入到httpPost对象中
			httpPost.setEntity(entity);
			// 3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
			HttpResponse response = client.execute(httpPost); // HttpUriRequest的后代对象
			if (response.getStatusLine().getStatusCode() == 200) {
				String is = EntityUtils.toString(response.getEntity(), "UTF-8");
				// String result = StreamTools.streamToString(is);
				byte[] outMsgBytes = is.getBytes("UTF-8");
				String result = new String(outMsgBytes, "UTF-8");
				System.out.println(result);
				JSONObject json = new JSONObject(result);
				String code = json.getString("code");
				if (code.equals("000")) {
					Message message = new Message();
					message.what = 7;
					handler.sendMessage(message);

				} else {
					Message message = new Message();
					message.what = 4;
					handler.sendMessage(message);

				}
			} else {
				Message message = new Message();
				message.what = 5;
				handler.sendMessage(message);
			}

		} catch (Exception e) {
			Message message = new Message();
			message.what = 5;
			handler.sendMessage(message);
			e.printStackTrace();
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}

	}
}
