package cn.net.caoyao.cpzshandset.common.bitmap.crop;

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

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.net.caoyao.cpzshandset.R;
import cn.net.caoyao.cpzshandset.common.config.Config;
import cn.net.caoyao.cpzshandset.ui.weight.DialogUtils;

/**
 * 维修合同
 * 
 * @author zwj
 * @date 2015-11-18 下午12:33:20
 */
public class ContractImageActivity extends Activity {

	private final String tName = "图片";
//	public static final int requestCode = 987;
//	public static final int resultCode = 987;

	private static final int PICK_FROM_CAMERA = 1;// 图片选择相机
	private static final int CROP_FROM_CAMERA = 2;// 剪切从相机自带的相机中
	private static final int PICK_FROM_ALBUM = 3;// 图片选择相册
	private Uri singleUri;

	private ImageView ivShow;// 展示图片
	private ImageView ivLeft; // 左旋转
	private ImageView ivCrop;// 裁剪
	private ImageView ivRight;// 右旋转
	private ProgressDialog mProgressDialog;
	private String label;
	private boolean isRotate = false;// 是否旋转过，旋转后不压缩
	private boolean isCrop = false;// 是否裁剪过
	private Context context;
	private String pictureKey = "selectedImage";
	private boolean hasFinish = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		setContentView(R.layout.activity_contract_image);
		initView();
		setListen();
		initData();
	}

	protected void initData() {
		SimpleDateFormat sdfFileName = new SimpleDateFormat("yyyyMMddHHmmss");    
        String newfileName = sdfFileName.format(new Date());
		singleUri = PhotoUtils.getInstance().createImageFile(newfileName);
	}

	protected void setListen() {
		selectCameraOrAlbum();
		ivLeft.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(isNotHaveImage()){
					return;
				}
				rotate(270);
			}
		});
		ivCrop.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(isNotHaveImage()){
					return;
				}
				beginCrop(singleUri);
			}
		});
		ivRight.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(isNotHaveImage()){
					return;
				}
				rotate(90);
			}
		});
	}

	protected void initView() {

		ivShow = (ImageView) findViewById(R.id.contract_iv_show);
		ivLeft = (ImageView) findViewById(R.id.contract_iv_left);
		ivCrop = (ImageView) findViewById(R.id.contract_iv_crop);
		ivRight = (ImageView) findViewById(R.id.contract_iv_right);

		View image_title_back_common = findViewById(R.id.image_title_back_common);
		image_title_back_common.setVisibility(View.VISIBLE);
		image_title_back_common.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		TextView tv_title_common = (TextView) findViewById(R.id.tv_title_common);
		tv_title_common.setText(tName);
		Button btn_title_more_option = (Button) findViewById(R.id.btn_title_more_option);
		btn_title_more_option.setText("完成");
		btn_title_more_option.setVisibility(View.VISIBLE);
		btn_title_more_option.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				hasFinish = true;
				if(isNotHaveImage()){
					return;
				}
				File file = null;
				if (!isRotate) {
					file = PhotoUtils.getInstance().scal(singleUri, isCrop);
				} else {
					file = new File(singleUri.getPath());
				}
				singleUri = Uri.fromFile(file);
				String path = singleUri.getPath();
			
//				PackDao dao = new PackDao(bContext);
//				dao.addImagePath(label, path);
				Intent data = new Intent();
				data.putExtra(pictureKey, path);
				setResult(Config.CROP_IMAGE_RESULT_CODE, data);
				finish();
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode == PICK_FROM_CAMERA) {
				// 选择来自相机
				dealCamera(singleUri);
			} else if (requestCode == PICK_FROM_ALBUM) {
				// 选择来自相册
				if (data != null) {
					// singleUri = data.getData();// 图片的路径
					// dealCamera(singleUri);
					dealAlbum(data.getData());
				} else {
//					Loge("图片选择错误");
				}
			} else if (requestCode == CROP_FROM_CAMERA) {
				// 选择来自相机裁剪
				setImageView(singleUri.getPath());
				isCrop = true;
			} else if (requestCode == Crop.REQUEST_CROP) {
				handleCrop(resultCode, data);
				isCrop = true;
			}
		} else if (resultCode == RESULT_CANCELED) {

		} else {

		}
	}

	// 开始剪切
	private void beginCrop(Uri source) {
		// Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
		Crop.of(source, source).withMaxSize(3072, 3072).start(this);
	}
	
	private void crop(Uri uri) {
        int dp = 250;
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        cropIntent.setDataAndType(uri, "image/*");
        cropIntent.putExtra("crop", "true");

        cropIntent.putExtra("scale", true);// 去黑边
        cropIntent.putExtra("scaleUpIfNeeded", true);// 去黑边

        cropIntent.putExtra("aspectX", 1);//输出是X方向的比例
        cropIntent.putExtra("aspectY", 1);

        // outputX outputY 是裁剪图片宽高，切忌不要再改动下列数字，会卡死
        cropIntent.putExtra("outputX", dp);
        cropIntent.putExtra("outputY", dp);

//        intent.putExtra("outputFormat", "JPEG");
        cropIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        cropIntent.putExtra("noFaceDetection", true);
        cropIntent.putExtra("return-data", true);
        cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(cropIntent, Crop.REQUEST_CROP);
    }
	// 剪切完成
	private void handleCrop(int resultCode, Intent result) {
		if (resultCode == RESULT_OK) {
			ivShow.setImageURI(Crop.getOutput(result));
		} else if (resultCode == Crop.RESULT_ERROR) {
//			showToast(Crop.getError(result).getMessage());
			Toast.makeText(context, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
		}
	}

	// 选择相机还是相册的dialog
	private void selectCameraOrAlbum() {
		AlertDialog.Builder builder = new AlertDialog.Builder(context, AlertDialog.THEME_HOLO_LIGHT);
		String[] items = {"相机", "相册"};
		builder.setItems(items, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
					case 0 :
						openCamera();
						break;
					case 1 :
						openAlbum();
						break;
					default :
						break;
				}
			}
		});
		Dialog dialog = builder.create();
		dialog.show();
	}

	/**
	 * 相册
	 */
	private void openAlbum() {
		Intent takePictureIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
			Intent chooser = Intent.createChooser(takePictureIntent, "请选择相册");
			startActivityForResult(chooser, PICK_FROM_ALBUM);
		}
	}

	/**
	 * 相机
	 */
	private void openCamera() {
		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
			takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, singleUri);
			startActivityForResult(takePictureIntent, PICK_FROM_CAMERA);
		}
	}
	// 从相机中来的图片
	private void dealCamera(Uri uri) {
		String path = uri.getPath();
		setImageView(path);
	}
	// 从相册来的图片
	private void dealAlbum(Uri uri) {
		String[] proj = {MediaStore.Images.Media.DATA};
		Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
		int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		if (cursor.moveToFirst()) {
			String path = cursor.getString(column_index);
			// 复制
			PhotoUtils.getInstance().nioTransferCopy(path, singleUri.getPath());
			setImageView(singleUri.getPath());
		} else {
			Log.e("AI", "无图片");
		}
	}
	// 显示图片
	private void setImageView(String path) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = false;
		options.inSampleSize = 2;
		Bitmap bitmap = BitmapFactory.decodeFile(path, options);
		ivShow.setImageBitmap(bitmap);
	}

	// 旋转
	private void rotate(final int degrees) {
		mProgressDialog = DialogUtils.showProgressDialog(mProgressDialog, "提示", "正在旋转图片...", context);

		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				if (!isRotate) {
					PhotoUtils.getInstance().scal(singleUri, false);
					// PhotoUtils.getInstance().compress(singleUri.getPath(),
					// ContractImageActivity.this);

				}
				isRotate = true;
				Bitmap bitmap = BitmapFactory.decodeFile(singleUri.getPath());
				Bitmap bitmap2 = PhotoUtils.getInstance().rotateBitmap(bitmap, degrees);

				PhotoUtils.getInstance().saveBitmap(bitmap2, singleUri.getPath());

				Message msg = mHandler.obtainMessage();
				msg.what = 99;
				msg.obj = singleUri;
				mHandler.sendMessage(msg);
				SystemClock.sleep(100);
				DialogUtils.dismissProgressDialog(mProgressDialog);
			}
		}, 200);
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case 99 :
					Uri uri = (Uri) msg.obj;
					if (uri == null) {
//						showToast("错误了...");
						Toast.makeText(context, "错误了...", Toast.LENGTH_SHORT).show();
					} else {
						singleUri = uri;
						setImageView(singleUri.getPath());
					}
					break;

				default :
					break;
			}
			super.handleMessage(msg);
		}
	};

	/**
	 * 是否有图片
	 * 
	 * @date 2015-11-30下午1:43:23
	 * @return true:无图片;false:有图片
	 */
	private boolean isNotHaveImage() {
		if(ivShow.getDrawable() == null){
			selectCameraOrAlbum();
			return true;
		}
		return false;
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (!hasFinish) {
//			LogUtil.e(TConfig.Echo, "删除操作：" + singleUri.getPath());
			PhotoUtils.getInstance().deleteFile(singleUri.getPath());
		}
	}

}
