package com.smart.gtstrvl;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

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

import com.alipay.sdk.app.PayTask;
import com.example.mountaintravel.base.BaseActivity;
import com.example.mountaintravel.fragment.MapFragment;
import com.example.mountaintravel.fragment.GradeFragment;
import com.example.mountaintravel.fragment.StaffFragment;
import com.example.mountaintravel.kind.GameInfo;
import com.example.mountaintravel.kind.PayResult;
import com.example.mountaintravel.service.MyGPSservice;
import com.example.mountaintravel.service.MyService;
import com.example.mountaintravel.util.AesTerminalUtil;
import com.example.mountaintravel.util.MD5Util;
import com.example.mountaintravel.util.StreamTools;
import com.example.mountaintravel.util.ToastUtil;
import com.example.mountaintravel.util.Util;
import com.example.mountaintravel.variable.Variable;
import com.example.mountaintravel.view.TitleBarView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.R.integer;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class GameManagerActivity extends BaseActivity implements
		OnClickListener {
	public static TextView tvclock1;
	public static TextView tvclock2;
	public static TextView tvclock3;
	public static TextView tvclock4;
	public static TextView tvclock5;
	public static TextView tvclock6;
	public static TextView tvclock7;
	public static TextView tvclock8;
	public static double pointx = 0.000;
	public static double pointy = 0.000;
	public MyService.MyBinder myBinder;
	private FrameLayout frameLayout;
	@SuppressLint("NewApi")
	private FragmentManager fm = this.getFragmentManager();
	private FragmentTransaction ft;
	private MapFragment fragmentPage3;
	private GradeFragment fragmentPage4;
	private StaffFragment fragmentPage5;
	private static final String TAG = "GameManagerActivity";
	private TextView gamemanager_tvmap;
	private TextView gamemanager_tvlist;
	private TextView gamemanager_tvapply;
	private boolean official = false;
	private boolean manager = false;
	private String hour = "";
	private String min = "";
	private String ss = "";
	private String ifBegin = "";
	private String begintime = "";
	public static String eventId = "";
	public static TextView gamemana_tv;
	public static TextView gamemana_tv2;
	private TextView gamemana_tv3;
	public static String result = "";
	private String key = ".5Xf_01KXd352s177Jx3wxXc074poII";
	private SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
	private String time = format.format(new Date());
	private String type = "android";
	private String sign = MD5Util.MD5(time + type + key);
	private String status = "";
	private String iftype = "";
	private boolean startorstop = false;
	private SharedPreferences sp;
	public static String eventEndTime = "";
	public static String eventStartTime = "";
	private boolean ifclick = false;
	public static boolean ifStart = false;
	boolean mBind = false;
	public static IWXAPI api;
	ImageView gamemana_leftivback;
	ImageView gamemana_share;
	public static final String PARTNER = "2088021830678838";
	// 商户收款账号
	public static final String SELLER = "gaotingshan517@163.com ";
	// 支付宝公钥
	public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB";
	private static final int SDK_PAY_FLAG = 1;
	private String orderInfo = "";
	String amount = "";
	String msg = "";

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_game_manager);
		sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
		Intent intent = getIntent();
		findView();
		Variable.className = "GameManagerActivity";
		hour = intent.getStringExtra("hour");
		ss = intent.getStringExtra("ss");
		gamemana_tv.setVisibility(View.GONE);
		gamemana_tv2.setVisibility(View.VISIBLE);
		ifStart = true;
		eventId = intent.getStringExtra("eventId");
		min = intent.getStringExtra("min");
		official = intent.getBooleanExtra("official", false);
		manager = intent.getBooleanExtra("manager", false);
		if (manager) {
			gamemana_tv.setVisibility(View.VISIBLE);
			gamemanager_tvapply.setVisibility(View.VISIBLE);
		} else if (!manager) {
			gamemana_tv.setVisibility(View.GONE);
			// gamemanager_tvapply.setVisibility(View.GONE);
		}
		ifBegin = intent.getStringExtra("ifBegin");
		begintime = intent.getStringExtra("begintime");
		eventStartTime = intent.getStringExtra("eventStartTime");
		eventEndTime = intent.getStringExtra("eventEndTime");
		frameLayout = (FrameLayout) findViewById(R.id.fragment_content);
		/*
		 * sp.edit().putBoolean("official", official).commit();
		 * sp.edit().putBoolean("manager", manager).commit();
		 * sp.edit().putString("hour", hour).commit();
		 * sp.edit().putString("min", min).commit(); sp.edit().putString("ss",
		 * ss).commit(); sp.edit().putString("ifBegin", ifBegin).commit();
		 */
		if (isWorked("com.example.mountaintravel.service.MyService")) {
			Intent stopIntent = new Intent(this, MyService.class);
			stopService(stopIntent);
			if (mBind) {
				unbindService(connection);
			}
			Variable.recLen1 = 0;
			Variable.recLen2 = 0;
			Variable.recLen3 = 0;
			Variable.recLen4 = 0;
			Variable.recLen5 = 0;
			Variable.recLen6 = 0;
			Intent startIntent = new Intent(this, MyService.class);
			startIntent.putExtra("official", official);
			startIntent.putExtra("manager", manager);
			startIntent.putExtra("hour", hour);
			startIntent.putExtra("min", min);
			startIntent.putExtra("ss", ss);
			startIntent.putExtra("ifBegin", ifBegin);
			startService(startIntent);
			Intent bindIntent = new Intent(this, MyService.class);
			bindService(bindIntent, connection, BIND_AUTO_CREATE);
			mBind = true;
		} else {
			Intent startIntent = new Intent(this, MyService.class);
			startIntent.putExtra("official", official);
			startIntent.putExtra("manager", manager);
			startIntent.putExtra("hour", hour);
			startIntent.putExtra("min", min);
			startIntent.putExtra("ss", ss);
			startIntent.putExtra("ifBegin", ifBegin);
			startService(startIntent);
			Intent bindIntent = new Intent(this, MyService.class);
			bindService(bindIntent, connection, BIND_AUTO_CREATE);
			mBind = true;
		}
		ft = fm.beginTransaction();
		friend();
		ft.commit();
	}

	@SuppressLint("NewApi")
	private void home() {
		if (fragmentPage4 == null) {
			fragmentPage4 = new GradeFragment(this);
			ft.add(R.id.fragment_content, fragmentPage4);
		} else {
			ft.show(fragmentPage4);
		}
	}

	@SuppressLint("NewApi")
	private void frag5() {
		if (fragmentPage5 == null) {
			fragmentPage5 = new StaffFragment(this);
			ft.add(R.id.fragment_content, fragmentPage5);
		} else {
			ft.show(fragmentPage5);
		}
	}

	@SuppressLint("NewApi")
	private void friend() {
		if (fragmentPage3 == null) {
			fragmentPage3 = new MapFragment(this);

			ft.add(R.id.fragment_content, fragmentPage3);
		} else {
			ft.show(fragmentPage3);
		}
	}

	@SuppressLint("NewApi")
	private void setSelected() {
		if (fragmentPage3 != null) {
			ft.hide(fragmentPage3);
		}
		if (fragmentPage4 != null) {
			ft.remove(fragmentPage4);
			fragmentPage4 = null;
		}
		if (fragmentPage5 != null) {
			ft.remove(fragmentPage5);
			fragmentPage5 = null;
		}
	}

	@SuppressLint("NewApi")
	@Override
	public void onClick(View v) {
		ft = fm.beginTransaction();
		setSelected();
		switch (v.getId()) {
		case R.id.gamemana_leftivback:
			if (sp.getBoolean("eventinfo", false)) {
				sp.edit().putBoolean("eventinfo", false).commit();
				finish();
				return;
			}
			startActivity(GameListActivity.class, R.anim.right_out,
					R.anim.left_in);
			finish();
			break;
		case R.id.gamemana_share:
			if (!isWXAppInstalledAndSupported()) {
				ToastUtil.show(GameManagerActivity.this, "未安装微信客户端");
				return;
			}
			if (api == null) {
				api = WXAPIFactory.createWXAPI(GameManagerActivity.this,
						"wxb8f15f96478031e0", false);
			}
			api.registerApp("wxb8f15f96478031e0");
			share2Wx();
			break;
		case R.id.gamemanager_tvlist:
			gamemana_share.setVisibility(View.VISIBLE);
			gamemanager_tvmap.setBackground(getResources().getDrawable(
					R.drawable.gamemanager_tv_no));
			gamemanager_tvlist.setBackground(getResources().getDrawable(
					R.drawable.gamemanager_tv_yes));
			gamemanager_tvapply.setBackground(getResources().getDrawable(
					R.drawable.gamemanager_tv_no));
			home();
			break;
		case R.id.gamemanager_tvmap:
			gamemana_share.setVisibility(View.GONE);
			gamemanager_tvmap.setBackground(getResources().getDrawable(
					R.drawable.gamemanager_tv_yes));
			gamemanager_tvlist.setBackground(getResources().getDrawable(
					R.drawable.gamemanager_tv_no));
			gamemanager_tvapply.setBackground(getResources().getDrawable(
					R.drawable.gamemanager_tv_no));
			friend();
			break;
		case R.id.gamemanager_tvapply:
			gamemana_share.setVisibility(View.GONE);
			gamemanager_tvmap.setBackground(getResources().getDrawable(
					R.drawable.gamemanager_tv_no));
			gamemanager_tvlist.setBackground(getResources().getDrawable(
					R.drawable.gamemanager_tv_no));
			gamemanager_tvapply.setBackground(getResources().getDrawable(
					R.drawable.gamemanager_tv_yes));
			frag5();
			break;
		}
		ft.commit();
	}

	private boolean isWXAppInstalledAndSupported() {
		IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
		msgApi.registerApp("wxb8f15f96478031e0");

		boolean sIsWXAppInstalledAndSupported = msgApi.isWXAppInstalled()
				&& msgApi.isWXAppSupportAPI();

		return sIsWXAppInstalledAndSupported;
	}

	private void share2Wx() {
		String url = "http://" + Variable.address
				+ "/wap/event_repeater_ranking?eventId="
				+ GameManagerActivity.eventId;
		WXWebpageObject webpage = new WXWebpageObject();
		webpage.webpageUrl = url + "&shareFlag=1";
		WXMediaMessage msg = new WXMediaMessage(webpage);
		msg.title = "智慧皋亭山－－赛事成绩";
		Bitmap thumb = BitmapFactory.decodeResource(this.getResources(),
				R.drawable.app_icon);
		if (thumb == null) {
			// Toast.makeText(context, "图片不能为空", Toast.LENGTH_SHORT).show();
		} else {
			msg.thumbData = Util.bmpToByteArray(thumb, true);
		}
		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = buildTransaction("webpage");
		req.message = msg;
		req.scene = SendMessageToWX.Req.WXSceneTimeline;
		api.sendReq(req);

	}

	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis())
				: type + System.currentTimeMillis();
	}

	private void findView() {
		tvclock1 = (TextView) findViewById(R.id.tvclock1);
		tvclock2 = (TextView) findViewById(R.id.tvclock2);
		tvclock3 = (TextView) findViewById(R.id.tvclock3);
		tvclock4 = (TextView) findViewById(R.id.tvclock4);
		tvclock5 = (TextView) findViewById(R.id.tvclock5);
		tvclock6 = (TextView) findViewById(R.id.tvclock6);
		tvclock7 = (TextView) findViewById(R.id.tvclock7);
		tvclock8 = (TextView) findViewById(R.id.tvclock8);
		gamemana_leftivback = (ImageView) findViewById(R.id.gamemana_leftivback);
		gamemana_leftivback.setOnClickListener(this);
		gamemana_share = (ImageView) findViewById(R.id.gamemana_share);
		gamemana_share.setOnClickListener(this);
		gamemana_tv = (TextView) findViewById(R.id.gamemana_tv);
		gamemana_tv.setOnClickListener(listener);
		gamemana_tv2 = (TextView) findViewById(R.id.gamemana_tv2);
		gamemana_tv2.setOnClickListener(listener2);
		gamemana_tv3 = (TextView) findViewById(R.id.gamemana_tv3);
		gamemanager_tvmap = (TextView) findViewById(R.id.gamemanager_tvmap);
		gamemanager_tvlist = (TextView) findViewById(R.id.gamemanager_tvlist);
		gamemanager_tvapply = (TextView) findViewById(R.id.gamemanager_tvapply);
		gamemanager_tvmap.setOnClickListener(this);
		gamemana_tv.setVisibility(View.VISIBLE);
		gamemanager_tvlist.setOnClickListener(this);
		gamemanager_tvapply.setOnClickListener(this);
	}

	android.view.View.OnClickListener listener = new android.view.View.OnClickListener() {
		@Override
		public void onClick(View v) {

			startorstop = false;
			new Thread(new Runnable() {
				@Override
				public void run() {
					loginByHttpClientSys();
				}
			}).start();
		}
	};
	android.view.View.OnClickListener listener2 = new android.view.View.OnClickListener() {
		@Override
		public void onClick(View v) {
			startorstop = true;
			if (ifclick) {
				ToastUtil.show(GameManagerActivity.this, "等待服务器响应，请稍等");
			} else {
				AlertDialog isExit = new AlertDialog.Builder(
						GameManagerActivity.this).create();
				// 设置对话框标题
				// 设置对话框消息
				isExit.setMessage("确定要结束比赛吗?");
				// 添加选择按钮并注册监听
				isExit.setButton("确定", listener4);
				isExit.setButton2("取消", listener4);
				// 显示对话框
				isExit.show();
			}

		}
	};
	DialogInterface.OnClickListener listener3 = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case AlertDialog.BUTTON_POSITIVE:

				break;

			}
		}
	};
	DialogInterface.OnClickListener listener5 = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case AlertDialog.BUTTON_POSITIVE:
				new Thread(new Runnable() {
					@Override
					public void run() {
						iftype = "1";

						ifclick = true;
						loginByHttpClientGet();

					}
				}).start();

				break;

			case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框
				break;
			}
		}
	};
	DialogInterface.OnClickListener listener4 = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
				new Thread(new Runnable() {
					@Override
					public void run() {
						ifclick = true;
						loginByHttpClientSys();
					}
				}).start();
				break;
			case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框
				break;

			}
		}
	};

	/*
	 * public boolean isServiceRunning(Context mContext, String className) {
	 * boolean isRunning = false; ActivityManager activityManager =
	 * (ActivityManager) mContext .getSystemService(Context.ACTIVITY_SERVICE);
	 * List<RunningServiceInfo> serviceList = activityManager
	 * .getRunningServices(30); if (!(serviceList.size() > 0)) { return false; }
	 * for (int i = 0; i < serviceList.size(); i++) { if
	 * (serviceList.get(i).service.getClassName().equals(className) == true) {
	 * isRunning = true; } break; } return isRunning; }
	 */
	private boolean isWorked(String className) {
		ActivityManager myManager = (ActivityManager) GameManagerActivity.this
				.getApplicationContext().getSystemService(
						Context.ACTIVITY_SERVICE);
		ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager
				.getRunningServices(300);
		for (int i = 0; i < runningService.size(); i++) {
			if (runningService.get(i).service.getClassName().toString()
					.equals(className)) {
				return true;
			}
		}
		return false;
	}

	private ServiceConnection connection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			myBinder = (MyService.MyBinder) service;
			myBinder.startDownload();
		}
	};

	protected void onDestroy() {
		super.onDestroy();
		sp.edit().putString("parameter", "").commit();
		mBind = false;
		if (isWorked("com.example.mountaintravel.service.MyService")) {
			Intent stopIntent = new Intent(this, MyService.class);
			stopService(stopIntent);
			unbindService(connection);
			Variable.recLen1 = 0;
			Variable.recLen2 = 0;
			Variable.recLen3 = 0;
			Variable.recLen4 = 0;
			Variable.recLen5 = 0;
			Variable.recLen6 = 0;
		}

	}

	private void loginByHttpClientGet() {
		DefaultHttpClient client = new DefaultHttpClient();
		String uri = "http://" + Variable.address + "/terminal/islogin";
		HttpPost httpPost = new HttpPost(uri);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			parameters.add(new BasicNameValuePair("weight", "80"));
			// 创建传递参数封装 实体对象
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
					"UTF-8");// 设置传递参数的编码
			// 把实体对象存入到httpPost对象中
			httpPost.setEntity(entity);
			if (!Variable.JSESSIONID.equals("")) {
				httpPost.setHeader("Cookie", "JSESSIONID="
						+ Variable.JSESSIONID);
			}
			// 3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
			HttpResponse response = client.execute(httpPost); // HttpUriRequest的后代对象
			if (response.getStatusLine().getStatusCode() == 200) {
				CookieStore mCookieStore = client.getCookieStore();
				List<Cookie> cookies = mCookieStore.getCookies();
				for (int i = 0; i < cookies.size(); i++) {
					// 这里是读取Cookie['PHPSESSID']的值存在静态变量中，保证每次都是同一个值
					if ("JSESSIONID".equals(cookies.get(i).getName())) {
						Variable.JSESSIONID = cookies.get(i).getValue();
						break;
					}
				}
				InputStream is = response.getEntity().getContent();
				String result = StreamTools.streamToString(is);
				JSONObject json = new JSONObject(result);
				String code = json.getString("code");
				// Message msg = new Message();
				// msg.obj = code;
				// msg.what = 0;
				// mHandler.sendMessage(msg);
				if (code.equals("4009")) {
					auLogin();
				} else if (code.equals("4008")) {
					loginByHttpClient("0");
					// String ifBegin=gameInfo.getIfBegin();

				}

			}

		} catch (Exception e) {
			e.printStackTrace();
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					ifclick = false;
					ToastUtil.show(GameManagerActivity.this, "网络超时，请检查网络");
				}
			});
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}

	}

	private void auLogin() {
		DefaultHttpClient client = new DefaultHttpClient();
		String uri = "http://" + Variable.address + "/terminal/login";
		HttpPost httpPost = new HttpPost(uri);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			parameters.add(new BasicNameValuePair("type", type));
			parameters.add(new BasicNameValuePair("time", time));
			parameters.add(new BasicNameValuePair("sign", sign));
			parameters.add(new BasicNameValuePair("name", sp.getString(
					"userName", "")));
			parameters.add(new BasicNameValuePair("login_type", "2"));
			parameters.add(new BasicNameValuePair("pwds", sp.getString(
					"userPass", "")));
			parameters.add(new BasicNameValuePair("origin", "phone"));
			// 创建传递参数封装 实体对象
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
					"UTF-8");// 设置传递参数的编码
			// 把实体对象存入到httpPost对象中
			httpPost.setEntity(entity);
			if (!Variable.JSESSIONID.equals("")) {
				httpPost.setHeader("Cookie", "JSESSIONID="
						+ Variable.JSESSIONID);
			}
			// 3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
			HttpResponse response = client.execute(httpPost); // HttpUriRequest的后代对象
																// //在浏览器中敲一下回车

			if (response.getStatusLine().getStatusCode() == 200) {
				CookieStore mCookieStore = client.getCookieStore();
				List<Cookie> cookies = mCookieStore.getCookies();
				for (int i = 0; i < cookies.size(); i++) {
					// 这里是读取Cookie['PHPSESSID']的值存在静态变量中，保证每次都是同一个值
					if ("JSESSIONID".equals(cookies.get(i).getName())) {
						Variable.JSESSIONID = cookies.get(i).getValue();
						break;
					}
				}
				InputStream is = response.getEntity().getContent();
				int b = 0;
				StringBuffer sb = new StringBuffer();
				while ((b = is.read()) != -1) {
					sb.append((char) b);
				}

				String result = sb.toString();
				JSONObject json = new JSONObject(result);
				status = json.getString("status");
				sp.edit().putString("sesskey", json.getString("sesskey"))
						.commit();

				Map<String, Object> map = AesTerminalUtil
						.gtsApiAesDecryptToMap(json.getString("sesskey"));
				sp.edit().putString("nick_name", (String) map.get("nick_name"))
						.commit();
				if (status.equals("9002")) {
					loginByHttpClient("0");
				} else {

				}

			}

		} catch (Exception e) {
			e.printStackTrace();
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					ToastUtil.show(GameManagerActivity.this, "网络超时，请检查网络");
				}
			});
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}

	}

	private void loginByHttpClient(String pay_flag) {
		DefaultHttpClient client = new DefaultHttpClient();
		String uri = "http://" + Variable.address + "/terminal/eventstartend";
		HttpPost httpPost = new HttpPost(uri);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			// 创建传递参数封装 实体对象
			parameters.add(new BasicNameValuePair("type", iftype));
			parameters.add(new BasicNameValuePair("id", eventId));
			parameters.add(new BasicNameValuePair("pay_flag", pay_flag));
			parameters.add(new BasicNameValuePair("user_id", sp.getString(
					"userid", "")));
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
					"UTF-8");// 设置传递参数的编码
			// 把实体对象存入到httpPost对象中
			httpPost.setEntity(entity);
			if (!Variable.JSESSIONID.equals("")) {
				httpPost.setHeader("Cookie", "JSESSIONID="
						+ Variable.JSESSIONID);
			}
			// 3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
			HttpResponse response = client.execute(httpPost); // HttpUriRequest的后代对象
			if (response.getStatusLine().getStatusCode() == 200) {
				CookieStore mCookieStore = client.getCookieStore();
				List<Cookie> cookies = mCookieStore.getCookies();
				for (int i = 0; i < cookies.size(); i++) {
					// 这里是读取Cookie['PHPSESSID']的值存在静态变量中，保证每次都是同一个值
					if ("JSESSIONID".equals(cookies.get(i).getName())) {
						Variable.JSESSIONID = cookies.get(i).getValue();
						break;
					}
				}
				String result = EntityUtils.toString(response.getEntity(),
						"UTF-8");
				System.out.println(result);
				JSONObject json = new JSONObject(result);
				String status = json.getString("status");
				String code = json.getString("code");

				if (status.equals("9003") && code.equals("5000")) {

					amount = json.getString("amount");
					msg = json.getString("msg");
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							// TODO Auto-generated method stub
							AlertDialog isExit = new AlertDialog.Builder(
									GameManagerActivity.this).create();
							isExit.setMessage(msg + "，确定支付吗？");
							isExit.setButton("确定", listenerPay);
							isExit.setButton2("取消", listenerPay);
							isExit.show();
						}
					});
					return;
				}
				if (status.equals("9002") && code.equals("1004")) {
					ifclick = false;
					if (iftype.equals("1")) {
						if (isWorked("com.example.mountaintravel.service.MyService")) {
							MyService.timer = true;
							myBinder.startDownload();
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									gamemana_tv.setVisibility(View.GONE);
									gamemana_tv2.setVisibility(View.VISIBLE);
									ifStart = true;
								}
							});
						} else {
							Intent startIntent = new Intent(
									GameManagerActivity.this, MyService.class);
							startIntent.putExtra("official", official);
							startIntent.putExtra("manager", manager);
							startIntent.putExtra("hour", hour);
							startIntent.putExtra("min", min);
							startIntent.putExtra("ss", ss);
							startIntent.putExtra("ifBegin", ifBegin);
							startService(startIntent);
							Intent bindIntent = new Intent(
									GameManagerActivity.this, MyService.class);

							bindService(bindIntent, connection,
									BIND_AUTO_CREATE);
							mBind = true;
							MyService.timer = true;
							myBinder.startDownload();
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									// TODO Auto-generated method stub
									gamemana_tv.setVisibility(View.GONE);
									gamemana_tv2.setVisibility(View.VISIBLE);
									ifStart = true;
								}
							});
						}
					} else if (iftype.equals("2")) {
						gamemana_tv2.setOnClickListener(null);
						if (isWorked("com.example.mountaintravel.service.MyService")) {
							Intent stopIntent = new Intent(
									GameManagerActivity.this, MyService.class);
							stopService(stopIntent);
							if (mBind) {
								Intent unIntent = new Intent(
										GameManagerActivity.this,
										MyService.class);
								unbindService(connection);
							}

							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									gamemana_tv2.setOnClickListener(null);
									gamemana_tv2.setVisibility(View.GONE);
									gamemana_tv3.setVisibility(View.VISIBLE);
								}
							});
							Variable.recLen1 = 0;
							Variable.recLen2 = 0;
							Variable.recLen3 = 0;
							Variable.recLen4 = 0;
							Variable.recLen5 = 0;
							Variable.recLen6 = 0;
						}
					}
				} else {
					ifclick = false;
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							ToastUtil.show(GameManagerActivity.this,
									"网络超时，请检查网络");
						}
					});
				}
				// String result = StreamTools.streamToString(is);
			}
		} catch (Exception e) {
			e.printStackTrace();
			ifclick = false;
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					ToastUtil.show(GameManagerActivity.this, "网络超时，请检查网络");
				}
			});
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}

	}

	DialogInterface.OnClickListener listenerPay = new DialogInterface.OnClickListener() {
		@SuppressLint("NewApi")
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case AlertDialog.BUTTON_POSITIVE:
				orderInfo = getOrderInfo("赛事服务费用", "开始比赛服务费用", amount);
				new Thread(new Runnable() {
					@Override
					public void run() {
						pay(orderInfo);
					}
				}).start();
				break;
			case AlertDialog.BUTTON_NEGATIVE:
				ifclick = false;
				break;
			}
		}
	};

	private String getOrderInfo(String subject, String body, String price) {

		// 签约合作者身份ID
		String orderInfo = "partner=" + "\"" + PARTNER + "\"";

		// 签约卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + getOutTradeNo() + "\"";

		// 商品名称
		orderInfo += "&subject=" + "\"" + subject + "\"";

		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";

		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\"" + "http://notify.msp.hk/notify.htm"
				+ "\"";

		// 服务接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";

		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";

		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";

		// 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}

	private String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
				Locale.getDefault());
		Date date = new Date();
		String key = format.format(date);
		Random r = new Random();
		key = key + r.nextInt();
		key = key.substring(0, 15);
		return key;
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	private String getSignType() {
		return "sign_type=\"RSA\"";
	}

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		@SuppressWarnings("unused")
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				PayResult payResult = new PayResult((String) msg.obj);
				/**
				 * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
				 * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
				 * docType=1) 建议商户依赖异步通知
				 */
				String resultInfo = payResult.getResult();// 同步返回需要验证的信息
				String resultStatus = payResult.getResultStatus();
				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					Toast.makeText(GameManagerActivity.this, "支付成功",
							Toast.LENGTH_SHORT).show();
					new Thread(new Runnable() {

						@Override
						public void run() {
							loginByHttpClient("1");
						}
					}).start();
				} else {
					ifclick = false;
					// 判断resultStatus 为非"9000"则代表可能支付失败
					// "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(GameManagerActivity.this, "支付结果确认中",
								Toast.LENGTH_SHORT).show();
					} else {
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						Toast.makeText(GameManagerActivity.this, "支付失败",
								Toast.LENGTH_SHORT).show();
					}
				}
				break;
			}

			}
		};
	};
	final Handler handler = new Handler() { // handle
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				String sign = (String) msg.obj;
				/**
				 * 完整的符合支付宝参数规范的订单信息
				 */
				final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
						+ getSignType();

				Runnable payRunnable = new Runnable() {

					@Override
					public void run() {
						// 构造PayTask 对象
						PayTask alipay = new PayTask(GameManagerActivity.this);
						// 调用支付接口，获取支付结果
						String result = alipay.pay(payInfo, true);
						Message msg = new Message();
						msg.what = SDK_PAY_FLAG;
						msg.obj = result;
						mHandler.sendMessage(msg);
					}
				};

				// 必须异步调用
				Thread payThread = new Thread(payRunnable);
				payThread.start();
				break;
			}

			super.handleMessage(msg);
		}
	};

	private void pay(String orderInfo) {
		// TODO Auto-generated method stub
		DefaultHttpClient client = new DefaultHttpClient();
		String uri = "http://" + Variable.address
				+ "/terminal/payment/getAlipaySign";
		HttpPost httpPost = new HttpPost(uri);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			parameters.add(new BasicNameValuePair("orderInfo", orderInfo));
			// 创建传递参数封装 实体对象
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
					"UTF-8");// 设置传递参数的编码
			httpPost.setEntity(entity);
			if (!Variable.JSESSIONID.equals("")) {
				httpPost.setHeader("Cookie", "JSESSIONID="
						+ Variable.JSESSIONID);
			}
			// 3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
			HttpResponse response = client.execute(httpPost); // HttpUriRequest的后代对象
																// //在浏览器中敲一下回车
			if (response.getStatusLine().getStatusCode() == 200) {
				CookieStore mCookieStore = client.getCookieStore();
				List<Cookie> cookies = mCookieStore.getCookies();
				for (int i = 0; i < cookies.size(); i++) {
					// 这里是读取Cookie['PHPSESSID']的值存在静态变量中，保证每次都是同一个值
					if ("JSESSIONID".equals(cookies.get(i).getName())) {
						Variable.JSESSIONID = cookies.get(i).getValue();
						break;
					}
				}
				InputStream is = response.getEntity().getContent();
				int b = 0;
				StringBuffer sb = new StringBuffer();
				while ((b = is.read()) != -1) {
					sb.append((char) b);
				}

				String result = sb.toString();
				Message message = new Message();
				message.what = 1;
				message.obj = result;
				handler.sendMessage(message);

			} else {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						ToastUtil.show(GameManagerActivity.this, "网络异常");
					}
				});
			}
		} catch (Exception e) {
			runOnUiThread(new Runnable() {
				public void run() {
					ToastUtil.show(GameManagerActivity.this, "网络异常");
				}
			});
			e.printStackTrace();
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}

	}

	private void loginByHttpClientSys() {
		DefaultHttpClient client = new DefaultHttpClient();
		String uri = "http://" + Variable.address + "/terminal/systime";
		HttpPost httpPost = new HttpPost(uri);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			// 创建传递参数封装 实体对象
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
					"UTF-8");// 设置传递参数的编码
			// 把实体对象存入到httpPost对象中
			httpPost.setEntity(entity);

			HttpResponse response = client.execute(httpPost); // HttpUriRequest的后代对象
			if (response.getStatusLine().getStatusCode() == 200) {

				HttpEntity entity1 = response.getEntity();
				String result = EntityUtils.toString(response.getEntity(),
						"UTF-8");
				// String result = StreamTools.streamToString(is);

				int i = Integer.parseInt(result);
				String ii = Variable.getStrTime(result);
				int j = Integer.parseInt(begintime);
				int k = i - j;
				if (k >= 0) {
					if (!startorstop) {
						if (ifclick) {
							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									ToastUtil.show(GameManagerActivity.this,
											"等待服务器响应，请稍等");
								}
							});

						} else {
							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									AlertDialog isExit = new AlertDialog.Builder(
											GameManagerActivity.this).create();
									// 设置对话框标题
									// 设置对话框消息
									isExit.setMessage("确定要开始比赛吗?");
									// 添加选择按钮并注册监听
									isExit.setButton("确定", listener5);
									isExit.setButton2("取消", listener5);
									// 显示对话框
									isExit.show();

								}
							});
						}

					} else {

						iftype = "2";
						loginByHttpClientGet();

						// post 时间给服务器
					}
					// post 时间给服务器
				} else {
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							AlertDialog isExit = new AlertDialog.Builder(
									GameManagerActivity.this).create();
							// 设置对话框标题
							isExit.setTitle("还没有到比赛开始时间");
							// 设置对话框消息
							// 添加选择按钮并注册监听
							isExit.setButton("确定", listener3);
							// 显示对话框
							isExit.show();

						}
					});

				}
			}

		}

		catch (Exception e) {
			e.printStackTrace();
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					ToastUtil.show(GameManagerActivity.this, "网络超时，请检查网络");
				}
			});
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}

	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// 创建退出对话框
			if (sp.getBoolean("eventinfo", false)) {
				sp.edit().putBoolean("eventinfo", false).commit();
				finish();
				return true;
			}
			startActivity(GameListActivity.class, R.anim.right_out,
					R.anim.left_in);
			finish();

		}

		return false;

	}
}
