package com.rv.home.rv.module.basic.presenter;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;


import com.base.utils.ui.datetime.selector.util.TextUtil;
import com.ruiwenliu.wrapper.util.FileStorage;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;

/**
 * Created by Amuse
 * Data:2018/12/28 0028
 * Desc:照相、图片选择
 */

public class PickerPresenter extends CommonPresenter {
    public final int TYPE_CAMERA_CODE = 1001;//照相
    public final int TYPE_ALBUM_CODE = 1002;//相册
    public final int TYPE_CAMERA_CROP_CODE = 1003;//照相并裁剪
    public final int TYPE_ALBUM_CROP_CODE = 1004;//相册并裁剪
    public final int TYPE_CROP_CODE = 1005;//裁剪后的结果
    private String cameraUrl;
    private File imageFile;
    private Uri cropUri;
    public FileStorage fileStore = null;
    private Uri outputUri;

    /**
     * 打开系统相机获取图片
     */
    public void openCamera(boolean isCrop) {
        imageFile = getFileStore().createCameraFile();
        if (imageFile == null || isViewAttached() == false) { //当地址存储为空或未绑定Activity 、fragment则不执行下面操作
            return;
        }
        /*调用系统拍照*/
        Intent intent = new Intent();
        cropUri = null;
        try {
            //API>=24 android 7.0
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                cropUri = FileProvider.getUriForFile(getPresenterContext(), getPresenterContext().getPackageName() +".fileProvider", imageFile);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
            } else {//<24
                cropUri = Uri.fromFile(imageFile);
            }
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
            intent.putExtra(MediaStore.EXTRA_OUTPUT, cropUri);
//            cameraUrl = String.format("%1$s%2$s", "file://", imageFile.getPath());//相机存储地址

            cameraUrl = String.format("%1$s", imageFile.getPath());//相机存储地址
            ((Activity) getPresenterContext()).startActivityForResult(intent, isCrop ? TYPE_CAMERA_CROP_CODE : TYPE_CAMERA_CODE);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得相机存储地址
     *
     * @return
     */
    public String gerCameraStoreUrl() {
       if (new File(cameraUrl).exists()) {
           return cameraUrl;
       }
       return "";
    }

    /**
     * 打开系统相册获取图片
     */
    public void openAlbum(boolean isCrop) {
        if (isViewAttached() == false) { //当地址存储为空或未绑定Activity 、fragment则不执行下面操作
            return;
        }
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        ((Activity) getPresenterContext()).startActivityForResult(intent, isCrop ? TYPE_ALBUM_CROP_CODE: TYPE_ALBUM_CODE);
    }

    /**
     * 获得uri String 地址
     *
     * @param uri
     * @return
     */
    public String getUriUrl(Uri uri) {
        if (uri != null) {
            return uri.toString();
        }
        return "";
    }


    public Uri getCropUri() {
        return cropUri;
    }

    /**
     * 调用系统裁剪功能
     */
    public void cropPhoto(Uri uri) {
        File file = new FileStorage().createCropFile();
        if (file == null && isViewAttached() == false) { //当地址存储为空或未绑定Activity 、fragment则不执行下面操作
            return;
        }
        outputUri = Uri.fromFile(file);//缩略图保存地址
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX",200);
        intent.putExtra("outputY", 200);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
//        cameraUrl = String.format("%1$s%2$s", "file://", outputUri.getPath());//相机存储地址
        cameraUrl = String.format("%1$s", outputUri.getPath());//相机存储地址
        ((Activity)  getPresenterContext()).startActivityForResult(intent, TYPE_CROP_CODE);
    }


    /**
     * 获取图片存储地址
     * @return
     */
    public FileStorage getFileStore() {

        if (fileStore == null) {
            fileStore = new FileStorage();
        }
        return fileStore;
    }


    /**
     * 根据路径获得图片信息并按比例压缩，返回bitmap
     */
    public File getSmallBitmap(String filePath) {
        File file=new File(filePath);//将要保存图片的路径
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;//只解析图片边沿，获取宽高
        BitmapFactory.decodeFile(filePath, options);
        // 计算缩放比
        options.inSampleSize = calculateInSampleSize(options, 200, 200);
        // 完整解析图片返回bitmap
        options.inJustDecodeBounds = false;
        Bitmap bitmap= BitmapFactory.decodeFile(filePath, options);
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
//        return BitmapFactory.decodeFile(filePath, options);
    }


    public  int calculateInSampleSize(BitmapFactory.Options options,
                                      int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }



//    public File getUrlFile(Uri uri){
//        File file = null;   //图片地址
//        try {
//            file = new File(new URI(uri));
//        } catch (URISyntaxException e) {
//            e.printStackTrace();
//        }
//      return file;
//    }
    /**
     * Try to return the absolute file path from the given Uri
     *
     * @param uri
     * @return the file path or null
     */
    public  String getRealFilePath( final Uri uri ) {
        if ( null == uri ) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if ( scheme == null )
            data = uri.getPath();
        else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
            data = uri.getPath();
        } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
            Cursor cursor =getPresenterContext().getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );
            if ( null != cursor ) {
                if ( cursor.moveToFirst() ) {
                    int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
                    if ( index > -1 ) {
                        data = cursor.getString( index );
                    }
                }
                cursor.close();
            }
        }
        return data;
    }
}
