package com.tagmae.tsgame_erwang;


import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

import com.jx.jyhd.R;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

/**
 * 调用手机拍照，将拍照的图片放在指定文件夹中，注意AndroidManifest.xml中添加权限
 */
public class Main extends Activity {
	// 界面控件
	private Button btn;
	private ImageView img;

	// 对象
	Uri originalUri;// 获取用户选择图片的Uri
	Bitmap bm = null;
	Handler h = new Handler();

	// 变量
	/* 用来标识请求照相功能的activity */
	private static final int CAMERA_WITH_DATA = 3023;
	/* 用来标识请求gallery的activity */
	private static final int PHOTO_PICKED_WITH_DATA = 3021;
	/* 拍照的照片存储位置 */
	private static final File PHOTO_DIR = new File(
			Environment.getExternalStorageDirectory() + "/TestPhotoPic");
	private String picName = "";// 用户拍照后保存的图片名称
	String imgName = "";// 图片名称，类似于：20121212.jpg
	private String userSelectPath = "";

	
	@SuppressLint("InlinedApi") public String[] carpermission = new String[] {
			Manifest.permission.READ_EXTERNAL_STORAGE,
			Manifest.permission.CAMERA };
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		init();
		btn.setOnClickListener(new btn_OnClick());
	}

	// 按钮点击事件
	private class btn_OnClick implements OnClickListener {
		@Override
		public void onClick(View v) {
			String status = Environment.getExternalStorageState();
			// 判断是否有SD卡
			if (status.equals(Environment.MEDIA_MOUNTED)) {
				
				if (!hasPermission(carpermission)) {

					PermissionGen.needPermission(Main.this, 18,
							carpermission);
				} else {

					doTakePhoto();// 用户点击了从照相机获取

				}
			} else {
				Toast.makeText(Main.this, "没有SD卡", Toast.LENGTH_LONG).show();
			}
		}
	};
	@PermissionSuccess(requestCode = 18)
	public void succes() {
		doTakePhoto();// 用户点击了从照相机获取
	}
	/**
	 * 为子类提供一个检查权限的方法
	 * 
	 * @param permissions
	 * @return
	 */
	public boolean hasPermission(String... permissions) {
		for (String permission : permissions) {
			if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
				return false;

			}
		}
		return true;
	}
	/**
	 * 从照片文件夹中选择完图片后会调用这个方法
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK)
			return;
		switch (requestCode) {
		case PHOTO_PICKED_WITH_DATA: {// 调用(相册)Gallery返回的
			try {
				// 获得图片的uri
				originalUri = data.getData();
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
			// 获取路径---------------------------
			String[] proj = { MediaStore.Images.Media.DATA };
			// 好像是android多媒体数据库的封装接口，具体的看Android文档
			@SuppressWarnings("deprecation")
			Cursor cursor = managedQuery(originalUri, proj, null, null, null);
			// 按我个人理解 这个是获得用户选择的图片的索引值
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			// 将光标移至开头 ，这个很重要，不小心很容易引起越界
			cursor.moveToFirst();
			// 最后根据索引值获取图片路径
			userSelectPath = cursor.getString(column_index);
			if (userSelectPath.indexOf("/") != -1) {
				imgName = userSelectPath.substring(userSelectPath
						.lastIndexOf("/") + 1);
			}
			try {
				BitmapFactory.Options options = new BitmapFactory.Options();
				// 先设置为TRUE不加载到内存中，但可以得到宽和高
				options.inJustDecodeBounds = true;
				bm = BitmapFactory.decodeFile(userSelectPath, options); // 此时返回bm为空
				options.inJustDecodeBounds = false;
				// 计算缩放比
				int be = (int) (options.outHeight / (float) 200);
				if (be <= 0)
					be = 1;
				options.inSampleSize = be;
				// 这样就不会内存溢出了
				bm = BitmapFactory.decodeFile(userSelectPath, options);
				h.post(new Runnable() {
					@Override
					public void run() {
						img.setImageBitmap(bm);
					}
				});
			} catch (Exception e) {
				System.out
						.println("PHOTO_PICKED_WITH_DATA:e=" + e.getMessage());
			}
			break;
		}
		// 照相机程序返回的,再次调用图片剪辑程序去修剪图片
		case CAMERA_WITH_DATA: {
			try {
				userSelectPath = PHOTO_DIR + "/" + picName;
				bm=BitmapFactory.decodeFile(userSelectPath);
				img.setImageBitmap(bm);
				
				
//				imgName = picName;
//				BitmapFactory.Options options = new BitmapFactory.Options();
//				// 先设置为TRUE不加载到内存中，但可以得到宽和高
//				options.inJustDecodeBounds = true;
//				bm = BitmapFactory.decodeFile(userSelectPath, options); // 此时返回bm为空
//				options.inJustDecodeBounds = false;
//				// 计算缩放比
//				int be = (int) (options.outHeight / (float) 200);
//				if (be <= 0)
//					be = 1;
//				options.inSampleSize = be;
//				// 这样就不会内存溢出了
//				bm = BitmapFactory.decodeFile(userSelectPath, options);
//				
//				h.post(new Runnable() {
//					@Override
//					public void run() {
//						img.setImageBitmap(bm);
//					}
//				});
			} catch (Exception e) {
				System.out.println("CAMERA_WITH_DATA:e=" + e.getMessage());
			}
			break;
		}
		}
	}

	/**
	 * 拍照获取图片
	 * 
	 */
	protected void doTakePhoto() {
		try {
			PHOTO_DIR.mkdirs();// 创建照片的存储目录
			Intent imageCaptureIntent = new Intent(
					MediaStore.ACTION_IMAGE_CAPTURE);
			// 重新分解图片名称将-:的符号去掉
			picName = getPhotoFileName();
			picName = picName.replace("-", "");
			picName = picName.replace(":", "");
			File out = new File(PHOTO_DIR, picName);
			Uri uri = Uri.fromFile(out);
			imageCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
			imageCaptureIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
			startActivityForResult(imageCaptureIntent, CAMERA_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, "doTakePhoto：e=" + e, Toast.LENGTH_LONG)
					.show();
		}
	}

	/**
	 * 用当前时间给取得的图片命名
	 * 
	 */
	private String getPhotoFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
		return dateFormat.format(date) + ".jpg";
	}

	// 初始化界面控件
	private void init() {
		btn = (Button) findViewById(R.id.btn);
		img = (ImageView) findViewById(R.id.img);
	}
}