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 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.util.MD5Util;
import com.example.mountaintravel.util.PhoneUtil;
import com.example.mountaintravel.util.ToastUtil;
import com.example.mountaintravel.variable.Variable;

import android.net.Uri;
import android.os.Bundle;
import android.os.Build.VERSION;
import android.provider.Settings;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Camera;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class BindActivity extends BaseActivity implements OnClickListener {
	private final static int SCANNIN_GREQUEST_CODE = 1;
	private ImageView bind_iv;
	private String text = null;
	private Button bind_button1;
	private EditText bind_editText1;
	private TextView bind_editText2;
	private String code = "";
	private TextView bind_tv;
	private static final String TAG = "BindActivity";
	private SharedPreferences sp;
	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 = "null";
	private JSONObject json = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_bind);
		sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
		findView();
		if (sp.getString("adddevice", "").equals("addBracelet")) {
			initTitleBar("绑定智能手表");
			bind_editText2.setText("(序列号见智能手表背面)");
			sp.edit().putString("adddevice", "adddevice").commit();
		} else {
			initTitleBar("绑定登山设备");
			bind_editText2.setText("(序列号见登山卡背面)");
		}
	}

	private void findView() {
		// TODO Auto-generated method stub
		bind_iv = (ImageView) findViewById(R.id.bind_iv);
		bind_iv.setOnClickListener(this);
		bind_editText2 = (TextView) findViewById(R.id.bind_editText2);
		bind_button1 = (Button) findViewById(R.id.bind_button);
		bind_button1.setOnClickListener(this);
		bind_tv = (TextView) findViewById(R.id.bind_tv);
		bind_editText1 = (EditText) findViewById(R.id.bind_editText1);
		bind_editText1
				.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
		bind_editText1.setInputType(InputType.TYPE_CLASS_NUMBER);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case SCANNIN_GREQUEST_CODE:
			if (resultCode == RESULT_OK) {
				Bundle bundle = data.getExtras();
				text = bundle.getString("result");
				bind_editText1.setText(text);
				// 扫描二维码并Base64解码
				/*
				 * byte[] outMsgBytes; try { outMsgBytes =
				 * text.getBytes("UTF-8"); byte[] contentBytes =
				 * Base64.decodeBase64(outMsgBytes); String aString=new
				 * String(contentBytes, "UTF-8");
				 * bind_editText1.setText(aString); } catch
				 * (UnsupportedEncodingException e) { // TODO Auto-generated
				 * catch block e.printStackTrace(); }
				 */

			}
			break;
		case 10:
			if (PhoneUtil.isCameraCanUse()) {
				Intent intent = new Intent();
				intent.setClass(this, MipcaActivityCapture.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivityForResult(intent, SCANNIN_GREQUEST_CODE);
			}
			break;
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.bind_iv:
			if (!PhoneUtil.isCameraCanUse()) {
				if (VERSION.SDK_INT >= 23) {
					AlertDialog isExit = new AlertDialog.Builder(this).create();
					// 设置对话框消息
					isExit.setMessage("没有摄像头权限,去打开权限?");
					// 添加选择按钮并注册监听
					isExit.setButton("确定", listener);
					isExit.setButton2("取消", listener);
					// 显示对话框
					isExit.show();
				} else {
					ToastUtil.show(BindActivity.this, "无摄像头权限");
				}
			} else {
				Intent intent = new Intent();
				intent.setClass(this, MipcaActivityCapture.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivityForResult(intent, SCANNIN_GREQUEST_CODE);
			}
			break;
		case R.id.bind_button:
			if (TextUtils.isEmpty(bind_editText1.getText().toString().trim())) {
				if (bind_editText2.getText().toString().trim()
						.equals("(序列号见登山卡背面)")) {
					bind_tv.setVisibility(View.VISIBLE);
					bind_tv.setText("卡号不能为空");
					return;
				} else {
					bind_tv.setVisibility(View.VISIBLE);
					bind_tv.setText("手表不能为空");
					return;
				}

			}
			new Thread(new Runnable() {

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

					if (bind_editText2.getText().toString().trim()
							.equals("(序列号见登山卡背面)")) {
						loginByHttpClientGet();
					} else {
						addBracelet();
					}
				}
			}).start();
			break;

		}

	}

	DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
		@SuppressLint("NewApi")
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
				Uri packageURI = Uri.parse("package:" + "com.smart.gtstrvl");
				Intent intent = new Intent(
						Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
						packageURI);
				startActivityForResult(intent, 10);
				break;
			case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框

				break;
			}
		}
	};

	private void addBracelet() {
		// TODO Auto-generated method stub
		String braceletSn = bind_editText1.getText().toString().trim();
		DefaultHttpClient client = new DefaultHttpClient();
		String uri = "http://" + Variable.address + "/terminal/bindBracelet";
		HttpPost httpPost = new HttpPost(uri);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			parameters.add(new BasicNameValuePair("braceletSn", braceletSn));
			parameters.add(new BasicNameValuePair("user_id", sp.getString(
					"userid", "")));
			parameters.add(new BasicNameValuePair("user_name", sp.getString(
					"nick_name", "")));
			// 创建传递参数封装 实体对象
			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);
				code = json.getString("code");
				if (code.equals("4015")) {
					login(sp.getString("userName", ""),
							sp.getString("userPass", ""));
				}
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub

						if (code.equals("1006")) {
							ToastUtil.show(BindActivity.this, "绑定成功");
							/*
							 * if (sp.getBoolean("binddevice", false)) {
							 * 
							 * }
							 */
							sp.edit()
									.putString(
											"braceletSn",
											bind_editText1.getText().toString()
													.trim()).commit();
							Intent intent = new Intent(BindActivity.this,
									DeviceManaActivity.class);
							setResult(RESULT_OK, intent);
							Intent intent2 = new Intent(BindActivity.this,
									VirtualRoadActivity.class);
							setResult(RESULT_OK, intent);
							Intent intent3 = new Intent(BindActivity.this,
									MainActivity.class);
							setResult(RESULT_OK, intent);
							Intent intent4 = new Intent(BindActivity.this,
									EventInfoActivity.class);
							setResult(RESULT_OK, intent);
							finish();
							return;
						}
						if (code.equals("4001")) {
							bind_tv.setVisibility(View.VISIBLE);
							bind_tv.setText("此手表不存在");
							return;
						}
						if (code.equals("6001")) {
							bind_tv.setVisibility(View.VISIBLE);
							bind_tv.setText("无效的手表号");
							return;
						}
						if (code.equals("6003")) {
							bind_tv.setVisibility(View.VISIBLE);
							bind_tv.setText("此手表已绑定过了");
							return;
						}
						if (code.equals("6004")) {
							bind_tv.setVisibility(View.VISIBLE);
							bind_tv.setText("已经绑定过手表了");
							return;
						}
						if (code.equals("6005")) {
							bind_tv.setVisibility(View.VISIBLE);
							bind_tv.setText("该手表未绑定赛事");
							return;
						} else {
							if (!code.equals("4015")) {
								bind_tv.setVisibility(View.VISIBLE);
								bind_tv.setText("绑定失败");
								return;
							}
						}
					}
				});
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			runOnUiThread(new Runnable() {

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

					bind_tv.setVisibility(View.VISIBLE);
					bind_tv.setText("绑定失败");

				}
			});
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}

	}

	private void loginByHttpClientGet() {
		// TODO Auto-generated method stub
		String device_sn = bind_editText1.getText().toString().trim();
		DefaultHttpClient client = new DefaultHttpClient();
		String uri = "http://" + Variable.address + "/terminal/binddevice";
		HttpPost httpPost = new HttpPost(uri);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			parameters.add(new BasicNameValuePair("device_type", "1"));
			parameters.add(new BasicNameValuePair("user_id", sp.getString(
					"userid", "")));
			parameters.add(new BasicNameValuePair("user_name", sp.getString(
					"nick_name", "")));
			parameters.add(new BasicNameValuePair("device_sn", device_sn));
			// 创建传递参数封装 实体对象
			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);
				code = json.getString("code");
				if (code.equals("4015")) {
					login(sp.getString("userName", ""),
							sp.getString("userPass", ""));
				}
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						if (code.equals("1006")) {
							ToastUtil.show(BindActivity.this, "绑定成功");
							/*
							 * if (sp.getBoolean("binddevice", false)) {
							 * 
							 * }
							 */
							sp.edit().putBoolean("bind", true).commit();
							Intent intent = new Intent(BindActivity.this,
									DeviceManaActivity.class);
							setResult(RESULT_OK, intent);
							Intent intent2 = new Intent(BindActivity.this,
									VirtualRoadActivity.class);
							setResult(RESULT_OK, intent);
							Intent intent3 = new Intent(BindActivity.this,
									MainActivity.class);
							setResult(RESULT_OK, intent);
							Intent intent4 = new Intent(BindActivity.this,
									EventInfoActivity.class);
							setResult(RESULT_OK, intent);
							finish();
							return;
						}
						if (code.equals("4001")) {
							bind_tv.setVisibility(View.VISIBLE);
							bind_tv.setText("此卡不存在");
							return;
						}
						if (code.equals("6001")) {
							bind_tv.setVisibility(View.VISIBLE);
							bind_tv.setText("无效的卡号");
							return;
						}
						if (code.equals("6003")) {
							bind_tv.setVisibility(View.VISIBLE);
							bind_tv.setText("此卡已绑定过了");
							return;
						}
						if (code.equals("6004")) {
							bind_tv.setVisibility(View.VISIBLE);
							bind_tv.setText("已经绑定过卡了");
							return;
						} else {
							if (!code.equals("4015")) {
								bind_tv.setVisibility(View.VISIBLE);
								bind_tv.setText("绑定失败");
								return;
							}
						}
					}
				});
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			runOnUiThread(new Runnable() {

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

					bind_tv.setVisibility(View.VISIBLE);
					bind_tv.setText("绑定失败");

				}
			});
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}

	}

	private void login(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++) {
					// 这里是读取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();
				json = new JSONObject(result);
				status = json.getString("status");

				if (status.equals("9002")) {
					if (bind_editText2.getText().toString().trim()
							.equals("(序列号见登山卡背面)")) {
						loginByHttpClientGet();
					} else {
						addBracelet();
					}
				} else {
					runOnUiThread(new Runnable() {
						public void run() {
							ToastUtil.show(BindActivity.this, "获取信息失败请重新登录");
						}
					});
				}

			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					ToastUtil.show(BindActivity.this, "获取信息失败请重新登录");
				}
			});
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}

	}

}
