package com.zxhl.cms.utils;

import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.zxhl.cms.AppContext;
import com.zxhl.cms.R;
import com.zxhl.cms.common.Constant;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by gaoleichao on 2018/6/7.
 */

public class PhotoUtils {

    public final static int REQUESTCODE_CAPTURE = 201;
    public final static int REQUESTCODE_CROP = 301;
    public final static int REQUESTCODE_GALLERY = 101;

    public static String CAMER = "android.permission.CAMERA";

    public static Uri fromCapture(Activity context, String filePath, String fileName) {

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//拍摄照片
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        Uri uri;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            uri = Uri.fromFile(new File(file, fileName));
        } else {
            uri = FileProvider.getUriForFile(context, Constant.Param.mPacketName + ".fileprovider", new File(file, fileName));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        PackageManager pm = context.getPackageManager();
        ComponentName cn = intent.resolveActivity(pm);
        if (cn == null) {
            Toast.makeText(context, "请检查相机是否可用", Toast.LENGTH_SHORT).show();
        } else {
            context.startActivityForResult(intent, REQUESTCODE_CAPTURE);
        }
        return uri;
    }

    public static void takePicture(Activity context) {
        //调用系统相机
        Intent intentCamera = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intentCamera.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
        }
        intentCamera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);

        //将拍照结果保存至photo_file的Uri中，不保留在相册中
//        intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        if (context != null) {
            context.startActivityForResult(intentCamera, REQUESTCODE_CAPTURE);
        }
    }

    public static void startPhotoCrop(Context context, File fileUri, int aspectX, int aspectY, int outputX, int outputY, String filePath, String fileName, Uri uris) {
        /*
         * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页
         * yourself_sdk_path/docs/reference/android/content/Intent.html
         * 直接在里面Ctrl+F搜：CROP ，之前没仔细看过，其实安卓系统早已经有自带图片裁剪功能, 是直接调本地库的
         */
        Intent intent = new Intent("com.android.camera.action.CROP");

        Uri uri;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            uri = Uri.fromFile(fileUri);
        } else {
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            uri = getImageContentUri(context, fileUri);
        }
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", aspectX);
        intent.putExtra("aspectY", aspectY);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("crop", true);
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra("return-data", false);
//        File file = new File(filePath);
//        if (!file.exists()) {
//            file.mkdirs();
//        }
        Uri outUri = Uri.fromFile(new File(filePath + File.separator + fileName));
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outUri);

        PackageManager pm = AppContext.get().getPackageManager();
        ComponentName cn = intent.resolveActivity(pm);
        if (cn == null) {
            // 没有相应的页面来处理请求
            Utils.showToast(AppContext.get(), AppContext.get().getString(R.string.album_not_available));
        } else {


            ((Activity) context).startActivityForResult(intent, REQUESTCODE_CROP);
        }
    }

    /**
     * 读取图片属性：旋转的角度
     *
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return degree;
        }
        return degree;
    }

    /**
     * 旋转图片，使图片保持正确的方向。
     *
     * @param degrees 原始图片的角度
     * @return Bitmap 旋转后的图片
     */
    public static Bitmap rotateBitmap(String path, int degrees) {
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        if (degrees == 0 || null == bitmap) {
            return bitmap;
        }
        Matrix matrix = new Matrix();
        matrix.setRotate(degrees);
        Bitmap bmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        if (null != bitmap) {
            bitmap.recycle();
        }
        return bmp;
    }

    public static boolean writeBitmapToPath(Bitmap bitmap, String filePath, String fileName) {
        if (bitmap == null || TextUtils.isEmpty(filePath) || TextUtils.isEmpty(fileName)) {
            return false;
        }
        FileOutputStream fos = null;
        ByteArrayOutputStream out = null;
        try {
            File pathFile = new File(filePath);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }

            File file = new File(filePath + fileName);
            if (file.exists()) {
                file.delete();
                file.createNewFile();
            }

            out = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            fos = new FileOutputStream(file);
            out.writeTo(fos);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
                if (out != null) {
                    out.flush();
                    out.close();
                }
                bitmap.recycle();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID},
                MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

}
