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 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.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.widget.ListView;
import android.widget.TextView;

public class TeamMemberActivity extends BaseActivity {
	ListView teammember_list;
	private TeamListAdapter adapter;
	String eventId = "";
	private SharedPreferences sp;
	TextView teammember_teamname;
	TextView teammember_teamnumber;
	TextView teammember_teamcaptain;

	String teamName = "暂无信息";
	String teamsize = "暂无信息";
	String captainName = "暂无信息";
	private final int SUCCESS = 1;
	private final int ERR = 5;
	private final int NOINFO = 6;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_team_member);
		sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
		initTitleBar("我的团队");
		Intent intent = getIntent();
		eventId = intent.getStringExtra("eventId");
		teammember_list = (ListView) findViewById(R.id.teammember_list);
		teammember_teamname = (TextView) findViewById(R.id.teammember_teamname);
		teammember_teamnumber = (TextView) findViewById(R.id.teammember_teamnumber);
		teammember_teamcaptain = (TextView) findViewById(R.id.teammember_teamcaptain);
		adapter = new TeamListAdapter(this);
		new Thread(new Runnable() {
			@Override
			public void run() {
				getTeamPeople();
			}

		}).start();
	}

	private void getTeamPeople() {
		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 = NOINFO;
					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"));
					String userId = StringUtils.toString(userInfomation
							.get("userId"));
					String organizerId = StringUtils.toString(userInfomation
							.get("organizerId"));
					if (userId.equals(organizerId)) {
						captainName = userName;
					}
					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 = SUCCESS;
				handler.sendMessage(message);
			} else {
				Message message = new Message();
				message.what = ERR;
				handler.sendMessage(message);
			}

		} catch (Exception e) {
			Message message = new Message();
			message.what = ERR;
			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 SUCCESS:
				teammember_teamname.setText(teamName);
				teammember_teamnumber.setText(teamsize);
				teammember_teamcaptain.setText(captainName);
				teammember_list.setAdapter(adapter);
				adapter.notifyDataSetChanged();
				break;
			case ERR:
				ToastUtil.show(TeamMemberActivity.this, "网络异常，请检查网络");
				break;
			case NOINFO:
				Fragment5twoAdapter adapter6 = new Fragment5twoAdapter(
						TeamMemberActivity.this);
				adapter6.addData("暂无团队信息");
				teammember_list.setAdapter(adapter6);
				adapter6.notifyDataSetChanged();
				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_member, menu);
		return true;
	}

}
