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.StreamTools;
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.content.Intent;
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.TextView;
import android.widget.Toast;

public class Findpass1Activity extends BaseActivity implements OnClickListener {
	private EditText find_editTextphone;
	private EditText find_editTextcode;
	private TextView find_getcode;
	private Button find_button;
	private int second;
	private SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
	private String time = format.format(new Date());
	private String type = "android";
	private String key = ".5Xf_01KXd352s177Jx3wxXc074poII";
	private String sign = MD5Util.MD5(time + type + key);
	private String timer;
	private String code = "";
	private TextView find_tverr;
	private TextView find_tverrtwo;
	private boolean ifphone = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_findpass1);
		initTitleBar("找回密码");
		find_editTextphone = (EditText) findViewById(R.id.find_editTextphone);
		find_editTextcode = (EditText) findViewById(R.id.find_editTextcode);
		find_getcode = (TextView) findViewById(R.id.find_getcode);
		find_button = (Button) findViewById(R.id.find_button);
		find_tverr = (TextView) findViewById(R.id.find_tverr);
		find_tverrtwo = (TextView) findViewById(R.id.find_tverrtwo);
		find_button.setOnClickListener(this);
		find_getcode.setOnClickListener(this);
		find_editTextcode
				.setOnFocusChangeListener(new View.OnFocusChangeListener() {

					@Override
					public void onFocusChange(View v, boolean hasFocus) {
						if (hasFocus) {// 获得焦点
							ifregister_editText1();

						} else {// 失去焦点

						}
					}

				});

	}

	private void ifregister_editText1() {
		if (TextUtils.isEmpty(find_editTextphone.getText().toString().trim())) {
			find_tverr.setVisibility(View.VISIBLE);
			find_tverr.setText("  号码不能为空");
			return;
		}
		if (find_editTextphone.getText().toString().length() != 11) {
			find_tverr.setVisibility(View.VISIBLE);
			find_tverr.setText("  号码长度不合法");
			return;
			// 有一个接口判断是否已注册过if
		}
		ifphone = PhoneUtil.isMobileNO(find_editTextphone.getText().toString()
				.trim());
		if (!ifphone) {
			find_tverr.setVisibility(View.VISIBLE);
			find_tverr.setText("  号码不存在");
			return;
		}
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				loginByHttpClientGet();
			}
		}).start();
		find_tverr.setText("123");
		find_tverr.setVisibility(View.GONE);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.findpass1, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.find_getcode:
			if (TextUtils.isEmpty(find_editTextphone.getText().toString()
					.trim())) {
				find_tverr.setVisibility(View.VISIBLE);
				find_tverr.setText("  号码不能为空");
				return;
			}
			if (find_editTextphone.getText().toString().length() != 11) {
				find_tverr.setVisibility(View.VISIBLE);
				find_tverr.setText("  号码长度不合法");
				return;
				// 有一个接口判断是否已注册过if
			}
			ifphone = PhoneUtil.isMobileNO(find_editTextphone.getText()
					.toString().trim());
			if (!ifphone) {
				find_tverr.setVisibility(View.VISIBLE);
				find_tverr.setText("  号码不存在");
				return;
			}
			find_tverr.setText("123");
			find_tverr.setVisibility(View.GONE);
			new Thread(new Runnable() {

				public void run() {
					// TODO Auto-generated method stub
					find_getcode.setOnClickListener(null);
					if (!find_tverrtwo.getText().toString().equals("  该手机号未注册")) {
						lowgetcode();
					}

				}
			}).start();
			second = 60;
			new MyThread().start();

			break;

		case R.id.find_button:
			if (TextUtils.isEmpty(find_editTextphone.getText().toString()
					.trim())) {
				find_tverr.setVisibility(View.VISIBLE);
				find_tverr.setText("  号码不能为空");
				return;
			}
			if (find_editTextphone.getText().toString().length() != 11) {
				find_tverr.setVisibility(View.VISIBLE);
				find_tverr.setText("  号码有误，请重新输入");
				return;
			}
			if (TextUtils
					.isEmpty(find_editTextcode.getText().toString().trim())) {
				find_tverrtwo.setVisibility(View.VISIBLE);
				find_tverrtwo.setText("  验证码不能为空");
				return;
			}
			if (!find_editTextcode.getText().toString().trim().equals(code)) {
				// ToastUtil.show(this, "  验证码有误，请重新输入");
				find_tverrtwo.setVisibility(View.VISIBLE);
				find_tverrtwo.setText("  验证码有误，请重新输入");
				return;
			}
			new Thread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					loginByHttpClientGet();
				}
			}).start();

			if (find_editTextcode.getText().toString().trim().equals(code)) {
				Intent intent = new Intent(Findpass1Activity.this,
						Findpass2Activity.class);
				intent.putExtra("name", find_editTextphone.getText().toString()
						.trim());
				startActivity(intent);
				overridePendingTransition(R.anim.left_out, R.anim.right_in);
				finish();
			}

			break;
		}

	}

	final Handler handler = new Handler() { // handle
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				String timerbegin = msg.obj.toString();
				find_getcode.setText(timerbegin);
				find_getcode.setOnClickListener(null);
				if (second == 0) {
					find_getcode.setOnClickListener(Findpass1Activity.this);
					find_getcode.setText("  获取验证码");
				}

			}
			super.handleMessage(msg);
		}
	};

	public class MyThread extends Thread {
		public void run() {
			while (second > 0) {
				try {
					timer = second + "秒";

					MyThread.sleep(1000);

					second -= 1;
					Message message = new Message();
					message.obj = timer;
					message.what = 1;
					handler.sendMessage(message);
				}

				catch (Exception e) {
				}
			}
		}
	}
	private void lowgetcode() {
		// TODO Auto-generated method stub
		String phone = find_editTextphone.getText().toString().trim();
		DefaultHttpClient client = new DefaultHttpClient();
		// String uri = "http://192.168.20.80:5050/gts/terminal/login";
		String uri = "http://" + Variable.address + "/terminal/smsapi";
		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("phone", phone));
			// 创建传递参数封装 实体对象
			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) {
				InputStream is = response.getEntity().getContent();
				String result = StreamTools.streamToString(is);
				JSONObject json = new JSONObject(result);
				JSONObject msgjson = json.getJSONObject("data");
				code = msgjson.getString("verifycode");
			}
		} catch (Exception e) {
			e.printStackTrace();
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					ToastUtil.show(Findpass1Activity.this, "获取异常");
				}
			});
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}
	}
	private void loginByHttpClientGet() {
		// TODO Auto-generated method stub
		String phone = find_editTextphone.getText().toString().trim();
		DefaultHttpClient client = new DefaultHttpClient();
		String uri = "http://" + Variable.address + "/terminal/phoneapi";
		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("phone", 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();
				System.out.println(result);
				JSONObject json = new JSONObject(result);
				String code = json.getString("code");
				if (!code.equals("4025")) {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							find_tverrtwo.setVisibility(View.VISIBLE);
							find_tverrtwo.setText("  该手机号未注册");
						}
					});
				} else {
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							find_tverrtwo.setVisibility(View.GONE);

						}
					});

				}

			}

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

	}
}
