package com.smart.gtstrvl;

import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

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.json.JSONObject;

import com.example.mountaintravel.base.BaseActivity;
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.StringUtils;
import com.example.mountaintravel.util.ToastUtil;
import com.example.mountaintravel.variable.Variable;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import android.os.Bundle;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends BaseActivity implements OnClickListener {

	private EditText editTextphone;
	private EditText editTextpass;
	private TextView login_tvfindpass;
	private TextView login_register;
	private static final String TAG = "LoginActivity";
	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 URL url = null;
	private String status = "";
	private JSONObject json = null;
	private SharedPreferences sp;
	TextView login_tverr;
	TextView login_tverr2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		initTitleBar("登录");
		sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
		editTextphone = (EditText) findViewById(R.id.editTextphone);
		editTextpass = (EditText) findViewById(R.id.editTextpass);
		login_tverr = (TextView) findViewById(R.id.login_tverr);
		login_tverr2 = (TextView) findViewById(R.id.login_tverr2);
		editTextphone.requestFocus();
		login_register = (TextView) findViewById(R.id.login_register);
		login_register.setOnClickListener(this);
		login_tvfindpass = (TextView) findViewById(R.id.login_tvfindpass);
		login_tvfindpass.setOnClickListener(this);
	}

	public void click(View v) {
		final String userName = editTextphone.getText().toString().trim();
		final String userPass = editTextpass.getText().toString().trim();
		if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(userPass)) {
			login_tverr2.setVisibility(View.VISIBLE);
			login_tverr2.setText("  用户名或密码不能为空");
			return;
		} else {
			login_tverr2.setVisibility(View.GONE);
			new Thread(new Runnable() {
				@Override
				public void run() {
					// 调用：loginByHttpClientGet(userName, userPass);
					loginByHttpClientGet(userName, userPass);// 测试
				}

			}).start();
		}

	}

	private void loginByHttpClientGet(final String userName,
			final String userPass) {
		// TODO Auto-generated method stub
		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", userName));
			parameters.add(new BasicNameValuePair("login_type", "2"));
			parameters.add(new BasicNameValuePair("pwds", 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++) {
					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();
				System.out.println(result + "登录");
				json = new JSONObject(result);
				status = json.getString("status");
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						if (status.equals("9002")) {
							sp.edit().putBoolean("isloginsuccess", true)
									.commit();
							sp.edit().putString("userName", userName).commit();
							sp.edit().putString("userPass", userPass).commit();
							try {
								JSONObject jsondata = json
										.getJSONObject("data");
								String headImageUrl = jsondata
										.getString("headImgUrl");
								String braceletSn = StringUtils
										.toString(jsondata
												.getString("braceletSn"));
								sp.edit().putString("braceletSn", braceletSn)
										.commit();
								sp.edit()
										.putString(
												"url",
												"http://" + Variable.address
														+ headImageUrl)
										.commit();
								sp.edit()
										.putString("userid",
												json.getString("userid"))
										.commit();
								sp.edit()
										.putString("sesskey",
												json.getString("sesskey"))
										.commit();
								Map<String, Object> map = AesTerminalUtil
										.gtsApiAesDecryptToMap(json
												.getString("sesskey"));
								String real_name = (String) map
										.get("real_name");
								sp.edit().putString("real_name", real_name)
										.commit();
								sp.edit()
										.putString("nick_name",
												(String) map.get("nick_name"))
										.commit();
								sp.edit()
										.putString("increased",
												(String) map.get("increased"))
										.commit();
								sp.edit()
										.putString("weight",
												(String) map.get("weight"))
										.commit();
								String aa = (String) map.get("device_sn");
								String sex1 = (String) map.get("sex");
								if (!isWorked("com.example.mountaintravel.service.MyGPSservice")) {
									Intent startIntent = new Intent(
											LoginActivity.this,
											MyGPSservice.class);
									startService(startIntent);
								}
								if (sex1.equals("0")) {
									sp.edit().putString("sex", "女").commit();
								} else {
									sp.edit().putString("sex", "男").commit();
								}
								if (!sp.getString("toapplyid", "").equals("")) {
									sp.edit().putString("eventId", "").commit();
									startActivity(EventInfoActivity.class);
									finish();
									return;
								}
								if (!sp.getString("eventId", "").equals("")) {
									sp.edit().putString("toapplyid", "")
											.commit();
									startActivity(EventInfoActivity.class);
									finish();
									return;
								}
								if (sp.getBoolean("comment", false)) {
									finish();
									return;
								} else {

									startActivity(MainActivity.class);
								}

							} catch (Exception e) {
								e.printStackTrace();
								runOnUiThread(new Runnable() {
									public void run() {
										login_tverr2
												.setVisibility(View.VISIBLE);
										login_tverr2.setText("  登录异常");
									}
								});
							}

						} else {
							runOnUiThread(new Runnable() {
								public void run() {
									login_tverr2.setVisibility(View.VISIBLE);
									login_tverr2.setText("  用户名或密码不正确");
								}
							});
						}
					}
				});
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					ToastUtil.show(LoginActivity.this, "登录异常");
				}
			});
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}

	}

	private boolean isWorked(String className) {
		ActivityManager myManager = (ActivityManager) LoginActivity.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;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		/*
		 * case R.id.login_imageView1: //onClickLogin(); break;
		 */
		case R.id.login_register:
			if (sp.getBoolean("comment", false)) {
				Intent intent = new Intent(this, PhoneRegisterActivity.class);
				startActivityForResult(intent, 1);
				return;
			}
			startActivity(PhoneRegisterActivity.class);
			break;
		case R.id.login_tvfindpass:
			startActivity(Findpass1Activity.class, R.anim.left_out,
					R.anim.right_in);
			break;
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		sp.edit().putBoolean("comment", false).commit();
		sp.edit().putString("toapplyid", "").commit();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 1:
			if (!sp.getBoolean("comment", false)) {
				finish();
				return;
			}
			break;

		}
	}
	/*
	 * protected void onActivityResult(int requestCode, int resultCode, Intent
	 * data) { super.onActivityResult(requestCode, resultCode, data);
	 *//** 使用SSO授权必须添加如下代码 */
	/*
	 * UMSsoHandler ssoHandler =
	 * UmengShareUtils.mController.getConfig().getSsoHandler(requestCode) ;
	 * if(ssoHandler != null){ ssoHandler.authorizeCallBack(requestCode,
	 * resultCode, data); } }
	 */
}
