package com.smart.gtstrvl;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
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.params.CoreConnectionPNames;

import com.example.mountaintravel.base.BaseActivity;
import com.example.mountaintravel.util.BitmapUtil;
import com.example.mountaintravel.util.PhoneUtil;
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.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.NetworkInfo.State;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.provider.MediaStore;
import android.provider.Settings;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;

public class ChangeHeadActivity extends BaseActivity {
	private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
	private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
	private static final int PHOTO_REQUEST_CUT = 3;// 结果
	private static final String TAG = "ChangeHeadActivity";
	private ImageView mFace;
	private Bitmap bitmap;
	public static Bitmap bitmap2;
	private Button button;
	private String result = "1";
	private SharedPreferences sp;
	/* 头像名称 */
	private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
	private File tempFile;
	private DisplayImageOptions options;
	protected ImageLoader imageLoader;
	private boolean ifupload = false;
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_change_head);
		initTitleBar("我的头像");
		sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
		mFace = (ImageView) findViewById(R.id.changehead_iv_image);
		if (!sp.getString("url", "").contains("face")) {

			imageLoader = ImageLoader.getInstance();
			imageLoader.init(ImageLoaderConfiguration
					.createDefault(ChangeHeadActivity.this));
			options = new DisplayImageOptions.Builder()
					.showStubImage(R.drawable.head)
					.showImageForEmptyUri(R.drawable.head)
					.showImageOnFail(R.drawable.head).cacheInMemory(true)
					.displayer(new RoundedBitmapDisplayer(100))
					.cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565)
					.build();
			imageLoader.loadImage(sp.getString("url", ""),
					new SimpleImageLoadingListener() {
						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
							super.onLoadingComplete(imageUri, view, loadedImage);
							Bitmap headBitmap = BitmapUtil
									.toRoundBitmap(loadedImage);
							mFace.setImageBitmap(headBitmap);
							mFace.setScaleType(ScaleType.FIT_XY);
						}
					});
		} else {
			mFace.setBackground(getResources().getDrawable(R.drawable.head));
		}
	}

	/*
	 * 上传图片
	 */
	public void upload() {
		ifupload = true;
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				loginByHttpClientGet();
			}
		}).start();

	}

	/*
	 * 从相册获取
	 */
	public void gallery(View view) {
		// 激活系统图库，选择一张图片
		// PackageManager pkm = getPackageManager();
		// has_permission = (PackageManager.PERMISSION_GRANTED == pkm
		// .checkPermission("android.permission.WRITE_EXTERNAL_STORAGE",
		// "com.smart.gtstrvl"));
		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(ChangeHeadActivity.this, "无摄像头权限");
			}
		} else {
			picture();
		}
		return;
	}

	private void picture() {
		/*
		 * ConnectivityManager cwjManager = (ConnectivityManager)
		 * getSystemService(this.CONNECTIVITY_SERVICE); State mobile =
		 * cwjManager.getNetworkInfo(
		 * ConnectivityManager.TYPE_MOBILE).getState(); State wifi =
		 * cwjManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) .getState();
		 * if (mobile == State.CONNECTED || mobile == State.CONNECTING || wifi
		 * == State.CONNECTED || wifi == State.CONNECTING) {
		 */
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType("image/*");
		startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
		/*
		 * } else { ToastUtil.show(ChangeHeadActivity.this, "当前网络不可用"); }
		 */
	}

	/*
	 * 从相机获取
	 */
	public void camera(View view) {
		// PackageManager pkm = getPackageManager();
		// has_permission = (PackageManager.PERMISSION_GRANTED == pkm
		// .checkPermission("android.permission.CAMERA",
		// "com.smart.gtstrvl"));
		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(ChangeHeadActivity.this, "无摄像头权限");
			}
		} else {
			takepicture();
		}

	}

	private void takepicture() {
		/*
		 * ConnectivityManager cwjManager = (ConnectivityManager)
		 * getSystemService(this.CONNECTIVITY_SERVICE); State mobile =
		 * cwjManager.getNetworkInfo(
		 * ConnectivityManager.TYPE_MOBILE).getState(); State wifi =
		 * cwjManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) .getState();
		 * if (mobile == State.CONNECTED || mobile == State.CONNECTING || wifi
		 * == State.CONNECTED || wifi == State.CONNECTING) {
		 */
		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
		// 判断存储卡是否可以用，可用进行存储
		if (hasSdcard()) {
			intent.putExtra(MediaStore.EXTRA_OUTPUT,
					Uri.fromFile(new File(Environment
							.getExternalStorageDirectory(), PHOTO_FILE_NAME)));
		}
		startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
		/*
		 * } else { ToastUtil.show(ChangeHeadActivity.this, "当前网络不可用"); }
		 */
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == PHOTO_REQUEST_GALLERY) {
			if (data != null) {
				// 得到图片的全路径
				Uri uri = data.getData();

				crop(uri);
			}
		} else if (requestCode == 10) {
			if (PhoneUtil.isCameraCanUse()) {
				picture();
			}
		} else if (requestCode == 11) {
			if (PhoneUtil.isCameraCanUse()) {
				takepicture();
			}

		} else if (requestCode == PHOTO_REQUEST_CAMERA) {
			if (hasSdcard()) {
				tempFile = new File(Environment.getExternalStorageDirectory(),
						PHOTO_FILE_NAME);
				crop(Uri.fromFile(tempFile));
			} else {
				Toast.makeText(ChangeHeadActivity.this, "未找到存储卡，无法存储照片！", 0)
						.show();
			}

		} else if (requestCode == PHOTO_REQUEST_CUT) {
			try {
				bitmap = data.getParcelableExtra("data");
				bitmap2 = BitmapUtil.toRoundBitmap(bitmap);
			} catch (Exception e) {
				e.printStackTrace();
			}
			upload();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 剪切图片
	 * 
	 * @function:
	 * @author:Jerry
	 * @date:2013-12-30
	 * @param uri
	 */
	private void crop(Uri uri) {
		// 裁剪图片意图
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// 裁剪框的比例，1：1
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// 裁剪后输出图片的尺寸大小
		intent.putExtra("outputX", 250);
		intent.putExtra("outputY", 250);
		// 图片格式
		intent.putExtra("outputFormat", "JPEG");
		intent.putExtra("noFaceDetection", true);// 取消人脸识别
		intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
		startActivityForResult(intent, PHOTO_REQUEST_CUT);
	}

	public void initTitleBar(String text) {
		TitleBarView v = (TitleBarView) findViewById(R.id.titleBarView1);
		if (v != null) {
			v.initTitleBar(R.drawable.zuoback, -1, text,
					new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							if (v.getId() == R.id.left_icon) {
								// 上传图片完成
								if (result == null) {
									finish();
									return;
								} else if (result.equals("1") && ifupload) {
									return;
								} else if (!result.equals("999")
										&& result != null && !result.equals("")
										&& !result.equals("1"))
									startActivity(MainActivity.class);
								else {
									finish();
								}

							}

						}
					});
		}
	}

	private boolean hasSdcard() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();

	}

	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;
			}
		}
	};

	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// 创建退出对话框

			if (result == null) {
				finish();
				Toast.makeText(ChangeHeadActivity.this, "头像上传失败!", 0).show();
				return true;
			} else if (result.equals("1") && ifupload) {
				return true;
			} else if (!result.equals("999") && result != null
					&& !result.equals("") && !result.equals("1"))
				startActivity(MainActivity.class);
			else {
				finish();
			}
		}
		return false;
	}

	private void loginByHttpClientGet() {
		// TODO Auto-generated method stub

		DefaultHttpClient client = new DefaultHttpClient();
		client.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);// 连接时间
		client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 3000);// 数据传输时间
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			bitmap2.compress(Bitmap.CompressFormat.JPEG, 100, out);
			out.flush();
			out.close();
			byte[] buffer = out.toByteArray();
			// byte[] encode = Base64.encode(buffer, Base64.DEFAULT);
			byte[] encode = Base64.encodeBase64(buffer);
			String photo = new String(encode);
			String sesskey = sp.getString("sesskey", "");
			String url = "http://" + Variable.address
					+ "/terminal/user/file/base64_upload_image";
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			parameters.add(new BasicNameValuePair("photo", photo));
			parameters.add(new BasicNameValuePair("userId", sp.getString(
					"userid", "")));
			parameters.add(new BasicNameValuePair("sesskey", sesskey));
			// 创建传递参数封装 实体对象
			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();
				int b = 0;
				StringBuffer sb = new StringBuffer();
				while ((b = is.read()) != -1) {
					sb.append((char) b);
				}
				result = sb.toString();
				if (result.equals("999")) {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							// TODO Auto-generated method stub
							Toast.makeText(ChangeHeadActivity.this, "头像上传失败!",
									0).show();
						}
					});

				} else {
					runOnUiThread(new Runnable() {
						public void run() {
							mFace.setImageBitmap(bitmap2);
						}
					});
					sp.edit()
							.putString("url",
									"http://" + Variable.address + result)
							.commit();

				}
			} else {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						ifupload = false;
						Toast.makeText(ChangeHeadActivity.this, "头像上传失败!", 0)
								.show();
					}
				});
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					ifupload = false;
					Toast.makeText(ChangeHeadActivity.this, "头像上传失败!", 0)
							.show();
				}
			});
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}

	}

}
