package com.gingersoft.supply_chain.mvp.utils;//package com.gingersoft.supply_chain.mvp.utils;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.OpenableColumns;

import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import com.gingersoft.gsa.cloud.common.utils.FileUtils;
import com.gingersoft.gsa.cloud.common.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.common.utils.toast.ToastUtils;
import com.gingersoft.gsa.cloud.ui.utils.AppDialog;
import com.permissionx.guolindev.PermissionX;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 宇航.
 * User: admin
 * Date: 2020/12/25
 * Time: 11:29
 * Use:
 */
public class SelectPicture {
    private static SelectPicture selectPicture;
    /**
     * 用于保存拍照图片的uri
     */
    private Uri mCameraUri;
    /**
     * 當前圖片的絕對路徑
     */
//    private String currentPhotoPath;
    final String[] items = new String[]{"拍照", "從相冊選擇"};
    public static final int CHOOSE_PHOTO = 101;
    public static final int TAKE_PHOTO = 102;
    public static final int PHOTO_CROP = 103;

    public static SelectPicture getInstance() {
        if (selectPicture == null) {
            selectPicture = new SelectPicture();
        }
        return selectPicture;
    }

    /**
     * 顯示方式
     */
    public void showSelectType(Fragment fragment) {
        //拍照或者選擇圖片
        PermissionX.init(fragment).permissions(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                .onExplainRequestReason((scope, deniedList) -> scope.showRequestReasonDialog(deniedList, "上傳圖片需要讀取文件權限", "確定", "取消"))
                .onForwardToSettings((scope, deniedList) -> scope.showForwardToSettingsDialog(deniedList, "您需要去設置當中開啟讀取文件權限", "確定", "取消"))
                .request((allGranted, grantedList, deniedList) -> showPictureChoice(fragment));
    }

    /**
     * 顯示方式
     *
     * @param activity
     */
    public void showSelectType(FragmentActivity activity) {
        //拍照或者選擇圖片
        PermissionX.init(activity).permissions(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                .onExplainRequestReason((scope, deniedList) -> scope.showRequestReasonDialog(deniedList, "上傳圖片需要讀取文件權限", "確定", "取消"))
                .onForwardToSettings((scope, deniedList) -> scope.showForwardToSettingsDialog(deniedList, "您需要去設置當中開啟讀取文件權限", "確定", "取消"))
                .request((allGranted, grantedList, deniedList) -> showPictureChoice(activity));
    }

    /**
     * 顯示照片選擇
     */
    public void showPictureChoice(Fragment fragment) {
        AppDialog.getInstance().showListDialog(fragment.requireContext(), items, (view, dialog, position) -> {
            if (position == 0) {
                takePhoto(fragment);
            } else if (position == 1) {
                Intent intentToPickPic = new Intent(Intent.ACTION_PICK, null);
                intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                fragment.startActivityForResult(intentToPickPic, CHOOSE_PHOTO);
            }
        });
    }

    /**
     * 顯示照片選擇
     */
    public void showPictureChoice(FragmentActivity activity) {
        AppDialog.getInstance().showListDialog(activity, items, (view, dialog, position) -> {
            if (position == 0) {
                takePhoto(activity);
            } else if (position == 1) {
                Intent intentToPickPic = new Intent(Intent.ACTION_PICK, null);
                intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                activity.startActivityForResult(intentToPickPic, CHOOSE_PHOTO);
            }
        });
    }

    /**
     * 拍照
     */
    private void takePhoto(Activity activity) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(activity.getPackageManager()) != null) {
            File photoFile;
            photoFile = createImageFile(activity);
            mCameraUri = Uri.fromFile(photoFile);
            try {
                Uri photoUri = FileProvider.getUriForFile(activity,
                        activity.getPackageName() + ".fileprovider", photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                activity.startActivityForResult(takePictureIntent, TAKE_PHOTO);
            } catch (IllegalArgumentException e) {
                ToastUtils.show(activity, "打開相機失敗，請更換其他方式");
            }

        } else {
            ToastUtils.show(activity, "請安裝相機");
        }
    }

    /**
     * 拍照
     */
    private void takePhoto(Fragment fragment) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(fragment.requireContext().getPackageManager()) != null) {
            File photoFile;
            photoFile = createImageFile(fragment.requireContext());
//                currentPhotoPath = image.getAbsolutePath();
            mCameraUri = Uri.fromFile(photoFile);
            try {
                Uri photoUri = FileProvider.getUriForFile(fragment.requireActivity(),
                        fragment.requireActivity().getPackageName() + ".fileprovider", photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                fragment.startActivityForResult(takePictureIntent, TAKE_PHOTO);
            } catch (IllegalArgumentException e) {
                ToastUtils.show(fragment.requireContext(), "打開相機失敗，請更換其他方式");
                e.printStackTrace();
            }
        } else {
            ToastUtils.show(fragment.requireContext(), "請安裝相機");
        }
    }

    /**
     * 創建照片保存路徑,然後再進行拍照
     */
    public File createImageFile(Context mContext) {
        // Create an image file name
        String timeStamp = TimeUtils.DEFAULT_DATE_FORMAT_YMDHM.format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File cacheDir = mContext.getCacheDir();
        File image = null;
        try {
            image = File.createTempFile(
                    imageFileName,  /* prefix */
                    ".jpg",         /* suffix */
                    cacheDir      /* directory */
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
        // Save a file: path for use with ACTION_VIEW intents
//        currentPhotoPath = image.getAbsolutePath();
//        mCameraUri = Uri.fromFile(image);
        return image;
    }

    /**
     * 創建照片保存路徑,然後再進行拍照
     */
    public File createImageFile2(Context mContext) {
        String image = mContext.getCacheDir() + File.separator + "purchase" + File.separator + "images" + File.separator + System.currentTimeMillis() + ".jpg";
        File outputFile = new File(image);
        if (!outputFile.exists()) {
            outputFile.mkdir();
        }
        return outputFile;
    }


    /**
     * uri轉換為文件路徑，適配android Q
     *
     * @param uri 私有uri
     * @return 轉換到沙盒文件的文件
     */
    public File uriToFileApiQ(Context mContext, Uri uri) {
        File file = null;
        //android10以上转换
        String scheme = uri.getScheme();
        if (scheme != null) {
            if (scheme.equals(ContentResolver.SCHEME_FILE)) {
                String path = uri.getPath();
                if (path != null) {
                    file = new File(path);
                }
            } else if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
                //把文件复制到沙盒目录
                ContentResolver contentResolver = mContext.getContentResolver();
                Cursor cursor = contentResolver.query(uri, null, null, null, null);
                if (cursor != null && cursor.moveToFirst()) {
                    String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                    try {
                        InputStream is = contentResolver.openInputStream(uri);
                        File externalCacheDir = mContext.getExternalCacheDir();
                        if (externalCacheDir != null) {
                            File cache = new File(mContext.getExternalCacheDir().getAbsolutePath(), Math.round((Math.random() + 1) * 1000) + displayName);
                            FileOutputStream fos = new FileOutputStream(cache);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && is != null) {
                                android.os.FileUtils.copy(is, fos);
                            } else {
                                String path = FileUtils.getFilePathByUri(mContext, uri);
                                FileUtils.copyFile(path, cache.getPath());
                            }
                            file = cache;
                            fos.close();
                        }
                        if (is != null) {
                            is.close();
                        }
                        cursor.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        }
        return file;
    }

    /**
     * 裁剪
     *
     * @param mCameraUri
     */
    public void crop(Uri mCameraUri, Fragment fragment) {
        UCrop.of(mCameraUri, mCameraUri)
                .withAspectRatio(1, 1)
                .withMaxResultSize(500, 500)
                .start(fragment.requireContext(), fragment);
    }

    public Uri getmCameraUri() {
        return mCameraUri;
    }
}

