package com.example.mountaintravel.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

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.Fragment5Adapter;
import com.example.mountaintravel.adapter.Fragment5twoAdapter;
import com.example.mountaintravel.kind.Fragment5Info;

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 com.example.mountaintravel.view.LoadingView;
import com.smart.gtstrvl.GameManagerActivity;
import com.smart.gtstrvl.R;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

@SuppressLint({ "ValidFragment", "NewApi" })
public class StaffFragment extends Fragment implements OnClickListener {
	private Context context;
	private Fragment5Adapter adapter;
	private String strURL = "http://" + Variable.address
			+ "/terminal/event/team_user_list";
	private static final String TAG = "FragmentPage5";
	private ListView gamelist_lv5;
	private LoadingView frag5_loadingview;
	private ArrayList<Fragment5Info> listinfo = new ArrayList<Fragment5Info>();
	private ArrayList<String> listinfo2 = new ArrayList<String>();
	RelativeLayout progress_relativelayout;
	private SharedPreferences sp;

	public StaffFragment(Context context) {
		this.context = context;
	}

	String applyStatus = "";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		return inflater.inflate(R.layout.fragment_5, container, false);
	}

	public void onResume() {
		// TODO Auto-generated method stub
		frag5_loadingview.start();
		super.onResume();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		frag5_loadingview.stop();
		super.onPause();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		sp = context.getSharedPreferences("variable", Context.MODE_PRIVATE);

		setView();
		super.onActivityCreated(savedInstanceState);
	}

	@SuppressLint("NewApi")
	public void addview() {
		WindowManager manager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = manager.getDefaultDisplay();
		DisplayMetrics outMetrics = new DisplayMetrics();
		display.getRealMetrics(outMetrics);
		progress_relativelayout = (RelativeLayout) getView().findViewById(
				R.id.progress_relativelayout);
		frag5_loadingview = new LoadingView(context, outMetrics.widthPixels);
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, 6);
		// lp.addRule(RelativeLayout.ALIGN_BASELINE);
		progress_relativelayout.setOnClickListener(this);
		// lp.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
		progress_relativelayout.addView(frag5_loadingview, lp);

	}

	private void setView() {
		// TODO Auto-generated method stub
		addview();
		gamelist_lv5 = (ListView) getView().findViewById(R.id.gamelist_lv5);
		adapter = new Fragment5Adapter(context);
		listinfo.clear();
		adapter.clear();
		progress_relativelayout.setVisibility(View.VISIBLE);
		gamelist_lv5.setVisibility(View.GONE);
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				loginByHttpClient();
			}
		}).start();

	}

	final Handler handler = new Handler() { // handle
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				progress_relativelayout.setVisibility(View.GONE);
				gamelist_lv5.setVisibility(View.VISIBLE);
				adapter.addDataList(listinfo);
				gamelist_lv5.setAdapter(adapter);
				adapter.notifyDataSetChanged();

				break;
			case 2:
				progress_relativelayout.setVisibility(View.GONE);
				gamelist_lv5.setVisibility(View.VISIBLE);
				ToastUtil.show(context, "获取信息失败");
				break;
			case 3:
				progress_relativelayout.setVisibility(View.GONE);
				gamelist_lv5.setVisibility(View.VISIBLE);
				adapter = null;
				Fragment5twoAdapter adapter2 = new Fragment5twoAdapter(context);
				listinfo2.add("暂无信息");
				adapter2.addDataList(listinfo2);
				gamelist_lv5.setAdapter(adapter2);
				adapter2.notifyDataSetChanged();
				break;
			}

			super.handleMessage(msg);
		}
	};

	private void loginByHttpClient() {
		// TODO Auto-generated method stub
		DefaultHttpClient client = new DefaultHttpClient();

		HttpPost httpPost = new HttpPost(strURL);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			parameters.add(new BasicNameValuePair("eventId",
					GameManagerActivity.eventId));

			// 创建传递参数封装 实体对象
			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> result_map = StringChangeUtils
						.toObject(result, HashMap.class);
				Map<String, List<String>> eventTeamUserMap = (Map<String, List<String>>) result_map
						.get("eventTeamUser");
				Iterator<Entry<String, List<String>>> eventTeamUserIter = eventTeamUserMap
						.entrySet().iterator();
				while (eventTeamUserIter.hasNext()) {
					Map.Entry entry = (Map.Entry) eventTeamUserIter.next();
					// String teamName = (String) entry.getKey();
					// System.out.println(teamName);
					List<String> haveTeamUserList = (List<String>) entry
							.getValue();
					for (int i = 0; i < haveTeamUserList.size(); i++) {
						HashMap<String, Object> userInfomation = StringChangeUtils
								.toObject(haveTeamUserList.get(i),
										HashMap.class);
						String userName = StringUtils.toString(userInfomation
								.get("userName"));
						String userPhone = StringUtils.toString(userInfomation
								.get("userPhone"));
						String teamName = StringUtils.toString(userInfomation
								.get("teamName"));
						Fragment5Info info = new Fragment5Info(false, userName,
								userPhone, "已通过", teamName, "");
						listinfo.add(info);

					}

				}

				Object result_obj = result_map.get("eventNotTeamUser");
				List<String> AllUserInformation = (List<String>) result_obj;
				if (AllUserInformation.size() == 0 && listinfo.size() == 0) {
					Message message = new Message();
					message.what = 3;
					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"));
					String userPhone = StringUtils.toString(userInfomation
							.get("userPhone"));
					Fragment5Info info = new Fragment5Info(false, userName,
							userPhone, "已通过", "", "");
					listinfo.add(info);

				}

				Message message = new Message();
				message.what = 1;
				handler.sendMessage(message);

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

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

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

	}

}
