package com.tofly.ghrq_route.common.util.image;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import androidx.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;

import androidx.appcompat.app.AlertDialog;

import com.gaoyuan.weixinrecord.utils.PermissionHelper;
import com.mgq.base.utils.filepath.FilePath;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.C;
import com.tofly.ghrq_route.base.url.NetRequestURL;
import com.tofly.ghrq_route.common.ui.activity.CameraActivity;
import com.tofly.ghrq_route.common.ui.activity.CameraPreviewActivity;
import com.tofly.ghrq_route.common.util.date.DateUtils;
import com.tofly.ghrq_route.common.util.dialog.DialogUtil;
import com.tofly.ghrq_route.common.util.file.FileSizeUtil;
import com.tofly.ghrq_route.common.util.file.FileUtil;
import com.tofly.ghrq_route.common.util.file.MimeUtil;
import com.tofly.ghrq_route.module.trouble.domain.TroubleAudioBean;
import com.tofly.ghrq_route.module.trouble.domain.TroubleBean;
import com.tofly.ghrq_route.module.trouble.domain.TroublePictureBean;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Date;
import java.util.UUID;

import cn.hzw.graffiti.GraffitiActivity;
import cn.hzw.graffiti.GraffitiParams;
import cn.hzw.graffiti.WaterMarkParams;

import static android.app.Activity.RESULT_OK;

/**
 * Created by Amu on 2017/4/12.
 */

public class PhotoHelper {

    private Context mContext;

    private PhotoListener mListener;

    private DocumentListener mDocListener;

    private PermissionHelper permissionHelper;

    private VideoListener mVideoListener;

    private File tempFile;

    private Uri uriTempFile;

    private TroublePictureBean mPhotoReturn;

    private boolean mbIsNeedCrop = false;

    private boolean mbIsAddWatermark = false;

    private boolean mbIsSketch = false;

    private static final float GRAFFITI_PAINT_SIZE = 15.0f;

    private static final int IMAGE_REQUEST_CODE = 10;
    private static final int CAMERA_REQUEST_CODE = 11;
    private static final int CROP_REQUEST_CODE = 12;
    private static final int REQ_CODE_GRAFFITI = 13;
    public static final int REQ_CODE_GRAFFITI_SKETCH = 14;
    private static final int IMAGE_REQUEST_CODE_N = 15;
    private static final int CAMERA_REQUEST_CODE_N = 16;
    public static final int IMAGE_SCREEN_SHOT = 17;
    private static final int FILE_REQUEST_CODE = 18;

    private static final String GET_PHOTO_ERR = "获取图片失败";
    private static final String GET_PHOTO_OK = "获取图片成功";
    private static final String GET_PHOTO_NO_STORAGE = "未找到存储卡，无法存储照片";
    private static final String GET_PHOTO_NO_CAMERA_PERMISSION = "获取授权失败,无法拍摄";
    private static final String GET_FILE_ERR = "读取文件失败";
    private static final String GET_FILE_OK = "读取文件成功";

    private static final String GET_PHOTO_RECORD_ERROR = "视频录制出错";

    private static final String GET_PHOTO_RECORD_OK = "视频录制完成";

    private WaterMarkParams mWaterMarkParams = null;

    private ImageUtil imageUtil;

    public PhotoHelper(@NonNull Context context, @NonNull PermissionHelper helper){
        mContext = context;
        permissionHelper = helper;
        imageUtil = new ImageUtil(context);
    }

    public void requestCameraPhoto(@NonNull PhotoListener listener){
        requestCameraPhoto(false, false, null, listener);
    }

    public void requestCameraPhoto(boolean isNeedCrop, @NonNull PhotoListener listener){
        requestCameraPhoto(isNeedCrop, false, null, listener);
    }

    public void requestCameraPhoto(boolean isNeedWatermark, GetWatermarkParams paramsCallback, @NonNull PhotoListener listener){
        isNeedWatermark = BaseApp.getInstance().getIsPhotoWatermark() == 0;
        requestCameraPhoto(false, isNeedWatermark/*false*/, paramsCallback, listener);
    }

    public void requestCameraPhoto(boolean isNeedCrop, boolean isNeedWatermark, GetWatermarkParams paramsCallback, @NonNull PhotoListener listener){
        mListener = listener;
        mbIsNeedCrop = isNeedCrop;
        mbIsAddWatermark = isNeedWatermark;
        mbIsSketch = false;
        if (isNeedWatermark && paramsCallback != null){
            mWaterMarkParams = paramsCallback.onGetWatermarkParams();
            if (mWaterMarkParams == null)
                mbIsAddWatermark = false;
        }else
            mbIsAddWatermark = false;
        /*判断是否可以存储照片*/
        if (!FileUtil.SDState()){
            returnErr(GET_PHOTO_NO_STORAGE);
            return;
        }
        checkPermission();
    }

    private void checkPermission(){
        String cameraPermission = Manifest.permission.CAMERA;
        String storagePermission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
        permissionHelper.requestPermissions("请授予[拍摄]，[读写]权限，否则无法进行拍摄", new PermissionHelper.PermissionListener() {
            @Override
            public void doAfterGrand(String... permission) {
                startCameraShot();
            }

            @Override
            public void doAfterDenied(String... permission) {
                returnErr(GET_PHOTO_NO_CAMERA_PERMISSION);
            }
        }, cameraPermission, storagePermission);
    }

    public void requestImagePhoto(boolean isNeedCrop, boolean isNeedWatermark, GetWatermarkParams paramsCallback, @NonNull PhotoListener listener){
        mListener = listener;
        mbIsNeedCrop = isNeedCrop;
        mbIsAddWatermark = isNeedWatermark;
        mbIsSketch = false;
        if (isNeedWatermark && paramsCallback != null){
            mWaterMarkParams = paramsCallback.onGetWatermarkParams();
            if (mWaterMarkParams == null)
                mbIsAddWatermark = false;
        }else
            mbIsAddWatermark = false;
        getPicFromSysAlbums();
    }

    public void requestImagePhoto(@NonNull PhotoListener listener){
        requestImagePhoto(false, false, null, listener);
    }

    public void requestImagePhoto(boolean isNeedCrop, @NonNull PhotoListener listener){
        requestImagePhoto(isNeedCrop, false, null, listener);
    }

    public void requestImagePhoto(boolean isNeedWatermark, GetWatermarkParams paramsCallback, @NonNull PhotoListener listener){
        requestImagePhoto(false, isNeedWatermark, paramsCallback, listener);
    }

    public void requestSketchByFilePath(@NonNull String filePath, @NonNull PhotoListener listener){
        mbIsSketch = true;
        mListener = listener;
        startPhotoGraffiti(filePath);
    }

    public void requestDocumentFile(@NonNull DocumentListener listener){
        mDocListener = listener;
        getDocFromLibrary(null);
    }

    public void requestDocumentFile(String docPath, @NonNull DocumentListener listener){
        mDocListener = listener;
        getDocFromLibrary(docPath);
    }

    public void requestRecordSmallVideo(@NonNull VideoListener listener){
        mVideoListener = listener;
        checkRecordPermission();
    }

    public void requestPreviewVideo(String first_frame, String video_url, int video_length) {
        startPreviewVideo(first_frame, video_url, video_length);
    }

    private void checkRecordPermission(){
        String cameraPermission = Manifest.permission.CAMERA;
        String audioPermission = Manifest.permission.RECORD_AUDIO;
        String storagePermission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
        permissionHelper.requestPermissions("请授予[拍摄]，[录音]，[读写]权限，否则无法进行拍摄", new PermissionHelper.PermissionListener() {
            @Override
            public void doAfterGrand(String... permission) {
                startCameraRecord();
            }

            @Override
            public void doAfterDenied(String... permission) {
                returnVideoErr(GET_PHOTO_NO_CAMERA_PERMISSION);
            }
        }, cameraPermission, audioPermission, storagePermission);
    }

    private void startCameraShot(){
            // 激活相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra("android.intent.extra.quickCapture", true);
        // 判断存储卡是否可以用，可用进行存储
        tempFile = new File(FileUtil.tempFileDir(), FileUtil.RandFileName(".png"));
        Uri uriFile = FileUtil.getUri(mContext, tempFile);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uriFile);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
        Activity activity = (Activity) mContext;
        activity.startActivityForResult(intent, CAMERA_REQUEST_CODE);
    }

    private void getPicFromSysAlbums(){
        // 激活系统图库，选择一张图片
        Intent intent = new Intent();
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
        } else {
            intent.setAction(Intent.ACTION_GET_CONTENT);
        }
        intent.setType("image/*");
        Activity activity = (Activity) mContext;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            tempFile = new File(FileUtil.tempFileDir(), FileUtil.RandFileName(".png"));
            Uri uriFile = FileUtil.getUri(mContext, tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uriFile);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            activity.startActivityForResult(intent, IMAGE_REQUEST_CODE_N);
        }else {
            activity.startActivityForResult(intent, IMAGE_REQUEST_CODE);
        }
    }

    private void getDocFromLibrary(String docPath){
        // 激活文档目录，选择一个文件
        Intent intent = new Intent();
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
        } else {
            intent.setAction(Intent.ACTION_GET_CONTENT);
        }
        if (docPath != null && !docPath.isEmpty()) {
            File file = new File(docPath);
            //Uri initialUri = FileUtil.getUri(mContext, file);
            Uri initialUri = Uri.parse("content://" + file.getAbsolutePath());
            intent.setData(initialUri);
            //intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, initialUri);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        Activity activity = (Activity) mContext;

        activity.startActivityForResult(intent, FILE_REQUEST_CODE);
    }

    private void startCameraRecord() {
        Activity activity = (Activity) mContext;
        activity.startActivityForResult(new Intent(activity, CameraActivity.class), 100);
    }

    private void startPreviewVideo(String first_frame, String video_url, long video_length) {
//        if (first_frame == null || first_frame.isEmpty())
//            return;

        if (video_url == null || video_url.isEmpty())
            return;

        Activity activity = (Activity) mContext;
        Intent intent = new Intent(activity, CameraPreviewActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(CameraActivity.VIDEO_FIRST_FRAME_KEY, first_frame);
        bundle.putString(CameraActivity.VIDEO_VIDEO_URL_KEY, video_url);
        bundle.putLong(CameraActivity.VIDEO_VIDEO_LENGTH_KEY, video_length);
        intent.putExtras(bundle);
        activity.startActivityForResult(intent, 100);
    }

    //图片剪切
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setDataAndType(uri, "image/*");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }else {
            if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                String url = FilePath.getImageAbsolutePath(mContext, uri);//这个方法是处理4.4以上图片返回的Uri对象不同的处理方法
                intent.setDataAndType(Uri.fromFile(new File(url)), "image/*");
            } else {
                intent.setDataAndType(uri, "image/*");
            }
        }
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        //intent.putExtra("return-data", true);

        // 判断存储卡是否可以用，可用进行存储
        tempFile = new File(FileUtil.tempFileDir(), FileUtil.RandFileName(".png"));
        Uri uriFile = Uri.fromFile(tempFile);//FileUtil.getUri(mContext, mContext.getString(R.string.app_file_provider), tempFile);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uriFile);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        Activity activity = (Activity) mContext;
        activity.startActivityForResult(intent, CROP_REQUEST_CODE);
    }

    private void startPhotoGraffiti(Uri uri){

        String imagePath = FilePath.getImageAbsolutePath(mContext, uri);

        if (imagePath == null || imagePath.isEmpty()){
            returnErr(GET_PHOTO_ERR);
            return;
        }

        String pictureid = UUID.randomUUID().toString();
        String filetype = "jpg";
        String filename = pictureid + "." + filetype;
        String filepath = C.dir.images + filename;//保存的文件路径
        String time = DateUtils.getDate(new Date().getTime());
        mPhotoReturn = new TroublePictureBean();
        mPhotoReturn.setId(pictureid);
        mPhotoReturn.setFilepath(filepath);
        mPhotoReturn.setFiletype(filetype);
        mPhotoReturn.setStatus(TroubleBean.SAVED_STATE);
        mPhotoReturn.setCreateTime(time);

        // 涂鸦参数
        GraffitiParams params = new GraffitiParams();
        // 图片路径
        params.mImagePath = imagePath;
        //图片保存路径
        params.mSavePath = filepath;
        params.mPaintSize = GRAFFITI_PAINT_SIZE;

        /*
        // 橡皮擦底图，如果为null，则底图为当前图片路径
        params.mEraserPath = "/storage/emulated/0/tencent/MicroMsg/WeiXin/mmexport1485172092678.jpg";
        //  橡皮擦底图是否调整大小，如果为true则调整到跟当前涂鸦图片一样的大小．
        params.mEraserImageIsResizeable = true;
        // 设置放大镜的倍数，当小于等于0时表示不使用放大器功能.放大器只有在设置面板被隐藏的时候才会出现
        params.mAmplifierScale = 2.5f;
        */
        Activity activity = (Activity) mContext;
        if (mbIsAddWatermark){
            GraffitiActivity.startActivityForResult(activity, params, mWaterMarkParams, REQ_CODE_GRAFFITI);
        }else {
            GraffitiActivity.startActivityForResult(activity, params, null, REQ_CODE_GRAFFITI);
        }
    }

    private void startPhotoGraffiti(String filePath){

        String imagePath = filePath;

        if (imagePath == null || imagePath.isEmpty()){
            returnErr(GET_PHOTO_ERR);
            return;
        }

        String pictureid = UUID.randomUUID().toString();
        String filetype = "jpg";
        String filename = FileUtil.RandFileName(".jpg");
        String filepath = C.dir.images + filename;//保存的文件路径
        String time = DateUtils.getDate(new Date().getTime());
        mPhotoReturn = new TroublePictureBean();
        mPhotoReturn.setId(pictureid);
        mPhotoReturn.setFilepath(filepath);
        mPhotoReturn.setFiletype(filetype);
        mPhotoReturn.setStatus(TroubleBean.SAVED_STATE);
        mPhotoReturn.setCreateTime(time);

        // 涂鸦参数
        GraffitiParams params = new GraffitiParams();
        // 图片路径
        params.mImagePath = imagePath;
        //图片保存路径
        params.mSavePath = filepath;
        params.mPaintSize = GRAFFITI_PAINT_SIZE;

        /*
        // 橡皮擦底图，如果为null，则底图为当前图片路径
        params.mEraserPath = "/storage/emulated/0/tencent/MicroMsg/WeiXin/mmexport1485172092678.jpg";
        //  橡皮擦底图是否调整大小，如果为true则调整到跟当前涂鸦图片一样的大小．
        params.mEraserImageIsResizeable = true;
        // 设置放大镜的倍数，当小于等于0时表示不使用放大器功能.放大器只有在设置面板被隐藏的时候才会出现
        params.mAmplifierScale = 2.5f;
        */
        Activity activity = (Activity) mContext;
        if (mbIsAddWatermark){
            GraffitiActivity.startActivityForResult(activity, params, mWaterMarkParams, REQ_CODE_GRAFFITI_SKETCH);
        }else {
            GraffitiActivity.startActivityForResult(activity, params, null, REQ_CODE_GRAFFITI_SKETCH);
        }
    }

    /**
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public void handleActivityResult(int requestCode, int resultCode, Intent data){
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case IMAGE_REQUEST_CODE:
                    if (data != null) {
                        // 得到图片的全路径
                        Uri uri = data.getData();
                        if (mbIsNeedCrop){
                            startPhotoZoom(uri);
                        }else {
                            startPhotoGraffiti(uri);
                        }
                    }else {
                        returnErr(GET_PHOTO_ERR);
                    }
                    break;
                case IMAGE_REQUEST_CODE_N:
                    if (data != null) {
                        // 得到图片的全路径
                        String imagePath = FilePath.getImageAbsolutePath(mContext, data.getData());
                        if (imagePath != null && !imagePath.isEmpty()) {
                            File imageFile = new File(imagePath);
                            if (imageFile.exists()) {
                                Uri uri = FileUtil.getUri(mContext, imageFile);
                                if (mbIsNeedCrop){
                                    startPhotoZoom(uri);
                                }else {
                                    startPhotoGraffiti(imagePath);
                                }
                            }else {
                                returnErr(GET_PHOTO_ERR);
                            }
                        }else {
                            returnErr(GET_PHOTO_ERR);
                        }
                    }else {
                        returnErr(GET_PHOTO_ERR);
                    }
                    break;
                case CAMERA_REQUEST_CODE:
                    if (mbIsNeedCrop){
                        Uri uri = FileUtil.getUri(mContext, tempFile);
                        startPhotoZoom(uri);
                    }else {
                        startPhotoGraffiti(tempFile.getPath());
                    }
                    break;
                case CROP_REQUEST_CODE:
                    getImageToView(data);
                    break;
                case REQ_CODE_GRAFFITI:
                case REQ_CODE_GRAFFITI_SKETCH:
                    getGraffitiFile(data, resultCode);
                    break;
                case FILE_REQUEST_CODE:
                    if (data != null) {
                        // 得到图片的全路径
                        getDocFile(data, resultCode);
                    }else {
                        returnDocErr(GET_FILE_ERR);
                    }
                    break;
            }
        }else if (resultCode == CameraActivity.VIDEO_REQUEST_RECORD_CODE ||
                resultCode == CameraActivity.VIDEO_REQUEST_ERROR_CODE) {
            getVideo(data, resultCode);
        }
    }

    private void getDocFile(Intent data, int resultCode){
        if (data == null) {
            returnDocErr(GET_FILE_ERR);
            return;
        }

        if (resultCode == GraffitiActivity.RESULT_OK) {
            Uri uri = data.getData();
            String filePath = FileUtil.getPath(mContext, uri);

            if (filePath == null || filePath.isEmpty()){
                returnDocErr(GET_FILE_ERR);
                return;
            }

            TroubleAudioBean audioBean = new TroubleAudioBean();
            String audio_id = UUID.randomUUID().toString();
            audioBean.setId(audio_id);
            double fileSize = FileSizeUtil.getFileOrFilesSize(filePath, FileSizeUtil.SIZETYPE_KB);
            audioBean.setSecond((int) fileSize);
            audioBean.setPath(filePath);
            String fileType = MimeUtil.getMimeType(filePath);
            audioBean.setFiletype(fileType);
            String time = DateUtils.getDate(new Date().getTime());
            audioBean.setCreateTime(time);
            audioBean.setStatus(TroublePictureBean.PHOTO_LOCAL_STATE);

            returnDocData(true, GET_FILE_OK, audioBean);
        } else if (resultCode == GraffitiActivity.RESULT_ERROR) {
            returnDocErr(GET_FILE_ERR);
        }
    }

    private void getGraffitiFile(Intent data, int resultCode){
        if (data == null) {
            returnErr(GET_PHOTO_ERR);
            return;
        }
        if (resultCode == GraffitiActivity.RESULT_OK) {
            String path = data.getStringExtra(GraffitiActivity.KEY_IMAGE_PATH);
            if (TextUtils.isEmpty(path)) {
                returnErr(GET_PHOTO_ERR);
                return;
            }
            getImageToView(path);
            /*ImageLoader.getInstance(this).display(findViewById(R.id.img), path);
            mPath.setText(path);*/
        } else if (resultCode == GraffitiActivity.RESULT_ERROR) {
            returnErr(GET_PHOTO_ERR);
        }
    }

    private void getImageToView(String path) {
        boolean success = false;
        String errStr = GET_PHOTO_ERR;
        if (mPhotoReturn != null){
            mPhotoReturn.setFilepath(path);
            boolean bSaveOk = FileUtil.fileExists(path);
            if (bSaveOk) {
                success = true;
                errStr = GET_PHOTO_OK;
            }
        }

        returnData(success, errStr, mPhotoReturn);
    }

    private void getVideo(Intent data, int resultCode) {
        String errStr = GET_PHOTO_RECORD_ERROR;
        if (data == null) {
            returnVideoErr(errStr);
            return;
        }

        if (resultCode == CameraActivity.VIDEO_REQUEST_RECORD_CODE) {
            String firstFrame = data.getStringExtra(CameraActivity.VIDEO_FIRST_FRAME_KEY);
            String videoUrl = data.getStringExtra(CameraActivity.VIDEO_VIDEO_URL_KEY);
            long videoLength = data.getLongExtra(CameraActivity.VIDEO_VIDEO_LENGTH_KEY, 0);
            errStr = GET_PHOTO_RECORD_OK;

            TroublePictureBean picture = new TroublePictureBean();
            String pictureid = UUID.randomUUID().toString();
            String filetype = TroublePictureBean.FILE_VIDEO_TYPE;
            String time = DateUtils.getDate(new Date().getTime());
            picture.setId(pictureid);
            picture.setFiletype(filetype);
            picture.setFilepath(videoUrl);
            picture.setFilethumb(firstFrame);
            picture.setStatus(TroubleBean.SAVED_STATE);
            picture.setCreateTime(time);
            picture.setSecond(videoLength);

            returnVideoData(true, errStr, picture);
        }else if (resultCode == CameraActivity.VIDEO_REQUEST_ERROR_CODE) {
            returnVideoErr(errStr);
        }
    }

    private void getImageToView(Intent data) {
        boolean success = false;
        TroublePictureBean picture;
        String errStr = GET_PHOTO_ERR;
        String pictureid = UUID.randomUUID().toString();
        String filetype = "png";
        String filename = FileUtil.RandFileName(".png");
        String filepath = C.dir.images + filename;//保存的文件路径
        String time = DateUtils.getDate(new Date().getTime());
        if (data != null){
            Bitmap bitmap = null;
            Bundle bundle = data.getExtras();
            if (bundle != null) {
                bitmap = bundle.getParcelable("data");
            }
            if (bitmap == null) {
                try {
                    Uri uri = FileUtil.getUri(mContext, tempFile);
                    bitmap = BitmapFactory.decodeStream(mContext.getContentResolver().openInputStream(uri));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
            if (bitmap != null) {
                boolean bSaveOk = FileUtil.saveImage(bitmap, filename, false);//保存图片到sd卡
                if (bSaveOk) {
                    success = true;
                    errStr = GET_PHOTO_OK;
                    picture = new TroublePictureBean();
                    picture.setId(pictureid);
                    picture.setFiletype(filetype);
                    picture.setFilepath(filepath);
                    picture.setStatus(TroubleBean.SAVED_STATE);
                    picture.setCreateTime(time);
                    mPhotoReturn = picture;
                }
            }
        }

        returnData(success,errStr, mPhotoReturn);
    }

    public View getPhotoViewFromPath(final TroublePictureBean picture, final PhotoClickListener listener){
        View rootView = imageUtil.getViewFromPath(picture.getFilepath());
        if (rootView == null)
            return null;

        rootView.setTag(picture);
        if (listener != null){
            rootView.setOnLongClickListener(view -> {
                String title = "删除图片";
                String content = "是否删除图片?";
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle(title);
                builder.setMessage(content);
                builder.setPositiveButton(android.R.string.ok, (dialog, which) -> {
                    TroublePictureBean pictureBean = (TroublePictureBean) view.getTag();
                    if (pictureBean != null)
                        pictureBean.setStatus(TroublePictureBean.PHOTO_DELETED_STATE);
                    String picPath = pictureBean.getFilepath();
                    if (imageUtil != null)
                        imageUtil.removePic(picPath);
                    if (listener != null)
                        listener.onRemovePhoto(view, picture);
                });
                builder.setNegativeButton(android.R.string.cancel, null);
                builder.show();
                return true;
            });
        }
        return rootView;
    }

    public View getPhotoViewFromPath(final String filepath){
        View rootView = imageUtil.getViewFromPath(filepath);
        if (rootView == null)
            return null;

        rootView.setTag(filepath);
        return rootView;
    }


    public View getPhotoViewFromUrl(final TroublePictureBean picture, final PhotoClickListener listener){
        String fileurl = picture.getFileurl();
        String realurl = NetRequestURL.newApi_dyrq.getFormattedPicture(fileurl);
        View rootView = imageUtil.getViewFromUrl(picture, realurl);

        if (rootView == null)
            return null;

        if (listener != null){
            rootView.setOnLongClickListener(view -> {
                String title = "删除图片";
                String content = "是否删除图片?";
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle(title);
                builder.setMessage(content);
                builder.setPositiveButton(android.R.string.ok, (dialog, which) -> {
                    TroublePictureBean pictureBean = (TroublePictureBean) view.getTag();
                    String picPath = pictureBean.getFilepath();
                    if (picPath != null && !picPath.isEmpty()) {
                        if (FileUtil.fileExists(picPath)) {
                            FileUtil.deleteFile(picPath);
                        }
                    }
                    if (imageUtil != null)
                        imageUtil.removePic(picPath);
                    if (listener != null)
                        listener.onRemovePhoto(view, picture);
                });
                builder.setNegativeButton(android.R.string.cancel, null);
                builder.show();
                return true;
            });
        }
        return rootView;
    }

    public View getPhotoViewFromUrl(final String fileurl){
        View rootView = imageUtil.getViewFromUrl(fileurl);
        if (rootView == null)
            return null;

        return rootView;
    }

    public View getVideoViewFromPath(TroublePictureBean picture, final PhotoClickListener listener) {
        String first_frame = picture.getFilethumb();
        String video_path = picture.getFilepath();
        long videoLength = picture.getSecond();
        View rootView = imageUtil.getViewFromPath(first_frame, true, videoLength);
        rootView.setOnClickListener(v -> startPreviewVideo(first_frame, video_path, videoLength));
        rootView.setTag(video_path);
        if (listener != null) {
            rootView.setOnLongClickListener(view -> {
                showDeleteFileDialog((dialog, which) -> {
                    TroublePictureBean pictureBean = (TroublePictureBean) view.getTag();
                    String picPath = pictureBean.getFilepath();
                    String thumbPath = pictureBean.getFilethumb();
                    FileUtil.deleteFile(picPath);
                    FileUtil.deleteFile(thumbPath);
                    listener.onRemovePhoto(view, picture);
                });
                return true;
            });
        }
        return rootView;
    }

    public void showDeleteFileDialog(DialogInterface.OnClickListener clickListener) {
        String title = "删除文件";
        String content = "是否删除文件?";
        DialogUtil.showAlertWithConfirmCancelButton(mContext, title, content, true, clickListener);
    }

    public void clearAllImages() {
        imageUtil.clearPicList();
    }

    public interface PhotoListener {
        void getPhoto(boolean success, String errStr, TroublePictureBean picture);
    }

    public interface PhotoViewListener {
        void getPhotoView(TroublePictureBean picture, View photoView);
    }

    public interface PhotoRemoveListener {
        void onRemovePhoto(TroublePictureBean picture, View photoView);
    }

    public interface DocumentListener {
        void getDocument(boolean success, String errStr, TroubleAudioBean document);
    }

    public interface PhotoClickListener{
        void onRemovePhoto(View view, TroublePictureBean picture);
    }

    public interface GetWatermarkParams{
        WaterMarkParams onGetWatermarkParams();
    }

    public interface VideoListener {
        void getVideo(boolean success, String errStr, TroublePictureBean pictureBean);
    }

    private void returnData(boolean sucess, String errStr, TroublePictureBean pictureBean){
        if (mListener != null){
            mListener.getPhoto(sucess, errStr, pictureBean);
        }
    }

    private void returnErr(String errStr){
        returnData(false, errStr, null);
    }

    private void returnDocData(boolean sucess, String errStr, TroubleAudioBean document){
        if (mDocListener != null){
            mDocListener.getDocument(sucess, errStr, document);
        }
    }

    private void returnDocErr(String errStr){
        returnDocData(false, errStr, null);
    }

    private void returnVideoData(boolean success, String errStr, TroublePictureBean pictureBean) {
        if (mVideoListener != null){
            mVideoListener.getVideo(success, errStr, pictureBean);
        }
    }

    private void returnVideoErr(String errStr) {
        returnVideoData(false, errStr, null);
    }
}
